从NSString NOT NSData解密AES256字符串

时间:2013-07-10 09:46:41

标签: iphone ios objective-c encryption commoncrypto

我正在尝试使用AES256从iPhone应用程序发送和接收字符串到服务器并返回。

使用以下内容,我可以使用以下代码成功加密字符串并解密字符串: -

// Encryption Methods
NSString *theStringToDecrypt = @"{\"String\":\"This is a string\"}";
NSData *theEncodedString = [theStringToDecrypt dataUsingEncoding:NSUTF8StringEncoding]; // NSUTF8 Encrypt the string
NSData *encryptedData = [theEncodedString AES256EncryptWithKey:theKey]; // Encrypt to AES-256
NSData *decryptedData = [encryptedData AES256DecryptWithKey:theKey]; // Decrypt from AES-256
NSString *theDecodedString = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding]; // NSUTF8 Decode the string
NSString *theString = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding]; // NSUTF8 Decode the string
NSLog(@"theDecryptedKey=%@ | theEncryptedKey=%@",theString,theDecodedString);

因此,这会抓取一个字符串,使用NSData 8编码转换为UTF,然后使用AES256加密数据。然后它解密NSData并转换回字符串。

这样可以正常工作并成功加密/解密字符串。

我遇到的问题是,从服务器我将数据作为解密字符串返回,因此需要将字符串传递给AES256DecryptWithKey以简单地解密它,但AES256DecryptWithKe y仅适用于{ {1}}。

这会导致问题,因为我已经有了加密字符串,所以转换为数据然后加密到NSData包括UTF8编码,所以我实际上只将AES字符串转换回解密字符串。

我是否遗漏了一些简单的东西,或者在工作中有更黑暗的力量?

1 个答案:

答案 0 :(得分:0)

不要将二进制数据(密文)视为UTF-8。密文不是字符串。

如果您的协议不处理二进制数据,则必须使用二进制到文本编码将密文转换为字符串,如Base64。

相关问题