-
Notifications
You must be signed in to change notification settings - Fork 3
/
KFKeychain.m
59 lines (45 loc) · 2.02 KB
/
KFKeychain.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#import "KFKeychain.h"
@implementation KFKeychain
+ (BOOL)checkOSStatus:(OSStatus)status {
return status == noErr;
}
+ (NSMutableDictionary *)keychainQueryForKey:(NSString *)key {
return [@{(__bridge id)kSecClass : (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrService : key,
(__bridge id)kSecAttrAccount : key,
(__bridge id)kSecAttrAccessible : (__bridge id)kSecAttrAccessibleAfterFirstUnlock
} mutableCopy];
}
+ (BOOL)saveObject:(id)object forKey:(NSString *)key {
NSMutableDictionary *keychainQuery = [self keychainQueryForKey:key];
// Deleting previous object with this key, because SecItemUpdate is more complicated.
[self deleteObjectForKey:key];
[keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:object] forKey:(__bridge id)kSecValueData];
return [self checkOSStatus:SecItemAdd((__bridge CFDictionaryRef)keychainQuery, NULL)];
}
+ (id)loadObjectForKey:(NSString *)key {
id object = nil;
NSMutableDictionary *keychainQuery = [self keychainQueryForKey:key];
[keychainQuery setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
[keychainQuery setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
CFDataRef keyData = NULL;
if ([self checkOSStatus:SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData)]) {
@try {
object = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
}
@catch (NSException *exception) {
NSLog(@"Unarchiving for key %@ failed with exception %@", key, exception.name);
object = nil;
}
@finally {}
}
if (keyData) {
CFRelease(keyData);
}
return object;
}
+ (BOOL)deleteObjectForKey:(NSString *)key {
NSMutableDictionary *keychainQuery = [self keychainQueryForKey:key];
return [self checkOSStatus:SecItemDelete((__bridge CFDictionaryRef)keychainQuery)];
}
@end