由于您还没有发布任何代码,因此很难确切地知道您遇到了哪些问题。然而,您链接到的博客文章似乎工作得相当不错......除了每次调用中的额外逗号CCCrypt()
这导致了编译错误。
后来对该帖子的评论包括这个改编的代码 http://pastie.org/426530,这对我有用,而且看起来更简单。如果您包含 NSData 类别的代码,您可以编写如下内容:(注意:printf()
调用仅用于演示各个点的数据状态 - 在实际应用程序中,打印此类值是没有意义的。)
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *key = @"my password";
NSString *secret = @"text to encrypt";
NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];
NSData *cipher = [plain AES256EncryptWithKey:key];
printf("%s\n", [[cipher description] UTF8String]);
plain = [cipher AES256DecryptWithKey:key];
printf("%s\n", [[plain description] UTF8String]);
printf("%s\n", [[[NSString alloc] initWithData:plain encoding:NSUTF8StringEncoding] UTF8String]);
[pool drain];
return 0;
}
考虑到这段代码,以及加密数据并不总是能很好地转换为 NSString 的事实,编写两种方法来包装您需要的功能(正向和反向)可能会更方便......
- (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] autorelease];
}
这绝对适用于雪豹,并且@Boz报道称 CommonCrypto 是 iPhone 核心操作系统的一部分。 10.4和10.5都有/usr/include/CommonCrypto
,尽管 10.5 有一个手册页CCCryptor.3cc
而 10.4 则没有,所以 YMMV。
EDIT: See 这个后续问题 https://stackoverflow.com/questions/1417893/使用 Base64 编码将加密数据字节表示为字符串(如果需要),并使用安全、无损的转换。