user3564870 user3564870 - 1 year ago 104
Objective-C Question

Encrypting with OpenSSL and CommonCrypto

I'm trying to ultimately encrypt a file with OpenSSL and decrypt with Objective-c CommonCrypto, but before that works I need both approaches to encrypt the same way.

This is what I have:

String to encrypt: "This is the string"

Key: "thisisthekey"


openssl enc -aes256 -a -e -nosalt -in InputFileWithString.txt -out OutputFile.txt thisisthekey

Resulting base 64 encoded string from openSSL:

Objective-c CommonCrypto:

+(NSString *)encryptText:(NSString *)text withKey:(NSString *)key{
NSData *plainData = [text dataUsingEncoding:NSUTF8StringEncoding];

NSData *encryptedData = [plainData AES256EncryptWithKey:key];

NSString *base64String = [encryptedData base64EncodedStringWithOptions:0];

return base64String;

- (NSData*)AES256EncryptWithKey:(NSString*)key {
char keyPtr[kCCKeySizeAES256 + 1];
bzero(keyPtr, sizeof(keyPtr));

[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

NSUInteger dataLength = [self length];

size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);

size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
[self bytes], dataLength,
buffer, bufferSize,

if (cryptStatus == kCCSuccess)
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];

return nil;

The resulting base 64 encoded string:

As you can see, each approach is producing a different encrypted string. Any ideas how to make these both produce the same string?

Answer Source
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download