首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ios密钥链中手动存储?

如何在ios密钥链中手动存储?
EN

Stack Overflow用户
提问于 2013-12-14 19:09:36
回答 1查看 690关注 0票数 6

对于我的应用程序,我必须以安全的方式存储用户名/密码,并认为最好的解决方案是将用户名/密码存储在系统密钥链中。最好的办法是什么?我是否需要强制使用像FDKeychain这样的密钥链工具,或者没有这样的包装器就可以轻松地完成它?

Thx

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-12-14 19:13:27

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

编辑: Martin注意到,如果密钥已经在使用中,SecItemAdd就会失败。在这种情况下,必须调用SecItemUpdate。

代码语言:javascript
复制
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);
}

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

代码语言:javascript
复制
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);
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20587114

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档