我在iphone上使用过以前提到的关于AES加密的提示。
NSString *mystr= [[self encryptString:[message valueForKey:@"message"] withKey:@"password"] hexadecimalString];
NSData *mydata= [self encryptString:[message valueForKey:@"message"] withKey:@"password"];
NSLog (@"Immediate decrypt data: %@",[self decryptData:mydata withKey:@"password"]);
NSLog (@"Immediate decrypt string: %@",[self decryptData:[mystr dataUsingEncoding:NSUTF8StringEncoding] withKey:@"password"]);
第一个NSLog正确解码字符串,第二个返回null。 本课程中的方法:
+ (NSData*) encryptString:(NSString*)plaintext withKey:(NSString*)key {
return [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
}
+ (NSString*) decryptData:(NSData*)ciphertext withKey:(NSString*)key {
return [[NSString alloc] initWithData:[ciphertext AES256DecryptWithKey:key]
encoding:NSUTF8StringEncoding] ;
}
和NSData(加密)的标题
- (NSData *)AES256EncryptWithKey:(NSString *)key;
- (NSData *)AES256DecryptWithKey:(NSString *)key;
答案 0 :(得分:2)
在你的第一步
NSString *mystr= [[self encryptString:[message valueForKey:@"message"] withKey:@"password"] hexadecimalString];
您使用NSData
方法将NSString
转换为hexadecimalString
。
例如,如果加密数据为01 02 03
,则mystr
为@"010203"
。
在你的最后一步
NSLog (@"Immediate decrypt string: %@",[self decryptData:[mystr dataUsingEncoding:NSUTF8StringEncoding] withKey:@"password"]);
您使用NSString
将NSData
转换回dataUsingEncoding:NSUTF8StringEncoding
。
例如,@"010203"
将转换为数据30 31 30 32 30 33
。
这是两个不同的转换过程,因此您无法获得正确的结果。 你可能应该做类似的事情
NSLog (@"Immediate decrypt string: %@",[self decryptData:[mystr dataFromHexadecimal] withKey:@"password"]);
其中dataFromHexadecimal
是将十六进制字符串转换回NSData
的方法(反向方法为hexadecimalString
)。