如何在iOS中使用AES128encryption的Openssl工具解密数据

我有很多代码片断,用AES128encryption数据(如果你提供你的工作实现,我将非常感谢)例如这个:

- (NSData*)AES128EncryptWithKey:(NSString*)key { // 'key' should be 16 bytes for AES128, will be null-padded otherwise char keyPtr[kCCKeySizeAES128 + 1]; // room for terminator (unused) bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding) // fetch key data [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding]; NSUInteger dataLength = [self length]; //See the doc: For block ciphers, the output size will always be less than or //equal to the input size plus the size of one block. //That's why we need to add the size of one block here size_t bufferSize = dataLength + kCCBlockSizeAES128; void* buffer = malloc(bufferSize); size_t numBytesEncrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode + kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES128, NULL /* initialization vector (optional) */, [self bytes], dataLength, /* input */ buffer, bufferSize, /* output */ &numBytesEncrypted); if (cryptStatus == kCCSuccess) { //the returned NSData takes ownership of the buffer and will free it on deallocation return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted]; } free(buffer); //free the buffer; return nil; } 

在数据被base64编码之后,使用在线工具将其保存到data.bin中

我想要做的是用OpenSSl解密这些数据。 但是,当我打电话

 openssl enc -aes-128-ecb -in data.bin -out out.bin -d -pass pass:0123456789123456 

它告诉我不好的魔法数字

如果我使用

 openssl enc -aes-128-ecb -in data.bin -out out.bin -d -pass pass:0123456789123456 -nosalt 

它告诉我糟糕的解密

请帮忙。

这里有几个问题。 首先,你用CBC模式(这是CCCrypt的默认值)进行encryption,但是在ECB模式下进行解密。 很less有理由使用ECB模式。

您正在使用string(我假定为“0123456789123456”)作为密钥进行encryption ,而不是密码 。 这些是不同的事情。 我不确定openssl如何将密码转换为密钥。 我在enc(1)页面上看不到这个解释。 我假设它使用PBKDF2,但不清楚(并没有给出迭代次数)。 您应该使用-K选项传递实际的密钥。 在这种情况下,你也需要明确地通过IV。 你没有正确地生成一个IV,或一个盐。 你应该是,然后你应该通过他们openssl。

要了解如何正确encryption ,请参阅使用CommonCrypto正确encryptionAES 。 一旦你有适当的encryption的东西,你应该有一个适当的密钥,盐和IV。 把所有的这些encryption,使用aes-128-cbc (假设128位AES),它应该工作。

编辑

值得一提的是这里显而易见:如果你在两边使用相同的工具包,encryption/解密要容易得多。 要做你想做的事情,你真的必须理解CCCrypt()和OpenSSL的细节,这就是为什么我正在讨论它们。 即使你发现“似乎有用”的东西,安全也很容易变得很糟糕,而你却没有意识到这一点。 AES128EncryptWithKey:就是这样一个例子; 它看起来很好,它“工作”,但它有几个安全问题。 如果可能的话,我会在两边都使用OpenSSL,或者在两边使用CCCrypt。