Decode OpenSSL AES256 string in iOS

CLI

$ echo -n "TEST1" | openssl enc -aes256 -k FUUU -nosalt -a bYbkQJcDFZt3y3UQEMbEeg== 

Ios

 NSString *leSYT = @"bYbkQJcDFZt3y3UQEMbEeg=="; NSData *data = [NSData dataFromBase64String:leSYT]; NSLog(@"%@",[data AES256DecryptWithKey:@"FUUU"]); 

iOS has not output anything since its failure. What am I missing?

NSData Additions: http://pastie.org/426530 // NSData + Base64 by Matt Gallagher

+2
source share
1 answer

The -k in the OpenSSL enc utility outputs the AES and IV switch from your passphrase "FUUU". You can use the -p option to have OpenSSL print the AES256 and IV key that it received:

 $ echo -n "TEST1" | openssl enc -aes256 -k FUUU -nosalt -a -p key=59C12FFF74992ED40F4DF80A56AB55AE7C513B17CB4B8CF8342E9444C7F7AF3B iv =0BEE68AD25123B7076B91A5AFB549E33 bYbkQJcDFZt3y3UQEMbEeg== 

AES256DecryptWithKey expects a 32-byte AES key, as the comments say:

 - (NSData *)AES256DecryptWithKey:(NSString *)key { // 'key' should be 32 bytes for AES256, will be null-padded otherwise char keyPtr[kCCKeySizeAES256+1]; // room for terminator (unused) bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding) 

But even if you convert the key string from OpenSSL to a string of bytes (rather than 64 ASCII characters, 32 bytes), you still cannot decrypt it and return the original string. This is because OpenSSL uses IV, but AES256DecryptWithKey does not:

 CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES256, NULL /* initialization vector (optional) */, [self bytes], dataLength, /* input */ buffer, bufferSize, /* output */ &numBytesDecrypted); 

(See NULL passed for IV? This will not work for you)

Thus, you need to use the encryption and decryption method, which uses the same AES and IV key for this.

+3
source

Source: https://habr.com/ru/post/910238/


All Articles