在iOS Keychain中,我应该使用哪个密钥来存储密码?

6
1个回答

7
您应该使用kSecValue数据作为密码(以NSData或CFDataRef格式)存储的关键字。
在这个主题中,参考文献有些不清楚,kSecValueData关键字作为输出关键字和输入关键字。也就是说,当您查询密钥链项目(SecItemCopyMatching)并指定kSecReturnAttributes关键字时,您会使用它,这样结果将作为字典返回,密码将存储在该字典的kSecValueData关键字下。在将项目添加到密钥链(SecItemAdd)时,调用该方法之前,将您的密码的NSData或CFDataRef值存储在kSecValueData关键字中。
以下是两种情况的示例:
检索密码:
NSMutableDictionary *queryDictionary = [[NSMutableDictionary alloc] init];
[queryDictionary setObject: (__bridge id)kSecClassGenericPassword forKey: (__bridge id<NSCopying>)kSecClass];
[queryDictionary setObject:service forKey:kSecAttrService];
[queryDictionary setObject:account forKey:kSecAttrAccount];
// The result will be a dictionary containing the password attributes...
[queryDictionary setObject:YES forKey:(__bridge id<NSCopying>)(kSecReturnAttributes)];
// ...one of those attributes will be a kSecValueData with the password
[queryDictionary setObject:YES forKey:(__bridge id<NSCopying>)(kSecReturnData)];
OSStatus sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef)(queryDictionary), (CFTypeRef *)&result);
if (sanityCheck != noErr)
{
    NSDictionary * resultDict = (__bridge NSDictionary *)result;
    // here's the queried password value
    NSData *passwordValue = [resultDict objectForKey:(__bridge id)(kSecValueData)];
}

添加密码:

NSString *passwordString = @"my password value";
NSData *passwordData = [passwordString dataUsingEncoding:NSUTF8StringEncoding];
CFDictionaryRef result = nil;
NSMutableDictionary *addDictionary = [[NSMutableDictionary alloc] init];
[addDictionary setObject: (__bridge id)kSecClassGenericPassword forKey: (__bridge id<NSCopying>)kSecClass];
[addDictionary setObject:service forKey:kSecAttrService];
[addDictionary setObject:account forKey:kSecAttrAccount];

// here goes the password value
[addDictionary setObject:passwordData forKey:(__bridge id<NSCopying>)(kSecValueData)];

OSStatus sanityCheck = SecItemAdd((__bridge CFDictionaryRef)(queryDictionary), NULL)
if (sanityCheck != noErr)
{
   // if no error the password got successfully stored in the keychain
}

更好的代码,更少的错误,请访问此链接:https://dev59.com/33fZa4cB1Zd3GeqPWM1W - Bill Cheswick

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接