[英]AES Base64 256 bit Encryption and Decryption with key in Objective C
[英]AES encryption on iOS with base64 key from CryptoJS
我正在使用CryptoJS生成和导出密钥:
const password = crypto.lib.WordArray.random(128 / 8);
const salt = crypto.lib.WordArray.random(128 / 8);
const encryptionKey = crypto.PBKDF2(password, salt, {keySize: 128 / 32});
return encryptionKey.toString();
现在,我正在尝试使用iOS上的密钥加密某些数据:
const char *s = [encryptionKey cStringUsingEncoding:NSASCIIStringEncoding];
NSData *keyData= [NSData dataWithBytes:s length:strlen(s)];
NSMutableData *ivData = [NSMutableData dataWithLength:kCCBlockSizeAES128];
SecRandomCopyBytes(kSecRandomDefault, kCCBlockSizeAES128, ivData.mutableBytes);
NSData *iv = [NSData dataWithData:ivData];
size_t outLength;
NSMutableData *cipherData = [NSMutableData dataWithLength:dataString.length + kCCBlockSizeAES128];
CCCrypt(kCCEncrypt, // operation
kCCAlgorithmAES128, // Algorithm
kCCOptionPKCS7Padding, // options
keyData.bytes, // key
keyData.length, // keylength
iv.bytes,// iv
jsonData.bytes, // dataIn
jsonData.length, // dataInLength,
cipherData.mutableBytes, // dataOut
cipherData.length, // dataOutAvailable
&outLength); // dataOutMoved
cipherData.length = outLength;
NSString *cipherText = [cipherData base64EncodedStringWithOptions:NSUTF8StringEncoding];
NSString *ivText = [iv base64EncodedStringWithOptions:NSUTF8StringEncoding];
return [ivText stringByAppendingString:cipherText]
到目前为止,所有这些都有效。 但是尝试使用CryptoJS解密数据失败:
const iv = crypto.enc.Base64.parse(message.substr(0, 24));
const encrypted = crypto.enc.Base64.parse(message.substring(24));
const decrypted = crypto.AES.decrypt(encrypted, encryptionKey, {
iv: iv,
padding: crypto.pad.Pkcs7,
mode: crypto.mode.CBC
});
console.log(decrypted.toString(crypto.enc.Utf8))
问题似乎出在密钥从CryptoJS到iOS的传递。 传递给CCCrypt的正确格式是什么?
base64EncodedStringWithOptions
的选项不正确,并且会将行尾字符添加到Base64编码的iv和加密数据中。
您不希望使用行尾选项,默认情况下,不插入任何行尾。 只需指定0
:
NSString *cipherText = [cipherData base64EncodedStringWithOptions:0];
NSString *ivText = [iv base64EncodedStringWithOptions:0];
选项注意NSUTF8StringEncoding
不是用于该方法的编码选项base64EncodedStringWithOptions
。 选项包括:
NSDataBase64Encoding64CharacterLineLength
NSDataBase64Encoding76CharacterLineLength
NSDataBase64EncodingEndLineWithCarriageReturn
NSDataBase64EncodingEndLineWithLineFeed`
所有这些都是行分隔符选项。
我的原始代码包含三个错误。
zaph建议不要使用任何参数对生成的字符串进行编码:
NSString *cipherText = [cipherData base64EncodedStringWithOptions:0]; NSString *ivText = [iv base64EncodedStringWithOptions:0];
要将加密密钥正确转换为NSData
,我使用此处提供的方法,并这样调用它:
NSData *keyData= [self dataFromHexString:encryptionKey];
CryptoJS的decrypt
功能需要这样的对象:
const encrypted = crypto.enc.Base64.parse(message.substring(24)); const params = { ciphertext: encrypted, salt: '' }; const decrypted = crypto.AES.decrypt(params, crypto.enc.Hex.parse(this.encryptionKey.toString()), { iv: iv, padding: crypto.pad.Pkcs7, mode: crypto.mode.CBC }); return decrypted.toString(crypto.enc.Utf8);
谢谢你的帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.