iOS AES数据/字符串转换
我以前在iphone上使用过AES加密提示iOS AES数据/字符串转换,ios,nsstring,nsdata,Ios,Nsstring,Nsdata,我以前在iphone上使用过AES加密提示 NSString *mystr= [[self encryptString:[message valueForKey:@"message"] withKey:@"password"] hexadecimalString]; NSData *mydata= [self encryptString:[message valueForKey:@"message"] withKey:@"password"]; NSLog (@"Imme
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的数据和标头(加密)
第一步
NSString *mystr= [[self encryptString:[message valueForKey:@"message"] withKey:@"password"] hexadecimalString];
使用hexadecimalString
方法将NSData
转换为NSString
。
例如,如果加密数据为01 02 03
,则mystr
为@“010203”
在你的最后一步
NSLog (@"Immediate decrypt string: %@",[self decryptData:[mystr dataUsingEncoding:NSUTF8StringEncoding] withKey:@"password"]);
使用dataUsingEncoding:NSUTF8StringEncoding
将NSString
转换回NSData
。
例如,@“010203”
将转换为数据30 31 30 33
这是两个不同的转换过程,因此不能期望得到正确的结果。
你可能应该做一些类似的事情
NSLog (@"Immediate decrypt string: %@",[self decryptData:[mystr dataFromHexadecimal] withKey:@"password"]);
其中,
dataFromHexadecimal
是一种将十六进制字符串转换回NSData
(与hexadecimalString
相反的方法)的方法。hexadecimalString只返回类似于-description的值,没有空格或括号。我没有意识到NSData是二进制的。我想我会用base64。
NSLog (@"Immediate decrypt string: %@",[self decryptData:[mystr dataFromHexadecimal] withKey:@"password"]);