iOS KeyChain使用和封装,唯一标识符存储

最近项目需要存储用户的唯一标识符,但是由于如果用户重装APP,获取到的又会是一个新的UDID。查询了一系列资料下来,可以用Keychain进行存储UDID,然后就算重装了APP,也能从Keychain中读取出之前存储的UDID。

Keychain存储在iOS系统的内部数据库中,由系统进行管理和加密,哪怕APP被删除了,它存储在Keychain中的数据也不会被删除。

So,Keychain使用走起~
首先一定要在Capabilities中打开Keychain,如图:

6B836BEE-1CDC-4D49-8E7E-50490DE2E953.png

好吧,不打开的话进行Keychain操作将会返回一个34018的错误码。。

当然别忘记引入import <Security/Security.h>

Keychain存储的流程如图所示:

B9C180AB-88D0-44B6-905E-37802CC13B6E.png

简单来说,如果要存储一个password,需要先遍历Keychain,看它的password是否已经存在于Keychain中,存在的话就更新它的值,不存在就存储。
所以这就使用到苹果提供的方法:

// 查询
OSStatus SecItemCopyMatching(CFDictionaryRef query, CFTypeRef *result);

// 添加
OSStatus SecItemAdd(CFDictionaryRef attributes, CFTypeRef *result);

// 更新
OSStatus SecItemUpdate(CFDictionaryRef query, CFDictionaryRef attributesToUpdate);

// 删除
OSStatus SecItemDelete(CFDictionaryRef query)

接下来看看操作Keychain常用的key-value.

kSecClass:有五个值,分别为
      kSecClassGenericPassword(通用密码--也是接下来使用的)、
      kSecClassInternetPassword(互联网密码)、
      kSecClassCertificate(证书)、
      kSecClassKey(密钥)、
      kSecClassIdentity(身份)

kSecAttrService:服务
kSecAttrServer:服务器域名或IP地址
kSecAttrAccount:账号
kSecAttrAccessGroup: 可以在应用之间共享keychain中的数据
kSecMatchLimit:返回搜索结果,kSecMatchLimitOne(一个)、kSecMatchLimitAll(全部)
//

这是基于CoreFundation框架的操作,通过带有以上key-value值的字典进行操作,所以写起来还是有些繁琐的。所幸苹果提供了一个源码Demo。demo中使用service和account以及accessGroup进行password的存储,也就是一个kSecClassGenericPassword类型的Keychain表,一个account对应一个password,可以很方便在APP中进行Key-Value类型的存储。

不过由于它是使用Swift编写的,在我的小项目中不适合引入混编,所以我就按着demo 的逻辑抄了个OC版的出来。个人看来,OC的还是好懂点,去除了各种try catch,思路上会清晰很多。

初始化方法:

- (instancetype)initWithSevice:(NSString *)service account :(NSString *)account accessGroup:(NSString *)accessGroup {
    if (self = [super init]) {
        _service = service;
        _account = account;
        _accessGroup = accessGroup;//可以在不同的app当中共享
    }
    return self;
}

主要方法有:

- (void)savePassword:(NSString *)password;
- (BOOL)deleteItem;

- (NSString *)readPassword;

//返回当前accessGroup下的service的所有Keychain Item
+ (NSArray *)passwordItemsForService:(NSString *)service accessGroup:(NSString *)accessGroup;

(具体代码在后面贴吧,防止影响篇幅,有兴趣的朋友也可以下demo看看)

使用起来就是:
存储:

    KeychainWrapper *wrapper = [[KeychainWrapper alloc] initWithSevice:kKeychainService account:self.accountField.text accessGroup:kKeychainAccessGroup];
    [wrapper savePassword:self.passwordField.text];

读取当前account 的password:

KeychainWrapper *item = [[KeychainWrapper alloc] initWithSevice:service account:acount accessGroup:accessGroup];
[item readPassword];

返回当前accessGroup下的service的所有Keychain:

NSArray *keychains = [KeychainWrapper passwordItemsForService:kKeychainService accessGroup:kKeychainAccessGroup];

踩坑:OSStatus状态错误码:

  • 50: 请求参数错误。我就曾经把kSecAttrService写成了kSecAttrServer,crash到哭了。。。
  • 34018:前面说的Capabilities...

代码:

- (void)savePassword:(NSString *)password {
    NSData *encodePasswordData = [password dataUsingEncoding:NSUTF8StringEncoding];
    
    // if password was existed, update
    NSString *originPassword = [self readPassword];
    
    if (originPassword.length > 0) {
        NSMutableDictionary *updateAttributes = [NSMutableDictionary dictionary];
        updateAttributes[(__bridge id)kSecValueData] = encodePasswordData;
        
        NSMutableDictionary *query = [self keychainQueryWithService:_service account:_account accessGroup:_accessGroup];
        OSStatus statusCode = SecItemUpdate(
                                           (__bridge CFDictionaryRef)query,
                                           (__bridge CFDictionaryRef)updateAttributes);
        NSAssert(statusCode == noErr, @"Couldn't update the Keychain Item." );
    }else{
        // else , add
        NSMutableDictionary *attributes = [self keychainQueryWithService:_service account:_account accessGroup:_accessGroup];
        attributes[(__bridge id)kSecValueData] = encodePasswordData;
        
        OSStatus status = SecItemAdd((__bridge CFDictionaryRef)attributes, nil);
        
        NSAssert(status == noErr, @"Couldn't add the Keychain Item.");
    }
}

- (NSString *)readPassword {
    NSMutableDictionary *attributes = [self keychainQueryWithService:_service account:_account accessGroup:_accessGroup];
    attributes[(__bridge id)kSecMatchLimit] = (__bridge id)(kSecMatchLimitOne);
    attributes[(__bridge id)kSecReturnAttributes] = (__bridge id _Nullable)(kCFBooleanTrue);
    attributes[(__bridge id)kSecReturnData] = (__bridge id _Nullable)(kCFBooleanTrue);
    
    CFMutableDictionaryRef queryResult = nil;
    OSStatus keychainError = noErr;
    keychainError = SecItemCopyMatching((__bridge CFDictionaryRef)attributes,(CFTypeRef *)&queryResult);
    if (keychainError == errSecItemNotFound) {
        if (queryResult) CFRelease(queryResult);
        return nil;
    }else if (keychainError == noErr) {
        
        if (queryResult == nil){return nil;}
        
        NSMutableDictionary *resultDict = (__bridge NSMutableDictionary *)queryResult;
        NSData *passwordData = resultDict[(__bridge id)kSecValueData];
        
        NSString *password = [[NSString alloc] initWithData:passwordData encoding:NSUTF8StringEncoding];
        
        return password;
    }else
    {
        NSAssert(NO, @"Serious error.\n");
        if (queryResult) CFRelease(queryResult);
    }
    
    return nil;
}

- (NSMutableDictionary *)keychainQueryWithService:(NSString *)service account:(NSString *)account accessGroup:(NSString *)accessGroup {
    
    NSMutableDictionary *query = [NSMutableDictionary dictionary];
    
    query[(__bridge id)kSecClass] = (__bridge id)kSecClassGenericPassword;
    
    query[(__bridge id)kSecAttrService] = service;
    
    query[(__bridge id)kSecAttrAccount] = account;
    
    query[(__bridge id)kSecAttrAccessGroup] = accessGroup;
    
    return query;
}

+ (NSArray *)passwordItemsForService:(NSString *)service accessGroup:(NSString *)accessGroup {
    NSMutableDictionary *query = [[[self alloc]init] keychainQueryWithService:service account:nil accessGroup:accessGroup];
    
    query[(__bridge id)kSecMatchLimit] = (__bridge id)kSecMatchLimitAll;
    query[(__bridge id)kSecReturnAttributes] = (__bridge id _Nullable)(kCFBooleanTrue);
    query[(__bridge id)kSecReturnData] = (__bridge id _Nullable)(kCFBooleanFalse);
    
    CFMutableArrayRef queryResult = nil;
    OSStatus status = noErr;
    status = SecItemCopyMatching((__bridge CFDictionaryRef)query,(CFTypeRef *)&queryResult);
    
    if (status == errSecItemNotFound) {
        return @[];
    }else if (status == noErr) {
        
        NSArray<NSDictionary *> *resultArray = (__bridge NSArray<NSDictionary *> *)queryResult;
        
        if (resultArray.count == 0){return @[];}
        
        NSMutableArray *passwordItems = [NSMutableArray array];
        
        for (NSDictionary *result in resultArray) {
            NSString *acount = result[(__bridge id)kSecAttrAccount];
            
            if (acount.length > 0) {
                KeychainWrapper *item = [[KeychainWrapper alloc] initWithSevice:service account:acount accessGroup:accessGroup];
                [passwordItems addObject:item];
            }
        }
        
        return passwordItems;
    }else {
        NSAssert(NO, @"Serious error.\n");
        if (queryResult) CFRelease(queryResult);
        return @[];
    }
}

- (BOOL)deleteItem {
    // Delete the existing item from the keychain.
    NSMutableDictionary *query = [self keychainQueryWithService:self.service account:self.account accessGroup:self.accessGroup];
    
    OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);
    
    if (status != noErr && status != errSecItemNotFound) {
        return NO;
    }
    return true;
}

demo
参考:
https://developer.apple.com/library/prerelease/content/documentation/Security/Conceptual/keychainServConcepts/iPhoneTasks/iPhoneTasks.html#//apple_ref/doc/uid/TP30000897-CH208-SW1
http://www.360doc.com/content/15/0708/15/20918780_483580050.shtml
https://my.oschina.net/w11h22j33/blog/206713

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,710评论 4 376
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,839评论 2 308
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,295评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,776评论 0 223
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,198评论 3 297
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,074评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,200评论 2 322
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,986评论 0 214
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,733评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,877评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,348评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,675评论 3 265
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,393评论 3 246
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,209评论 0 9
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,996评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,212评论 2 287
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 36,003评论 2 280

推荐阅读更多精彩内容