gpt4 book ai didi

ios - 如何在 ios 钥匙串(keychain)中手动存储?

转载 作者:可可西里 更新时间:2023-11-01 05:41:15 24 4
gpt4 key购买 nike

对于我的应用程序,我必须以安全的方式存储用户名/密码,并认为最好的解决方案是将其存储在系统钥匙串(keychain)中。最好的方法是什么?我是否需要像 FDKeychain 这样的强制性钥匙串(keychain)工具,或者在没有此类包装器的情况下是否有一种简单的方法可以做到这一点?

谢谢

最佳答案

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

编辑:Martin R 指出,如果 key 已在使用中,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);
}

关于ios - 如何在 ios 钥匙串(keychain)中手动存储?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20587114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com