views:

67

answers:

2

I'm trying to encrypt data to be transferred back and fourth between a server but I can't seem to get the right output in objective-c: (full code here: http://pastebin.com/zPdHxShu)

 // 128-bit key, CBC mode
 // ------------------------
 // IV = '1234567890123456'  
 //  (hex: 31323334353637383930313233343536)
 // Key = '1234567890123456'  
 //  (hex: 31323334353637383930313233343536)
 // PlainText:
 //  'The quick brown fox jumped over the lazy dog'
 // CipherText(hex):
 //  f78176ae 8dfe8457 8529208d 30f446bb b29a64dc 388b5c0b 63140a4f 316b3f34 1fe7d3b1 a3cc5113 c81ef8dd 714a1c99 // correct output
 //  f78176ae 8dfe8457 8529208d 30f446bb b29a64dc 388b5c0b 63140a4f 316b3f34 50f18175 f7a3ad06 2d8033cc d092ca6a // my output
    //                                                                       ^^^ start to get different output here
 //  Note: I get this output in php no problem.
+1  A: 

The iPhone is using a standard padding scheme, PKCS5 padding. The output you have labelled as "correct" is using zero padding. I'm not familiar with CCCrypt, but I think if replace kCCOptionPKCS7Padding with 0, and do you own padding with binary zeros, you'll get the same answer.

GregS
Just know that zero-padding is almost always the wrong solution :-)
St3fan
@GregS, do you have any sample code to point me in the right direction?
Joseph Stein
Agree with @St3fan - the proper solution is to change the PHP side to use PKCS#5 padding, which is easy enough.
caf
Felt the need to add myself to the chorus against zero-padding.
imaginaryboy
@St3fan, @caf, @imaginary: agree completely, zero padding is brain-dead, but sometimes you must work with broken code.
GregS
you guys are lifesavers...I've been breaking my head on this for almost a week now. I manipulated the php side to use pkcs7padding and it worked!
Joseph Stein
+1  A: 

You should change the PHP side to pad the plaintext using PKCS#5 padding - then you should get the same result. You can use this function (passing a $blocksize of 16) on the plaintext before encryption:

function pkcs5_pad ($text, $blocksize)
{
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}
caf
yea i had already figured this out. thanks though
Joseph Stein