Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PKCS5 padding in Objective-C

Is there any way of getting actual PKCS5 padding in Cocoa Touch? While I'm well aware that for decryption purposes, PKCS7 and PKCS5 are compatible, but I need to match the exact encryption method that the server uses, since the encrypted password is hashed and used as a decryption key for encrypted data. It's quite convoluted, but it's pretty secure. Unfortunately, I don't think PKCS7 and PKCS5 can be used interchangeably if you're hashing the padded strings afterwards. Can anyone help me? Bonus points if it works decently with the NSData+CommonCrypto or RNCryptor libraries.

like image 279
zhbrass Avatar asked Oct 08 '22 02:10

zhbrass


1 Answers

Here's my solution. Worked like a charm.

NSString *password = @"YOUR PASSWORD HERE";
NSMutableData *passwordData = [[NSMutableData alloc] initWithData:[password dataUsingEncoding:NSUTF8StringEncoding]];
int blockSize = 16;
int charDiv = blockSize - ((passwordData.length + 1) % blockSize);

//PKCS5 Padding
NSMutableString *padding = [[NSMutableString alloc] initWithFormat:@"%c",(unichar)10];

for (int c = 0; c <charDiv; c++) {
    [padding appendFormat:@"%c",(unichar)charDiv];
}
[passwordData appendData:[padding dataUsingEncoding:NSUTF8StringEncoding]];

...and your padded data will be in passwordData.

like image 63
zhbrass Avatar answered Oct 12 '22 23:10

zhbrass