-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathKeychainUtil.m
More file actions
executable file
·615 lines (534 loc) · 16.8 KB
/
KeychainUtil.m
File metadata and controls
executable file
·615 lines (534 loc) · 16.8 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//
// KeychainUtil.m
// iPhoneLib,
// Helper Functions and Classes for Ordinary Application Development on iPhone
//
// Created by meinside on 09. 07. 19.
//
// last update: 13.04.02.
//
#import "KeychainUtil.h"
@implementation KeychainUtil
#pragma mark -
#pragma mark factory functions
+ (NSMutableDictionary*)dictionaryOfGenericPasswdForAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
accessGroup:(NSString*)group
{
NSMutableDictionary* dic = [[NSMutableDictionary alloc] init];
NSData* identifier = [key dataUsingEncoding:NSUTF8StringEncoding];
[dic setObject:identifier
forKey:(id)kSecAttrGeneric];
[dic setObject:account
forKey:(id)kSecAttrAccount];
[dic setObject:service
forKey:(id)kSecAttrService];
[dic setObject:(id)kSecClassGenericPassword
forKey:(id)kSecClass];
if(group)
[dic setObject:group
forKey:(id)kSecAttrAccessGroup];
return [dic autorelease];
}
+ (NSMutableDictionary*)dictionaryOfGenericPasswdForAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
{
return [KeychainUtil dictionaryOfGenericPasswdForAccount:account
service:service
passwdKey:key
accessGroup:nil];
}
#pragma mark -
#pragma mark C/R/U/D functions
+ (NSMutableDictionary*)searchDictionaryOfGenericPasswdForAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
accessGroup:(NSString*)group
{
NSMutableDictionary* dic = [KeychainUtil dictionaryOfGenericPasswdForAccount:account
service:service
passwdKey:key
accessGroup:group];
[dic setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
[dic setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnAttributes];
[dic setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
return dic;
}
+ (BOOL)saveGenericPasswd:(NSData*)data
forAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
accessGroup:(NSString*)group
overwrite:(BOOL)overwrite
{
NSMutableDictionary* dic = [KeychainUtil dictionaryOfGenericPasswdForAccount:account
service:service
passwdKey:key
accessGroup:group];
[dic setObject:data forKey:(id)kSecValueData];
OSStatus status = SecItemAdd((CFDictionaryRef)dic, NULL);
if(status == noErr)
{
return YES;
}
else if(status == errSecDuplicateItem && overwrite == YES)
{
return [KeychainUtil updateGenericPasswd:data
forAccount:account
service:service
passwdKey:key
accessGroup:group];
}
return NO;
}
+ (BOOL)saveGenericPasswd:(NSData*)data
forAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
overwrite:(BOOL)overwrite
{
return [KeychainUtil saveGenericPasswd:data
forAccount:account
service:service
passwdKey:key
accessGroup:nil
overwrite:overwrite];
}
+ (BOOL)updateGenericPasswd:(NSData*)data
forAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
accessGroup:(NSString*)group
{
NSMutableDictionary* dic = [KeychainUtil dictionaryOfGenericPasswdForAccount:account
service:service
passwdKey:key
accessGroup:group];
NSMutableDictionary* updateDic = [NSMutableDictionary dictionary];
[updateDic setObject:data forKey:(id)kSecValueData];
OSStatus status = SecItemUpdate((CFDictionaryRef)dic, (CFDictionaryRef)updateDic);
if(status == noErr)
return YES;
else
return NO;
}
+ (BOOL)updateGenericPasswd:(NSData*)data
forAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
{
return [KeychainUtil updateGenericPasswd:data
forAccount:account
service:service
passwdKey:key
accessGroup:nil];
}
+ (NSMutableDictionary*)loadDictionaryOfGenericPasswdForAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
accessGroup:(NSString*)group
{
NSMutableDictionary* searchDic = [KeychainUtil searchDictionaryOfGenericPasswdForAccount:account
service:service
passwdKey:key
accessGroup:group];
NSMutableDictionary* dic = nil;
OSStatus status = SecItemCopyMatching((CFDictionaryRef)searchDic, (CFTypeRef*)&dic);
if(status == noErr)
return [dic autorelease];
else
return nil;
}
+ (NSData*)loadGenericPasswdForAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
accessGroup:(NSString*)group
{
NSMutableDictionary* dic = [KeychainUtil loadDictionaryOfGenericPasswdForAccount:account
service:service
passwdKey:key
accessGroup:group];
if(dic)
return [KeychainUtil dataFromDictionary:dic];
else
return nil;
}
+ (NSString*)loadPasswdStringForAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
accessGroup:(NSString*)group
{
NSMutableDictionary* dic = [KeychainUtil loadDictionaryOfGenericPasswdForAccount:account
service:service
passwdKey:key
accessGroup:group];
if(dic)
{
NSString* resultString = [[NSString alloc] initWithData:[dic objectForKey:(id)kSecValueData] encoding:NSUTF8StringEncoding];
return [resultString autorelease];
}
else
return nil;
}
+ (NSString*)loadPasswdStringForAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
{
return [KeychainUtil loadPasswdStringForAccount:account
service:service
passwdKey:key
accessGroup:nil];
}
+ (NSData*)loadPasswdDataForAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
accessGroup:(NSString*)group
{
NSMutableDictionary* dic = [KeychainUtil loadDictionaryOfGenericPasswdForAccount:account
service:service
passwdKey:key
accessGroup:group];
if(dic)
return [dic objectForKey:(id)kSecValueData];
else
return nil;
}
+ (NSData*)loadPasswdDataForAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
{
return [KeychainUtil loadPasswdDataForAccount:account
service:service
passwdKey:key
accessGroup:nil];
}
+ (BOOL)deleteGenericPasswdForAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
accessGroup:(NSString*)group
{
NSMutableDictionary* dic = [KeychainUtil dictionaryOfGenericPasswdForAccount:account
service:service
passwdKey:key
accessGroup:group];
OSStatus status = SecItemDelete((CFDictionaryRef)dic);
if(status == noErr)
return YES;
else
return NO;
}
+ (BOOL)deleteGenericPasswdForAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
{
return [KeychainUtil deleteGenericPasswdForAccount:account
service:service
passwdKey:key
accessGroup:nil];
}
+ (BOOL)genericPasswdExistsForAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
accessGroup:(NSString*)group
{
NSMutableDictionary* searchDic = [KeychainUtil searchDictionaryOfGenericPasswdForAccount:account
service:service
passwdKey:key
accessGroup:group];
NSMutableDictionary* dic = nil;
OSStatus status = SecItemCopyMatching((CFDictionaryRef)searchDic, (CFTypeRef*)&dic);
[dic release];
if(status == noErr)
return YES;
else if(status == errSecItemNotFound)
return NO;
else
return NO;
}
+ (BOOL)genericPasswdExistsForAccount:(NSString*)account
service:(NSString*)service
passwdKey:(NSString*)key
{
return [KeychainUtil genericPasswdExistsForAccount:account
service:service
passwdKey:key
accessGroup:nil];
}
#pragma mark -
#pragma mark helper functions
+ (NSData*)dataFromDictionary:(NSMutableDictionary*)dic
{
if(dic == nil)
return nil;
NSString* errorString;
NSData* data = [NSPropertyListSerialization dataFromPropertyList:dic
format:NSPropertyListBinaryFormat_v1_0
errorDescription:&errorString];
return data;
}
+ (NSMutableDictionary*)dictionaryFromData:(NSData*)data
{
if(data == nil)
return nil;
NSString* errorString;
NSMutableDictionary* dic = [NSPropertyListSerialization propertyListFromData:data
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:NULL
errorDescription:&errorString];
return dic;
}
+ (NSString*)fetchStatus:(OSStatus)status
{
if(status == 0)
return @"success";
else if(status == errSecNotAvailable)
return @"no trust results available";
else if(status == errSecItemNotFound)
return @"the item cannot be found";
else if(status == errSecParam)
return @"parameter error";
else if(status == errSecAllocate)
return @"memory allocation error";
else if(status == errSecInteractionNotAllowed)
return @"user interaction not allowd";
else if(status == errSecUnimplemented)
return @"not implemented";
else if(status == errSecDuplicateItem)
return @"item already exists";
else if(status == errSecDecode)
return @"unable to decode data";
else
return [NSString stringWithFormat:@"%ld", status];
}
#pragma mark -
#pragma mark functions for debug purpose
//from: https://devforums.apple.com/message/123846#123846
+ (void)resetCredentials
{
OSStatus err;
err = SecItemDelete((CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassIdentity, kSecClass,
nil]);
assert(err == noErr);
err = SecItemDelete((CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassCertificate, kSecClass,
nil]);
assert(err == noErr);
err = SecItemDelete((CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassKey, kSecClass,
nil]);
assert(err == noErr);
err = SecItemDelete((CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassGenericPassword, kSecClass,
nil]);
assert(err == noErr);
err = SecItemDelete((CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassInternetPassword, kSecClass,
nil]);
assert(err == noErr);
}
+ (void)_printCertificate:(SecCertificateRef)certificate attributes:(NSDictionary *)attrs indent:(int)indent
{
CFStringRef summary;
NSString* label;
NSData* hash;
summary = SecCertificateCopySubjectSummary(certificate);
assert(summary != NULL);
label = [attrs objectForKey:(id)kSecAttrLabel];
if (label != nil)
{
fprintf(stderr, "%*slabel = '%s'\n", indent, "", [label UTF8String]);
}
fprintf(stderr, "%*ssummary = '%s'\n", indent, "", [(NSString *)summary UTF8String]);
hash = [attrs objectForKey:(id)kSecAttrPublicKeyHash];
if (hash != nil)
{
fprintf(stderr, "%*shash = %s\n", indent, "", [[hash description] UTF8String]);
}
CFRelease(summary);
}
+ (void)_printKey:(SecKeyRef)key
attributes:(NSDictionary *)attrs
indent:(int)indent
{
#pragma unused(key)
NSString* label;
CFTypeRef keyClass;
label = [attrs objectForKey:(id)kSecAttrLabel];
if (label != nil)
{
fprintf(stderr, "%*slabel = '%s'\n", indent, "", [label UTF8String]);
}
label = [attrs objectForKey:(id)kSecAttrApplicationLabel];
if (label != nil)
{
fprintf(stderr, "%*sapp label = %s\n", indent, "", [[label description] UTF8String]);
}
label = [attrs objectForKey:(id)kSecAttrApplicationTag];
if (label != nil)
{
fprintf(stderr, "%*sapp tag = %s\n", indent, "", [[label description] UTF8String]);
}
//test
// NSArray* keys = [attrs allKeys];
// for(int i=0; i<[keys count]; i++)
// {
// NSLog(@"key: %@ => value: %@", [keys objectAtIndex:i], [attrs objectForKey:[keys objectAtIndex:i]]);
// }
keyClass = (CFTypeRef) [attrs objectForKey:(id)kSecAttrKeyClass];
if (keyClass != nil)
{
const char* keyClassStr;
// keyClass is a CFNumber whereas kSecAttrKeyClassPublic (and so on)
// are CFStrings. Gosh, that makes things hard <rdar://problem/6914637>.
// So I compare their descriptions. Yuck!
if ([[(id)keyClass description] isEqual:(id)kSecAttrKeyClassPublic])
{
keyClassStr = "kSecAttrKeyClassPublic";
}
else if ([[(id)keyClass description] isEqual:(id)kSecAttrKeyClassPrivate])
{
keyClassStr = "kSecAttrKeyClassPrivate";
}
else if ([[(id)keyClass description] isEqual:(id)kSecAttrKeyClassSymmetric])
{
keyClassStr = "kSecAttrKeyClassSymmetric";
}
else
{
keyClassStr = "?";
}
fprintf(stderr, "%*skey class = %s\n", indent, "", keyClassStr);
}
}
+ (void)_printIdentity:(SecIdentityRef)identity
attributes:(NSDictionary *)attrs
{
OSStatus err;
SecCertificateRef certificate;
SecKeyRef key;
err = SecIdentityCopyCertificate(identity, &certificate);
assert(err == noErr);
err = SecIdentityCopyPrivateKey(identity, &key);
assert(err == noErr);
fprintf(stderr, " certificate\n");
[self _printCertificate:certificate
attributes:attrs
indent:6];
fprintf(stderr, " key\n");
[self _printKey:key
attributes:attrs
indent:6];
CFRelease(key);
CFRelease(certificate);
}
+ (void)_printPassword:(CFStringRef)password
attributes:(NSDictionary *)attrs
indent:(int)indent
{
NSString* generic;
NSString* account;
NSString* label;
NSString* value;
generic = [attrs objectForKey:(id)kSecAttrGeneric];
if (generic != nil)
{
fprintf(stderr, "%*sgeneric = '%s'\n", indent, "", [[generic description] UTF8String]);
}
account = [attrs objectForKey:(id)kSecAttrAccount];
if (account != nil)
{
fprintf(stderr, "%*saccount = '%s'\n", indent, "", [account UTF8String]);
}
label = [attrs objectForKey:(id)kSecAttrLabel];
if (label != nil)
{
fprintf(stderr, "%*slabel = '%s'\n", indent, "", [label UTF8String]);
}
value = [attrs objectForKey:(id)kSecValueData];
if (value != nil)
{
NSString* valueStr = [[NSString alloc] initWithData:(NSData*)value
encoding:NSUTF8StringEncoding];
fprintf(stderr, "%*svalue = %s\n", indent, "", [value UTF8String]);
[valueStr release];
}
}
+ (void)_printCertificate:(SecCertificateRef)certificate
attributes:(NSDictionary *)attrs
{
[self _printCertificate:certificate
attributes:attrs
indent:4];
}
+ (void)_printKey:(SecKeyRef)key
attributes:(NSDictionary *)attrs
{
[self _printKey:key
attributes:attrs
indent:4];
}
+ (void)_printPassword:(CFStringRef)password
attributes:(NSDictionary *)attrs
{
[self _printPassword:password
attributes:attrs
indent:4];
}
+ (void)_dumpCredentialsOfSecClass:(CFTypeRef)secClass
printSelector:(SEL)printSelector
{
OSStatus err;
CFArrayRef result;
CFIndex resultCount;
CFIndex resultIndex;
result = NULL;
err = SecItemCopyMatching((CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:
(id)secClass, kSecClass,
kSecMatchLimitAll, kSecMatchLimit,
kCFBooleanTrue, kSecReturnRef,
kCFBooleanTrue, kSecReturnAttributes,
nil],
(CFTypeRef *) &result);
if (result != NULL)
{
assert( CFGetTypeID(result) == CFArrayGetTypeID() );
resultCount = CFArrayGetCount(result);
for (resultIndex = 0; resultIndex < resultCount; resultIndex++)
{
NSDictionary * thisResult;
fprintf(stderr, " %zd\n", (ssize_t) resultIndex);
thisResult = (NSDictionary *) CFArrayGetValueAtIndex(result, resultIndex);
if ((secClass == kSecClassGenericPassword) || (secClass == kSecClassInternetPassword))
{
[self performSelector:printSelector withObject:[thisResult objectForKey:(NSString *)kSecValueData] withObject:thisResult];
}
else
{
[self performSelector:printSelector withObject:[thisResult objectForKey:(NSString *)kSecValueRef] withObject:thisResult];
}
}
CFRelease(result);
}
}
+ (void)dumpCredentials
{
fprintf(stderr, "identities:\n");
[self _dumpCredentialsOfSecClass:kSecClassIdentity
printSelector:@selector(_printIdentity:attributes:)];
fprintf(stderr, "certificates:\n");
[self _dumpCredentialsOfSecClass:kSecClassCertificate
printSelector:@selector(_printCertificate:attributes:)];
fprintf(stderr, "keys:\n");
[self _dumpCredentialsOfSecClass:kSecClassKey
printSelector:@selector(_printKey:attributes:)];
fprintf(stderr, "generic passwords:\n");
[self _dumpCredentialsOfSecClass:kSecClassGenericPassword
printSelector:@selector(_printPassword:attributes:)];
fprintf(stderr, "internet passwords:\n");
[self _dumpCredentialsOfSecClass:kSecClassInternetPassword
printSelector:@selector(_printPassword:attributes:)];
}
@end