[英]How to store manually in ios keychain?
对于我的应用程序,我必须以安全的方式存储用户名/密码,并认为其最佳解决方案存储在系统钥匙串中。 最好的方法是什么? 我是否需要强制性的钥匙串工具,如FDKeychain,还是有一种简单的方法可以在没有这样的包装器的情况下完成它?
谢谢
您可以这种方式手动存储值(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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.