你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS7技巧 >> ios keychain共享存取敏感信息方法

ios keychain共享存取敏感信息方法

編輯:IOS7技巧
iOS的keychain服務提供了一種安全的保存私密信息(密碼,序列號,證書等)的方式。每個ios程序都有一個獨立的keychain存儲。從ios 3.0開始,跨程序分享keychain變得可行。

iOS開發時一般使用UserDefaults來存取App的配置信息,但是如果需要保存一些敏感信息的話,這時可以考慮使用Keychain來存取。開發時需要注意的是,App卸載後UserDefaults的內容會被刪除,而Keychain裡面的則不會,如果首次將內容寫入Keychain,需要判斷Keychain中是否包含之前沒有刪除干淨的內容。
Keychain(鑰匙串)是蘋果公司Mac OS中的密碼管理系統,iOS出現後也被引入到iOS中,作為用戶密碼管理的重要工具。使用Keychain對開發者來說,可以省略掉敏感信息的加密和解密的過程,交由系統管理。

使用蘋果官方發布的KeychainItemWrapper或者SFHFKeychainUtils很方便。

蘋果已經有現成的類封裝好了keychain,KeychainItemWrapper.h和KeychainItemWrapper.m文件,可以在GenericKeychain實例裡找到。


Keychain的用法也很簡單,蘋果提供了一段示例代碼裡面包含了KeychainItemWrapper這個對Keychain操作的包裝工具包。使對Keychain的操作如同NSDictionary一樣簡單

 代碼如下 復制代碼

KeychainItemWrapper *keychainItem = [[[KeychainItemWrapper alloc]
                                    initWithIdentifier:@"Identifier"
                                           accessGroup:@"cn.limc.app.boundle"]autorelease];
//獲取keychain中的內容
NSString *value = [keychainItem objectForKey:keyForValue];
 
//寫入內容到keychain
NSString *valueToWrite = @"value to store";
[keychainItem setObject:valueToWrite forKey:keyForValue];


下面就使用keychain來實現存取用戶名和密碼。

 代碼如下 復制代碼

CHKeychain.h

 
#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


#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;
}

+ (void)delete:(NSString *)service {
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((CFDictionaryRef)keychainQuery);
}


@end

 

首先需要定義幾個字符串用來做key:

 代碼如下 復制代碼

 

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";


把用戶名和密碼存入keychain:

 代碼如下 復制代碼


 
NSMutableDictionary *usernamepasswordKVPairs = [NSMutableDictionary dictionary];
[usernamepasswordKVPairs setObject:txtfldUsername.text forKey:KEY_USERNAME];
[usernamepasswordKVPairs setObject:txtfldPassword.text forKey:KEY_PASSWORD];
[CHKeychain save:KEY_USERNAME_PASSWORD data:usernamepasswordKVPairs];


從keychain中取出用戶名和密碼:

 代碼如下 復制代碼

 

NSMutableDictionary *usernamepasswordKVPairs = (NSMutableDictionary *)[CHKeychain load:KEY_USERNAME_PASSWORD];
txtfldUsername.text = [usernamepasswordKVPairs objectForKey:KEY_USERNAME];
txtfldPassword.text = [usernamepasswordKVPairs objectForKey:KEY_PASSWORD];


刪除一個keychain item:

 代碼如下 復制代碼
[cpp] view plaincopyprint?
01.[CHKeychain delete:KEY_USERNAME_PASSWORD]; 
[CHKeychain delete:KEY_USERNAME_PASSWORD];

這樣一個簡單的使用keychain存取用戶名密碼的功能就做好了。

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved