所以你想在 CBC 模式下使用 AES256 进行加密。
您正在寻找的库是 CommonCrypto,您可以在这里找到一篇关于它的好文章:http://robnapier.net/aes-commoncrypto http://robnapier.net/aes-commoncrypto.
您还需要一个 MD5 函数,可以在此处找到:http://www.makebetterthings.com/iphone/how-to-get-md5-and-sha1-in-objective-c-ios-sdk/ http://www.makebetterthings.com/iphone/how-to-get-md5-and-sha1-in-objective-c-ios-sdk/
您的代码应该如下所示:
NSString *originalString,*keyString;
NSData *key = [[self md5:keyString] dataUsingEncoding:NSUTF8StringEncoding];
NSData *iv = [[self md5:[self md5:key]] dataUsingEncoding:NSUTF8StringEncoding];
NSData *data = [originalString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *cipherData = [NSMutableData dataWithLength:data.length + kCCBlockSizeAES128]; //The block size of MCRYPT_RIJNDAEL_256 is just like AES128
size_t outLength;
CCCryptorStatus result
= CCCrypt(kCCEncrypt, // operation, replace with kCCDecrypt to decrypt
kCCAlgorithmAES, // Same as MCRYPT_RIJNDAEL_256
nil, // CBC mode
key.bytes, // key
32, // Since you are using AES256
iv.bytes,// iv
data.bytes, // dataIn
data.length, // dataInLength,
cipherData.mutableBytes, // dataOut
cipherData.length, // dataOutAvailable
&outLength); // dataOutMoved
NSString resultString = [cipherData base64Encoding];
并确保在这两种情况下使用相同的 UTF8 编码,并使用此导入:
#import <CommonCrypto/CommonCryptor.h>
我很确定这应该有效。
编辑:密钥长度应为 32,因为您使用的是 AES256 256bit=32bytes。我认为默认情况下 MD5 输出与此长度不匹配。