如何在ios密钥链中手动存储?
对于我的应用程序,我必须以安全的方式存储用户名/密码,并考虑将其存储在系统密钥链中的最佳解决方案。最好的方法是什么?我是否需要像FDKeychain这样的强制键链工具,或者没有这样的包装器,有没有一种简单的方法可以做到这一点如何在ios密钥链中手动存储?,ios,objective-c,security,Ios,Objective C,Security,对于我的应用程序,我必须以安全的方式存储用户名/密码,并考虑将其存储在系统密钥链中的最佳解决方案。最好的方法是什么?我是否需要像FDKeychain这样的强制键链工具,或者没有这样的包装器,有没有一种简单的方法可以做到这一点 Thx您可以通过这种方式手动存储值(iOS7): 编辑:Martin R注意到,如果密钥已在使用中,SecItemAdd将失败。在这种情况下,必须调用SecItemUpdate NSString *key = @"full_name"; NSString *value =
Thx您可以通过这种方式手动存储值(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);
}
然后你可以像这样检索它:
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);
}
只要阅读,你会在那里找到你的答案你不需要像FDKeychain这样的强制性工具,但是如果你试图自己直接访问密钥链,你会遇到我在开发FDKeychain时遇到的所有问题。我强烈建议您将其分叉(或其他开源选项之一)并从那里开始,因为您在第一次使用时将错过大量的边缘案例。请注意(据我所知),如果已经存在具有给定键的对象,则SecItemAdd将失败。在这种情况下,必须调用SecItemUpdate。因此,我编写了FDKeychain