KeyChain是蘋果提供的一種安全的保存用戶名、密碼、證書的方式,將敏感信息保存在keychain中後,這些信息不會隨著app的卸載而丟失,除非開發人員在app中手動刪除敏感信息,否則,這些信息將會一直保存在keychain中。
在使用keychain時,我們首先要將security.framework引入到工程中。由於使用時不支持arc,所以我們在arc環境中需要針對相關文件啟用mrc模式。
首先,我們構造一個工具類,通過這個類來操作keychain。
#import#import @interface KeyChain : NSObject // save username and password to keychain + (void)save:(NSString *)service data:(id)data; // take out username and passwore from keychain + (id)load:(NSString *)service; // delete username and password from keychain + (void)delete:(NSString *)service; @end
#import "KeyChain.h" @implementation KeyChain /** *該類需要工作在mrc模式下,acr的項目按照如下步驟操作 *選中工程->TARGETS->相應的target然後選中右側的“Build Phases”,向下就找到“Compile Sources”了。然後在相應的文件後面添加:-fno-objc-arc參數 * **/ + (NSMutableDictionary *)getKeychainQuery:(NSString *)service { return [NSMutableDictionary dictionaryWithObjectsAndKeys: (id)kSecClassGenericPassword,(id)kSecClass, service, (id)kSecAttrService, service, (id)kSecAttrAccount, (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible, nil]; } #pragma mark 寫入 + (void)save:(NSString *)service data:(id)data { //Get search dictionary NSMutableDictionary *keychainQuery = [self getKeychainQuery:service]; //Delete old item before add new item SecItemDelete((CFDictionaryRef)keychainQuery); //Add new object to search dictionary(Attention:the data format) [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData]; //Add item to keychain with the search dictionary SecItemAdd((CFDictionaryRef)keychainQuery, NULL); } #pragma mark 讀取 + (id)load:(NSString *)service { id ret = nil; NSMutableDictionary *keychainQuery = [self getKeychainQuery:service]; //Configure the search setting //Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData]; [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit]; CFDataRef keyData = NULL; if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) { @try { ret = [NSKeyedUnarchiver unarchiveObjectWithData:(NSData *)keyData]; } @catch (NSException *e) { NSLog(@"Unarchive of %@ failed: %@", service, e); } @finally { } } if (keyData) CFRelease(keyData); return ret; } #pragma mark 刪除 + (void)delete:(NSString *)service { NSMutableDictionary *keychainQuery = [self getKeychainQuery:service]; SecItemDelete((CFDictionaryRef)keychainQuery); } @end修改工程的相關放在在代碼注釋中已經寫清楚了。
下邊是使用這個類
首先,我們定義幾個字符串類型的標識符
NSString * const KEY_USERNAME_PASSWORD = @"com.company.app.usernamepassword"; NSString * const KEY_USERNAME = @"com.company.app.username"; NSString * const KEY_PASSWORD = @"com.company.app.password";之後,我們創建一個字典,並將用戶名和密碼放入字典中
NSMutableDictionary *userNamePasswordKVPairs = [NSMutableDictionary dictionary]; [userNamePasswordKVPairs setObject:@"userName" forKey:KEY_USERNAME]; [userNamePasswordKVPairs setObject:@"password" forKey:KEY_PASSWORD];
// A、將用戶名和密碼寫入keychain [KeyChain save:KEY_USERNAME_PASSWORD data:userNamePasswordKVPairs]; // B、從keychain中讀取用戶名和密碼 NSMutableDictionary *readUsernamePassword = (NSMutableDictionary *)[KeyChain load:KEY_USERNAME_PASSWORD]; NSString *userName = [readUsernamePassword objectForKey:KEY_USERNAME]; NSString *password = [readUsernamePassword objectForKey:KEY_PASSWORD]; NSLog(@"username = %@", userName); NSLog(@"password = %@", password); // C、將用戶名和密碼從keychain中刪除 [KeyChain delete:KEY_USERNAME_PASSWORD];