2012-12-29 54 views
-1

如何使用字符串和密鑰生成加密的字符串?喜歡的東西...從另一個NSString和密鑰獲取加密的NSString

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

Encryptor是什麼類? –

+1

在http://crypto.stackexchange.com/上有更多的加密方式比有問題要多;而且至少有十幾種這些日子是可行的。你必須更具體。 – delnan

回答

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