Keychain在每次调用中返回不同的值

时间:2015-10-21 12:06:42

标签: ios objective-c keychain

我有一个课程可以将NSDictionary保存到 KeyChain 中。它工作正常,但突然,当我尝试加载NSDictionary我得到零值。

这是班级:

//
//  KeyChainHandler.m
//
//

#import "KeyChainHandler.h"

#define IDENTIFIER @"Identifier"

@interface KeyChainHandler ()

@property (strong, nonatomic, readwrite) NSDictionary *applicationData;

@end

@implementation KeyChainHandler

// Make this class a singleton
static KeyChainHandler *instance = nil;

+ (KeyChainHandler*)sharedKeyChain
{
    @synchronized(self)
    {
        if (!instance) {
            instance = [[self alloc] init];
        }
    }
    return instance;
}

- (id)init
{
    self = [super init];
    if (self)
    {
        [self load];
    }
    return self;
}

- (void)saveObject:(NSDictionary*)data
{
    self.applicationData = data;
    [self storeDictionary:data toKeychainWithKey:IDENTIFIER];
}

- (NSDictionary*)load
{
    NSDictionary *data = [KeyChainHandler dictionaryFromKeychainWithKey:IDENTIFIER];
    self.applicationData = data;
    return data;
}

- (void)remove
{
    [self deleteDictionaryFromKeychainWithKey:IDENTIFIER];
}

- (void)storeDictionary:(NSDictionary*)data toKeychainWithKey:(NSString*)aKey
{
    // serialize dict
    NSData *serializedDictionary = [NSKeyedArchiver archivedDataWithRootObject:data];
    // encrypt in keychain
    // first, delete potential existing entries with this key (it won't auto update)
    [self remove];

    // setup keychain storage properties
    NSDictionary *storageQuery = @{
                                   (__bridge id)kSecAttrAccount:    aKey,
                                   (__bridge id)kSecValueData:      serializedDictionary,
                                   (__bridge id)kSecClass:          (__bridge id)kSecClassGenericPassword,
                                   (__bridge id)kSecAttrAccessible: (__bridge id)kSecAttrAccessibleWhenUnlocked
                                   };
    OSStatus osStatus = SecItemAdd((__bridge CFDictionaryRef)storageQuery, nil);
    if(osStatus != noErr) {
        // do someting with error
    }
}


+ (NSDictionary*)dictionaryFromKeychainWithKey:(NSString *)aKey
{
    // setup keychain query properties
    NSDictionary *readQuery = @{
                                (__bridge id)kSecAttrAccount: aKey,
                                (__bridge id)kSecReturnData: (id)kCFBooleanTrue,
                                (__bridge id)kSecClass:      (__bridge id)kSecClassGenericPassword
                                };

    CFDataRef serializedDictionary = NULL;
    OSStatus osStatus = SecItemCopyMatching((__bridge CFDictionaryRef)readQuery, (CFTypeRef *)&serializedDictionary);
    if(osStatus == noErr) {
        // deserialize dictionary
        NSData *data = (__bridge NSData *)serializedDictionary;
        NSDictionary *storedDictionary = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        return storedDictionary;
    }
    else {
        // do something with error
        return nil;
    }
}


- (void)deleteDictionaryFromKeychainWithKey:(NSString*)aKey
{
    // setup keychain query properties
    NSDictionary *deletableItemsQuery = @{
                                          (__bridge id)kSecAttrAccount:        aKey,
                                          (__bridge id)kSecClass:              (__bridge id)kSecClassGenericPassword,
                                          (__bridge id)kSecMatchLimit:         (__bridge id)kSecMatchLimitAll,
                                          (__bridge id)kSecReturnAttributes:   (id)kCFBooleanTrue
                                          };

    CFArrayRef itemList = nil;
    OSStatus osStatus = SecItemCopyMatching((__bridge CFDictionaryRef)deletableItemsQuery, (CFTypeRef *)&itemList);
    // each item in the array is a dictionary
    NSArray *itemListArray = (__bridge NSArray *)itemList;
    for (NSDictionary *item in itemListArray) {
        NSMutableDictionary *deleteQuery = [item mutableCopy];
        [deleteQuery setValue:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
        // do delete
        osStatus = SecItemDelete((__bridge CFDictionaryRef)deleteQuery);
        if(osStatus != noErr) {
            // do something with error
        }
    }
}

@end

当我AppDelegate打印[[KeyChainHandler sharedHandler] load];时,我会获得正确的数据,然后在登录屏幕上我尝试再次执行此操作,然后获得nil。然后,当我重新启动(仅使用CMD + R)应用程序时,我没有得到nil,我再次获得了正确的数据..

似乎有什么问题?也许它是某种Apple的错误?

1 个答案:

答案 0 :(得分:1)

为什么:调用[[KeyChainHandler sharedHandler] load];,属性已经在单例创建时加载,如果更改,属性也会更新。

您需要在nil中将属性设置为remove

而只是使用:

NSDictionary *dict = [KeyChainHandler sharedKeyChain].applicationData;

注意:代码为:sharedKeyChain,示例调用为:sharedHandler