keychain初探

KeyChain详解

keychain 是一个相对独立的空间,保存到keychain钥匙串中的信息不会因为卸载/重装app而丢失, 。相对于NSUserDefaults、plist文件保存等一般方式,keychain保存更为安全。所以我们会用keyChain保存一些私密信息,比如密码、证书、设备唯一码(把获取到用户设备的唯一ID 存到keychain 里面这样卸载或重装之后还可以获取到id,保证了一个设备一个ID)等等。keychain是用SQLite进行存储的。用苹果的话来说是一个专业的数据库,加密我们保存的数据,可以通过metadata(attributes)进行高效的搜索。keychain适合保存一些比较小的数据量的数据,如果要保存大的数据,可以考虑文件的形式存储在磁盘上,在keychain里面保存解密这个文件的密钥

接下来记录下平时用到的基本方法

存储数据

+ (BOOL)saveValue:(NSString *)value key:(NSString *)key group:(NSString *)group service:(NSString *)service
{
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:key withAccessGroup:group withService:service];

    NSMutableDictionary *query = nil;
    OSStatus status;
    status = SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, nil);
    if (status == errSecSuccess) {
        query = [[NSMutableDictionary alloc]init];
        [query setObject:[NSKeyedArchiver archivedDataWithRootObject:value] forKey:(__bridge id)kSecValueData];
        
        status = SecItemUpdate((__bridge CFDictionaryRef)(keychainQuery), (__bridge CFDictionaryRef)(query));
    }else if(status == errSecItemNotFound)
    {
        [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:value] forKey:(__bridge id)kSecValueData];
        status = SecItemAdd((__bridge CFDictionaryRef)keychainQuery, NULL);
    }
    
    return (status == errSecSuccess);
}

删除数据

+ (BOOL)deleteWithkey:(NSString *)key group:(NSString *)group service:(NSString *)service
{
    NSMutableDictionary *query = [self getKeychainQuery:key withAccessGroup:group withService:service];
    OSStatus status = SecItemDelete((__bridge CFDictionaryRef)query);
    return (status == errSecSuccess);
}

读取数据

+ (id)loadWithkey:(NSString *)key group:(NSString *)group service:(NSString *)service
{
    CFTypeRef result = NULL;
    NSMutableDictionary *query = [self getKeychainQuery:key withAccessGroup:group withService:service];
    [query setObject:@YES forKey:(__bridge id)kSecReturnData];
    [query setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
    id value;
    if (SecItemCopyMatching((__bridge CFDictionaryRef)query, &result) == noErr) {
        @try {
            value = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)result];
        }
        @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", key, e);
            value = nil;
        }
        @finally {}
    }
    if (result) {
        CFRelease(result);
    }
    return value;
}

默认数据

+ (NSMutableDictionary *)getKeychainQuery:(NSString *)key withAccessGroup:(NSString *)group withService:(NSString *)service
{
    NSMutableDictionary *keychainQuery = [NSMutableDictionary dictionary];
    [keychainQuery setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
    [keychainQuery setValue:service forKey:(__bridge id)kSecAttrService];
    [keychainQuery setValue:key forKey:(__bridge id)kSecAttrAccount];
    [keychainQuery setValue:(__bridge id)kSecAttrAccessibleWhenUnlocked forKey:(__bridge id)kSecAttrAccessible];
    [keychainQuery setValue:group forKey:(__bridge id)kSecAttrAccessGroup];
    return keychainQuery;
}

note:每个group命名开头必须是开发者账号的teamId。不同开发者账号的teamId是唯一的,所以苹果限制了只有同一个开发者账号下的应用才可以进行共享。如果有多个sharedGroup,在添加的时候如果不指定,默认是第一个group。

你可能感兴趣的:(keychain初探)