Decode OpenSSL AES256 string in iOS

纵然是瞬间 提交于 2019-12-12 07:21:54

问题


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 doesn't output anything since it failed. What am I missing?

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


回答1:


The -k option in OpenSSL's enc utility derives an AES key and IV from your passphrase "FUUU". You can use the -p option to have OpenSSL print the AES256 key and IV that it derived:

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

AES256DecryptWithKey is expecting 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 (not 64 ASCII characters. 32 bytes), you still won't be able to decrypt it and get your original string back. That's because OpenSSL is using an IV, but AES256DecryptWithKey is not:

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

(See the NULL being passed for the IV? That's not going to work for you)

So you need to use an encryption and decryption method that both use the same AES key and IV for this to work.



来源:https://stackoverflow.com/questions/9271588/decode-openssl-aes256-string-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!