-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathOAToken_KeychainExtensions.m
95 lines (77 loc) · 3.22 KB
/
OAToken_KeychainExtensions.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//
// OAToken_KeychainExtensions.m
// TouchTheFireEagle
//
// Created by Jonathan Wight on 04/04/08.
// Copyright 2008 __MyCompanyName__. All rights reserved.
//
#import "OAToken_KeychainExtensions.h"
@implementation OAToken (OAToken_KeychainExtensions)
- (id)initWithKeychainUsingAppName:(NSString *)name serviceProviderName:(NSString *)provider
{
[super init];
SecKeychainItemRef item;
NSString *serviceName = [NSString stringWithFormat:@"%@::OAuth::%@", name, provider];
OSStatus status = SecKeychainFindGenericPassword(NULL,
strlen([serviceName UTF8String]),
[serviceName UTF8String],
0,
NULL,
NULL,
NULL,
&item);
if (status != noErr) {
return nil;
}
// from Advanced Mac OS X Programming, ch. 16
UInt32 length;
char *password;
SecKeychainAttribute attributes[8];
SecKeychainAttributeList list;
attributes[0].tag = kSecAccountItemAttr;
attributes[1].tag = kSecDescriptionItemAttr;
attributes[2].tag = kSecLabelItemAttr;
attributes[3].tag = kSecModDateItemAttr;
list.count = 4;
list.attr = attributes;
status = SecKeychainItemCopyContent(item, NULL, &list, &length, (void **)&password);
if (status == noErr) {
self.key = [[[NSString alloc] initWithBytes:list.attr[0].data
length:list.attr[0].length
encoding:NSUTF8StringEncoding] autorelease];
if (password != NULL) {
char passwordBuffer[1024];
if (length > 1023) {
length = 1023;
}
strncpy(passwordBuffer, password, length);
passwordBuffer[length] = '\0';
self.secret = [NSString stringWithUTF8String:passwordBuffer];
}
SecKeychainItemFreeContent(&list, password);
} else {
// TODO find out why this always works in i386 and always fails on ppc
NSLog(@"Error from SecKeychainItemCopyContent: %d", status);
return nil;
}
NSMakeCollectable(item);
return self;
}
- (OSStatus)storeInDefaultKeychainWithAppName:(NSString *)name serviceProviderName:(NSString *)provider
{
return [self storeInKeychain:NULL appName:name serviceProviderName:provider];
}
- (OSStatus)storeInKeychain:(SecKeychainRef)keychain appName:(NSString *)name serviceProviderName:(NSString *)provider
{
OSStatus status = SecKeychainAddGenericPassword(keychain,
[name length] + [provider length] + 9,
[[NSString stringWithFormat:@"%@::OAuth::%@", name, provider] UTF8String],
[self.key length],
[self.key UTF8String],
[self.secret length],
[self.secret UTF8String],
NULL
);
return status;
}
@end