It was somewhat not straight forward getting this task done initially for me, but finally everything was fine with Objective-C & PHP on decrypting the text encrypted via iOS code with the help of Google & StackOverflow. So I thought of sharing successful piece of codes for iOS and PHP for this task on my blog. The problem with PHP is PHP does not support PKCS7Padding by default which is supported by iOS. So we need to unpad the encrypted text to make decryption successful at PHP code.
On Objective-C, we will extend NSData class and NSString class to have an AES128 encrypted string on iOS using categories. Basically, important AES128 Encryption code is listed below. But for easy reference, download NSData,NSString AES128 Categories from here. and add them to XCode project.
– (NSData *)AES128EncryptWithKey:(NSString *)key
// ‘key’ should be 16 bytes for AES128
char keyPtr[kCCKeySizeAES128 + 1]; // room for terminator (unused)
bzero( keyPtr, sizeof( keyPtr ) ); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof( keyPtr ) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That’s why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc( bufferSize );
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt( kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode | kCCOptionPKCS7Padding,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
if( cryptStatus == kCCSuccess )
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
free( buffer ); //free the buffer
Now add the below PHP function at your server side to decrypt the text with PHP.
$base64encoded_ciphertext = $pass;
$res_non = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($base64encoded_ciphertext), ‘ecb’);
$decrypted = $res_non;
$dec_s2 = strlen($decrypted);
$padding = ord($decrypted[$dec_s2-1]);
$decrypted = substr($decrypted, 0, -$padding);