How can I do this same encrypt/decrypt PHP function on iOS with Objective-C?

encryption, ios, objective-c, php

Solution

So you want to encrypt using AES256 in CBC mode. The library you are looking for is CommonCrypto and you can find a good article about it here:http://robnapier.net/aes-commoncrypto.

You will also need an MD5 function that you can find here: http://www.makebetterthings.com/iphone/how-to-get-md5-and-sha1-in-objective-c-ios-sdk/

Your code should look something like this:

NSString *originalString,*keyString;
NSData *key = [[self md5:keyString] dataUsingEncoding:NSUTF8StringEncoding];
NSData *iv = [[self md5:[self md5:key]] dataUsingEncoding:NSUTF8StringEncoding];
NSData *data = [originalString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *cipherData = [NSMutableData dataWithLength:data.length + kCCBlockSizeAES128]; //The block size of MCRYPT_RIJNDAEL_256 is just like AES128
size_t outLength;

CCCryptorStatus result
       = CCCrypt(kCCEncrypt, // operation, replace with kCCDecrypt to decrypt
                 kCCAlgorithmAES, // Same as MCRYPT_RIJNDAEL_256
                 nil, // CBC mode
                 key.bytes, // key
                 32, // Since you are using AES256
                 iv.bytes,// iv
                 data.bytes, // dataIn
                 data.length, // dataInLength,
                 cipherData.mutableBytes, // dataOut
                 cipherData.length, // dataOutAvailable
                 &outLength); // dataOutMoved
NSString resultString = [cipherData base64Encoding];

And make sure you are using the same UTF8 encoding in both cases, and use this import:

#import <CommonCrypto/CommonCryptor.h>

I am pretty sure this should work.

EDIT: the key length should be 32 since you are using AES256 256bit=32bytes. The MD5 output wouldn't match this length by default I think.

Problem

I have a function in PHP that encrypts and decrypts strings: ``` function encrypt_decrypt($action, $string) { $output = false; $key = 'mykeyhereblah'; $iv = md5(md5($key)); if( $action == 'encrypt' ) { $output = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, $iv); $output = base64_encode($output); } else if( $action == 'decrypt' ){ $output = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, $iv); $output = rtrim($output, ""); } return $output; } ``` and I call it like this: ``` echo encrypt_decrypt('decrypt', '2Fa9cICuUFa/UnmAAa5FjXZK4ht9q3cN2qgk1pCvDSs='); ``` How can I do this exact same thing on iOS with Objective-C for an `NSString`? It needs to be compatible with this PHP function.

Original source

Related problems