对于我的应用程序,我必须以安全的方式存储用户名/密码,并认为最好的解决方案是将用户名/密码存储在系统密钥链中。最好的办法是什么?我是否需要强制使用像FDKeychain这样的密钥链工具,或者没有这样的包装器就可以轻松地完成它?
Thx
发布于 2013-12-14 19:13:27
您可以以这种方式手动存储值(iOS7):
编辑: Martin注意到,如果密钥已经在使用中,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);
}然后你可以像这样检索它:
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);
}https://stackoverflow.com/questions/20587114
复制相似问题