forked from jeremangnr/JNKeychain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJNKeychain.m
73 lines (57 loc) · 2.17 KB
/
JNKeychain.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//
// JNKeychain.m
//
// Created by Jeremias Nunez on 5/10/13.
// Copyright (c) 2013 Jeremias Nunez. All rights reserved.
//
#import "JNKeychain.h"
@interface JNKeychain ()
+ (NSMutableDictionary *)getKeychainQuery:(NSString *)key;
@end
@implementation JNKeychain
+ (NSMutableDictionary *)getKeychainQuery:(NSString *)key
{
// see http://developer.apple.com/library/ios/#DOCUMENTATION/Security/Reference/keychainservices/Reference/reference.html
return [NSMutableDictionary dictionaryWithObjectsAndKeys:
(__bridge id)kSecClassGenericPassword, (__bridge id)kSecClass,
key, (__bridge id)kSecAttrService,
key, (__bridge id)kSecAttrAccount,
(__bridge id)kSecAttrAccessibleAfterFirstUnlock, (__bridge id)kSecAttrAccessible,
nil];
}
+ (void)saveValue:(id)data forKey:(NSString*)key
{
NSMutableDictionary *keychainQuery = [self getKeychainQuery:key];
// delete any previous value with this key
SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
[keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(__bridge id)kSecValueData];
SecItemAdd((__bridge CFDictionaryRef)keychainQuery, NULL);
}
+ (id)loadValueForKey:(NSString *)key
{
id value = nil;
NSMutableDictionary *keychainQuery = [self getKeychainQuery:key];
CFDataRef keyData = NULL;
[keychainQuery setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
[keychainQuery setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
if (SecItemCopyMatching((__bridge CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
@try {
value = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
}
@catch (NSException *e) {
NSLog(@"Unarchive of %@ failed: %@", key, e);
}
@finally {}
}
if (keyData) {
CFRelease(keyData);
}
return value;
}
+ (void)deleteValueForKey:(NSString *)key
{
NSMutableDictionary *keychainQuery = [self getKeychainQuery:key];
SecItemDelete((__bridge CFDictionaryRef)keychainQuery);
}
@end