KeychainItemWrapper SecItemAdd报: -25299

https://stackoverflow.com/questions/24835625/keychainitemwrapper-weird-behavior-existing-non-existing-item-error-with-the-sa
遇到了跟这个提问一样的问题,使用官方的范例,在SecItemCopyMatching时返回-25300为找不到,但是SecItemAdd时却返回–25299说是已存在


result = SecItemAdd((CFDictionaryRef)[self dictionaryToSecItemFormat:keychainItemData], NULL);
NSAssert( result == noErr, @"Couldn't add the Keychain Item." );

在这个地方会跳出

有找到不少文章但是测试都没有成功,最后按照上面链接采纳的第一个答案,自己加了一个KeychainHelper的类

KeychainHelper.h


#import <UIKit/UIKit.h>

@interface KeychainHelper : NSObject
{
}

- (NSString*) getKeyChainItem:(NSString*)key;
- (BOOL) setKeyChainItem:(NSString*)key withValue:(NSString*)value;
- (NSMutableDictionary*)createKeyChainDict:(NSString*)key;
@end

KeychainHelper.m


#import "KeychainHelper.h"
#import <Security/Security.h>

@implementation KeychainHelper

- (NSString*) getKeyChainItem:(NSString*)key {
NSString* keyChainValue = NULL;
NSData *attributes = NULL;

NSMutableDictionary* keyChainParams = [self createKeyChainDict:key];
[keyChainParams setObject:key forKey:(id)kSecAttrService];
[keyChainParams setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];

if (SecItemCopyMatching((CFDictionaryRef)keyChainParams, (CFTypeRef *)&attributes) == noErr)
{
keyChainValue = [[[NSString alloc] initWithBytes:[attributes bytes] length:[attributes length]
encoding:NSUTF8StringEncoding] autorelease];
}
return keyChainValue;
}

- (BOOL) setKeyChainItem:(NSString*)key withValue:(NSString*)value {
NSMutableDictionary* keyChainParams = [self createKeyChainDict:key];
[keyChainParams setObject:[value dataUsingEncoding:NSUTF8StringEncoding] forKey:(id)kSecValueData];

return SecItemAdd((CFDictionaryRef)keyChainParams, NULL) == noErr;
}

- (NSMutableDictionary*)createKeyChainDict:(NSString*)key {
NSMutableDictionary* keyChainParams = [[NSMutableDictionary alloc] init];
[keyChainParams setObject:(id)kSecClassGenericPassword forKey:(id)kSecClass];
[keyChainParams setObject:@"" forKey:(id)kSecAttrLabel];
[keyChainParams setObject:@"" forKey:(id)kSecAttrDescription];
[keyChainParams setObject:key forKey:(id)kSecAttrService];
[keyChainParams setObject:key forKey:(id)kSecAttrAccount];
return keyChainParams;
}

@end

使用时:


KeychainHelper *keychainHelper = [[KeychainHelper alloc] init];

NSString *keychain_uuid = [keychainHelper getKeyChainItem:@"uuid"];//获取
[keychainHelper setKeyChainItem:@"uuid" withValue:@""];//保存

[keychainHelper release];

Leave a Reply

Your email address will not be published. Required fields are marked *