从另一个NSString和密钥获取加密的NSString

时间:2012-12-29 11:57:18

标签: iphone objective-c ios encryption

如何使用字符串和密钥生成加密字符串?有点像...

NSString *key = @"password";
NSString *stringToBeEncrypted = @"This is important";
NSString *result = [Encryptor encryptedStringForKey:key string:stringToBeEncrypted];

2 个答案:

答案 0 :(得分:1)

经常使用的一种是AES256Encryption,它实现为:

NSString *stringToBeEncrypted = @"This is important";
NSString *key = @"password"; 

NSLog( @"Original String: %@", stringToBeEncrypted );

NSString *encryptedString = [stringToBeEncrypted AES256EncryptWithKey:key];

NSLog( @"Encrypted String: %@", encryptedString );

NSLog( @"Decrypted String: %@", [encryptedString AES256DecryptWithKey:key] );

答案 1 :(得分:1)

有许多类型的编码,

这是一个样本,

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *key = @"my password";
NSString *secret = @"text to encrypt";
NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];
NSData *cipher = [plain AES256EncryptWithKey:key];
plain = [cipher AES256DecryptWithKey:key];
[pool drain];


- (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];
}