Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AES decryption in iOS: PKCS5 padding and CBC

Tags:

padding

ios

aes

I am implementing for iOS some decryption code for a message originating on a server over which I have no control. A previous implementation on another platform documents the decryption requirements AES256, specifies the key and the initialization vector, and also says:

 * Cipher Mode: CBC
 * Padding: PKCS5Padding

The options for creation of a CCCryptor object include only kCCOptionPKCS7Padding and kCCOptionECBMode, noting that CBC is the default. From what what I understand about padding for encryption, I don't understand how one might use both; I thought they were mutually exclusive. In creating a CCCryptor for the decryption, I have tried using both a 0 for options and kCCOptionPKCS7Padding, but both give me gibberish after decryption.

I have compared the dump of this decryption with a dump of the decoded byte buffer on the other platform and confirmed that they really are different. So there is something that I am doing different in this implementation that is significantly different, I just don't know what... And don't have a clue as to how to get a handle on it. The platforms are different enough that it is difficult to infer much from the previous implementation because it is based on a very different platform. And of course, the author of the previous implementation has since departed.

Any guesses what else could be incompatible or how to troubleshoot this thing?

like image 700
Paul Mailman Avatar asked Feb 09 '11 22:02

Paul Mailman


1 Answers

PKCS#5 padding and PKCS#7 padding are practically the same (adding bytes 01, or 0202, or 0303 etc up to the length of the block size of the algorithm, 16 bytes in this case). Officially PKCS#5 padding should only be used for 8 byte blocks, but in many runtimes the two can be interchanged without issue. Padding always occurs at the end of the ciphertext, so if you get just gibberish it's not the padding. ECB is a block mode of operation (that should not be used to encrypt data that can be distinguished from random numbers) : it would require padding, so the two are not mutually exclusive.

Finally, if you just perform decryption (not MAC'ing or other forms of integrity control), and you return the result of the unpadding to the server (decryption failed), your plain text data is not safe because of padding oracle attacks.

like image 178
Maarten Bodewes Avatar answered Oct 13 '22 15:10

Maarten Bodewes