The PHP API Im calling from my iOS application requires the payload to be encrypted in a certain way. Im having problems replicating this approach in Objective-C, with RNCryptor.
Here is the PHP code used to encrypt the string:
function encrypt($string) {
$key = 'some-random-key';
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
}
And this is how I try to achieve the same encryption result in Objective-C:
+ (NSData*)encryptData:(NSData*)sourceData {
NSString *keyString = @"some-random-key";
NSData *key = [[keyString MD5String] dataUsingEncoding:NSUTF8StringEncoding];
NSData *iv = [[[keyString MD5String] MD5String] dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *encryptedData = [NSMutableData data];
RNCryptorEngine *cryptor = [[RNCryptorEngine alloc] initWithOperation:kCCEncrypt settings:kRNCryptorAES256Settings key:key IV:iv error:nil];
[encryptedData appendData:[cryptor addData:sourceData error:nil]];
[encryptedData appendData:[cryptor finishWithError:nil]];
return encryptedData;
}
But the results from the two functions never match. For example, for the same line of a single word, the PHP code returns J39gRcuBEaqMIPP1VlizdA8tRjmyAB6za4zG5wcOB/8=, and in Objective-C (after starting base64EncodedStringWithOptions:as a result of NSData), Im receives 1FGpZpVm2p4z3BBY6KW2fw==.
Is there anything I need for further configuration in RNCryptor settings to make it work?
UPDATE
Ive iOS CommonCrypto, RNCryptor lib. , RNCryptor. AES128 Objective-C, PHP , ...
2
MD5String, , NSString :
- (NSString *)MD5String {
const char *cstr = [self UTF8String];
unsigned char result[16];
CC_MD5(cstr, strlen(cstr), result);
return [[NSString stringWithFormat:
@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
] lowercaseString];
}