iOS的keychain服務提供了一種安全的儲存私密資訊(密碼,序號,認證等)的方式。每個ios程式都有一個獨立的keychain儲存。從ios 3.0開始,跨程式分享keychain變得可行。
使用蘋果官方發布的KeychainItemWrapper或者SFHFKeychainUtils很方便。
蘋果已經有現成的類封裝好了keychain,KeychainItemWrapper.h和KeychainItemWrapper.m檔案,可以在GenericKeychain執行個體裡找到。
下面就使用keychain來實現存取使用者名稱和密碼。
代碼如下:
CHKeychain.h
[cpp] view plain copy #import <Foundation/Foundation.h> #import <Security/Security.h> @interface CHKeychain : NSObject + (void)save:(NSString *)service data:(id)data; + (id)load:(NSString *)service; + (void)delete:(NSString *)service; @end
CHKeychain.m
[cpp] view plain copy #import "CHKeychain.h" @implementation CHKeychain + (NSMutableDictionary *)getKeychainQuery:(NSString *)service { return [NSMutableDictionary dictionaryWithObjectsAndKeys: (id)kSecClassGenericPassword,(id)kSecClass, service, (id)kSecAttrService, service, (id)kSecAttrAccount, (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible, nil]; } + (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); } + (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; }