in iOS ~ read.

iOS - Use of KeyChain

Simple use of KeyChain

  • For example
    NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity:0];
    NSData * psd = [@"data" dataUsingEncoding:NSUTF8StringEncoding];
    //设置类型
    [dict setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecAttrLabel];
    //标签
    [dict setObject:@"login" forKey:(__bridge id)kSecAttrLabel];
    //描述
    [dict setObject:@"description" forKey:(__bridge id)kSecAttrDescription];
    //账户
    [dict setObject:@"dthiel" forKey:(__bridge id)kSecAttrAccount];
    //服务标识符(防止重复)
    [dict setObject:@"com.isecpartners.SampleKeychain" forKey:(__bridge id)kSecAttrService];
    //设置数据
    [dict setObject:psd forKey:(__bridge id)kSecValueData];
    //设置可访问属性
    [dict setObject:(__bridge id)kSecAttrAccessibleWhenUnlocked forKey:(__bridge id)kSecAttrAccessible];
    //执行添加
    OSStatus error = SecItemAdd((__bridge CFDictionaryRef)dict, NULL);
    if (error == errSecSuccess) {
        NSLog(@"save success");
    }    
    //更新
    NSString * newPsd = @"";
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
    [dic setObject:@"dthiel" forKey:(__bridge id)kSecAttrAccount];
    [dic setObject:@"com.isecpartners.SampleKeychain" forKey:(__bridge id)kSecAttrService];
    NSDictionary * updateAttribute = [NSDictionary dictionaryWithObject:[newPsd dataUsingEncoding:NSUTF8StringEncoding] forKey:(__bridge id)kSecValueData];
    OSStatus err = SecItemUpdate((__bridge CFDictionaryRef)dic, (__bridge CFDictionaryRef)updateAttribute);    
    //查询
    [dict setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
    [dict setObject:@"dthiel" forKey:(__bridge id)kSecAttrAccount];
    [dict setObject:@"com.isecpartners.SampleKeychain" forKey:(__bridge id)kSecAttrService];
    [dict setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnAttributes];
    NSDictionary * result = nil;
    OSStatus er = SecItemCopyMatching((__bridge CFDictionaryRef)dict, (void*)&result);
    NSLog(@"resutl = %@",result);
    //删除
    NSMutableDictionary * searchDict = [NSMutableDictionary dictionary];
    [searchDict setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
    [searchDict setObject:@"dthiel" forKey:(__bridge id)kSecAttrAccount];
    [searchDict setObject:@"com.isecpartners.SampleKeychain" forKey:(__bridge id)kSecAttrService];
    OSStatus e = SecItemDelete((__bridge CFDictionaryRef)searchDict);

Shared Keychain

  • iOS 允许在多个应用之间共享钥匙串数据。通过设置相同的程序包 ID。
  • 如果引用需要使用访问组,需要创建一个权限属性列表,包含一个 keychain-access-groups 数组,每个共享要是串项目都会在数组中添加一个字符串元素。
[dict setObject:@"XXX.Secure" forKey:(id)kSecAttrAccessGroup];

demo


Start iCloud synchronization

  • 把钥匙串项目同步到 iCloud,允许用户在多个设备之间共享钥匙串项目,可以将kSecAttrSynchronizable 设置为 true 启用
[dic setObject:(id)kCFBooleanTrue forKey:(id)kSecAttrSynchronizable];
comments powered by Disqus