1

我在 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;
4

1 回答 1

2

在你的第一步

NSString *mystr= [[self encryptString:[message valueForKey:@"message"] withKey:@"password"] hexadecimalString];

您使用该方法转换NSData为。例如,如果加密的数据是那么是。NSStringhexadecimalString01 02 03mystr@"010203"

在你的最后一步

NSLog (@"Immediate decrypt string: %@",[self decryptData:[mystr dataUsingEncoding:NSUTF8StringEncoding] withKey:@"password"]);

你转换NSStringNSDatawith dataUsingEncoding:NSUTF8StringEncoding。例如,@"010203"将转换为数据30 31 30 32 30 33

这是两个不同的转换过程,因此您不能期望得到正确的结果。你可能应该做类似的事情

NSLog (@"Immediate decrypt string: %@",[self decryptData:[mystr dataFromHexadecimal] withKey:@"password"]);

wheredataFromHexadecimal是将十六进制字符串转换回NSData(与 的逆方法hexadecimalString)的方法。

于 2013-04-07T08:26:09.297 回答