Initial checkin. Passes tests on Mac and in iPhone simulator.
5 // Created by Jens Alfke on 3/26/09.
6 // Copyright 2009 Jens Alfke. All rights reserved.
9 #import "MYKeychainItem.h"
10 #import "MYCrypto_Private.h"
11 #import "MYErrorUtils.h"
14 NSString* const MYCSSMErrorDomain = @"CSSMErrorDomain";
17 @implementation MYKeychainItem
20 - (id) initWithKeychainItemRef: (MYKeychainItemRef)itemRef;
22 Assert(itemRef!=NULL);
32 @synthesize keychainItemRef=_itemRef;
36 if (_itemRef) CFRelease(_itemRef);
40 - (id) copyWithZone: (NSZone*)zone {
41 // As keys are immutable, it's not necessary to make copies of them. This makes it more efficient
42 // to use instances as NSDictionary keys or store them in NSSets.
46 - (BOOL) isEqual: (id)obj {
47 // Require the objects to be of the same class, so that a MYPublicKey will not be equal to a
48 // MYKeyPair with the same public key.
49 return (obj == self) ||
50 ([obj class] == [self class] && CFEqual(_itemRef, [obj keychainItemRef]));
54 return CFHash(_itemRef);
57 - (NSArray*) _itemList {
58 return $array((id)_itemRef);
62 - (CFDictionaryRef) asQuery {
63 return (CFDictionaryRef) $dict( {(id)kSecClass, (id)kSecClassKey},//FIX
64 {(id)kSecMatchItemList, self._itemList} );
69 - (MYKeychain*) keychain {
71 return [MYKeychain defaultKeychain];
73 MYKeychain *keychain = nil;
74 SecKeychainRef keychainRef = NULL;
75 if (check(SecKeychainItemCopyKeychain((SecKeychainItemRef)_itemRef, &keychainRef), @"SecKeychainItemCopyKeychain")) {
77 keychain = [[[MYKeychain alloc] initWithKeychainRef: keychainRef] autorelease];
78 CFRelease(keychainRef);
85 - (BOOL) removeFromKeychain {
87 return check(SecItemDelete(self.asQuery), @"SecItemDelete");
89 return check(SecKeychainItemDelete((SecKeychainItemRef)_itemRef), @"SecKeychainItemDelete");
95 #pragma mark DATA / METADATA ACCESSORS:
98 - (NSData*) _getContents: (OSStatus*)outError {
99 NSData *contents = nil;
104 *outError = SecKeychainItemCopyAttributesAndData(_itemRef, NULL, NULL, NULL, &length, &bytes);
105 if (!*outError && bytes) {
106 contents = [NSData dataWithBytes: bytes length: length];
107 SecKeychainItemFreeAttributesAndData(NULL, bytes);
113 + (NSData*) _getAttribute: (SecKeychainAttrType)attr ofItem: (MYKeychainItemRef)item {
116 NSDictionary *info = $dict( {(id)kSecClass, (id)kSecClassKey},
117 {(id)kSecMatchItemList, $array((id)item)},
118 {(id)kSecReturnAttributes, $true} );
119 CFDictionaryRef attrs;
120 if (!check(SecItemCopyMatching((CFDictionaryRef)info, (CFTypeRef*)&attrs), @"SecItemCopyMatching"))
122 CFTypeRef rawValue = CFDictionaryGetValue(attrs,attr);
123 value = rawValue ?[[(id)CFMakeCollectable(rawValue) retain] autorelease] :nil;
127 UInt32 format = kSecFormatUnknown;
128 SecKeychainAttributeInfo info = {.count=1, .tag=(UInt32*)&attr, .format=&format};
129 SecKeychainAttributeList *list = NULL;
131 if (check(SecKeychainItemCopyAttributesAndData((SecKeychainItemRef)item, &info,
132 NULL, &list, NULL, NULL),
133 @"SecKeychainItemCopyAttributesAndData")) {
135 if (list->count == 1)
136 value = [NSData dataWithBytes: list->attr->data
137 length: list->attr->length];
138 else if (list->count > 1)
139 Warn(@"Multiple values for keychain item attribute");
140 SecKeychainItemFreeAttributesAndData(list, NULL);
147 + (NSString*) _getStringAttribute: (SecKeychainAttrType)attr ofItem: (MYKeychainItemRef)item {
148 NSData *value = [self _getAttribute: attr ofItem: item];
149 if (!value) return nil;
150 const char *bytes = value.bytes;
151 size_t length = value.length;
152 if (length>0 && bytes[length-1] == 0)
153 length--; // Some values are null-terminated!?
154 NSString *str = [[NSString alloc] initWithBytes: bytes length: length
155 encoding: NSUTF8StringEncoding];
157 Warn(@"MYKeychainItem: Couldn't decode attr value as string");
158 return [str autorelease];
161 - (NSString*) stringValueOfAttribute: (SecKeychainAttrType)attr {
162 return [[self class] _getStringAttribute: attr ofItem: _itemRef];
166 + (BOOL) _setAttribute: (SecKeychainAttrType)attr ofItem: (MYKeychainItemRef)item
167 stringValue: (NSString*)stringValue
170 id value = stringValue ?(id)stringValue :(id)[NSNull null];
171 NSDictionary *query = $dict({(id)kSecClass, (id)kSecClassKey},
172 {(id)kSecAttrKeyType, (id)attr},
173 {(id)kSecMatchItemList, $array((id)item)});
174 NSDictionary *attrs = $dict({(id)attr, value});
175 return check(SecItemUpdate((CFDictionaryRef)query, (CFDictionaryRef)attrs), @"SecItemUpdate");
178 NSData *data = [stringValue dataUsingEncoding: NSUTF8StringEncoding];
179 SecKeychainAttribute attribute = {.tag=attr, .length=data.length, .data=(void*)data.bytes};
180 SecKeychainAttributeList list = {.count=1, .attr=&attribute};
181 return check(SecKeychainItemModifyAttributesAndData((SecKeychainItemRef)item, &list, 0, NULL),
182 @"SecKeychainItemModifyAttributesAndData");
186 - (BOOL) setValue: (NSString*)valueStr ofAttribute: (SecKeychainAttrType)attr {
187 return [[self class] _setAttribute: attr ofItem: _itemRef stringValue: valueStr];
196 BOOL check(OSStatus err, NSString *what) {
199 if (err < -2000000000)
200 return checkcssm(err,what);
202 Warn(@"MYCrypto error, %@: %@", what, MYErrorName(NSOSStatusErrorDomain,err));
209 BOOL checkcssm(CSSM_RETURN err, NSString *what) {
210 if (err != CSSM_OK) {
211 Warn(@"MYCrypto error, %@: %@", what, MYErrorName(MYCSSMErrorDomain,err));