2012-07-18 85 views
6

我想在App中保存用戶的ID和密碼。如何使用鑰匙串保存密碼,如GenericKeychain示例代碼

當我保存ID和密碼時,什麼是值得推薦的加密方式。

我從越獄或黑客找到更安全的方式。

GenericKeychain示例代碼如何?

http://developer.apple.com/library/ios/#samplecode/GenericKeychain/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007797

我不能有關於安全的信心如何使用鑰匙扣像GenericKeychain示例代碼。

請告訴我一些建議。謝謝^^ *

回答

23

您可以使用安全框架

#import <Security/Security.h>

要保存用戶名和密碼的服務器:

-(void) saveUsername:(NSString*)user withPassword:(NSString*)pass forServer:(NSString*)server { 

    // Create dictionary of search parameters 
    NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)(kSecClassInternetPassword), kSecClass, server, kSecAttrServer, kCFBooleanTrue, kSecReturnAttributes, nil]; 

    // Remove any old values from the keychain 
    OSStatus err = SecItemDelete((__bridge CFDictionaryRef) dict); 

    // Create dictionary of parameters to add 
    NSData* passwordData = [pass dataUsingEncoding:NSUTF8StringEncoding]; 
    dict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)(kSecClassInternetPassword), kSecClass, server, kSecAttrServer, passwordData, kSecValueData, user, kSecAttrAccount, nil]; 

    // Try to save to keychain 
    err = SecItemAdd((__bridge CFDictionaryRef) dict, NULL); 

} 

要刪除:

-(void) removeAllCredentialsForServer:(NSString*)server { 

    // Create dictionary of search parameters 
    NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)(kSecClassInternetPassword), kSecClass, server, kSecAttrServer, kCFBooleanTrue, kSecReturnAttributes, kCFBooleanTrue, kSecReturnData, nil]; 

    // Remove any old values from the keychain 
    OSStatus err = SecItemDelete((__bridge CFDictionaryRef) dict); 

} 

閱讀:

-(void) getCredentialsForServer:(NSString*)server { 

    // Create dictionary of search parameters 
    NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:(__bridge id)(kSecClassInternetPassword), kSecClass, server, kSecAttrServer, kCFBooleanTrue, kSecReturnAttributes, kCFBooleanTrue, kSecReturnData, nil]; 

    // Look up server in the keychain 
    NSDictionary* found = nil; 
    CFDictionaryRef foundCF; 
    OSStatus err = SecItemCopyMatching((__bridge CFDictionaryRef) dict, (CFTypeRef*)&foundCF); 

    // Check if found 
    found = (__bridge NSDictionary*)(foundCF); 
    if (!found) 
     return; 

    // Found 
    NSString* user = (NSString*) [found objectForKey:(__bridge id)(kSecAttrAccount)]; 
    NSString* pass = [[NSString alloc] initWithData:[found objectForKey:(__bridge id)(kSecValueData)] encoding:NSUTF8StringEncoding]; 

} 
+1

現在,您需要使用__bridge(讓自動鏈接地址爲你做它)在上面ObjC和C代碼之間施放。 – 2013-01-30 04:36:03

+0

請問您可以更新此ARC嗎? – 2014-08-21 23:05:42

+0

你需要在SecItemCopyMatching之後檢查err == errSecItemNotFound – 2016-03-09 11:25:13

相關問題