如何在ios钥匙串中手动存储?

tho*_*b65 5 security objective-c ios

对于我的应用程序,我必须以安全的方式存储用户名/密码,并认为将其存储在系统钥匙串中的最佳解决方案。最好的方法是什么?我是否需要强制使用像 FDKeychain 这样的钥匙串工具,或者有没有没有这样的 Wrapper 的简单方法?

谢谢

wmv*_*vis 5

您可以通过这种方式手动存储值(iOS7):

编辑:Martin R 指出,如果密钥已在使用中,则 SecItemAdd 失败。在这种情况下,必须调用 SecItemUpdate。

NSString *key = @"full_name";
NSString *value = @"My Name";
NSData *valueData = [value dataUsingEncoding:NSUTF8StringEncoding];
NSString *service = [[NSBundle mainBundle] bundleIdentifier];

NSDictionary *secItem = @{
    (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword,
    (__bridge id)kSecAttrService : service,
    (__bridge id)kSecAttrAccount : key,
    (__bridge id)kSecValueData : valueData,};

CFTypeRef result = NULL;
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)secItem, &result);
if (status == errSecSuccess){ 
    NSLog(@"value saved");
}else{
    NSLog(@"error: %ld", (long)status);
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样检索它:

NSString *keyToSearchFor = @"full_name";
NSString *service = [[NSBundle mainBundle] bundleIdentifier];

NSDictionary *query = @{
    (__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword, 
    (__bridge id)kSecAttrService : service,
    (__bridge id)kSecAttrAccount : keyToSearchFor,
    (__bridge id)kSecReturnAttributes : (__bridge id)kCFBooleanTrue, };

CFDictionaryRef valueAttributes = NULL;
OSStatus results = SecItemCopyMatching((__bridge CFDictionaryRef)query,
                                           (CFTypeRef *)&valueAttributes);
NSDictionary *attributes = (__bridge_transfer NSDictionary *)valueAttributes;

if (results == errSecSuccess){
     NSString *key, *accessGroup, *creationDate, *modifiedDate, *service;
     key = attributes[(__bridge id)kSecAttrAccount];
     accessGroup = attributes[(__bridge id)kSecAttrAccessGroup];
     creationDate = attributes[(__bridge id)kSecAttrCreationDate];
     modifiedDate = attributes[(__bridge id)kSecAttrModificationDate];
     service = attributes[(__bridge id)kSecAttrService];
} else {
    NSLog(@"error: %ld", (long)results);
}
Run Code Online (Sandbox Code Playgroud)