Created
July 15, 2012 11:18
-
-
Save mikeabdullah/3116322 to your computer and use it in GitHub Desktop.
Safely wrapping keychain passwords with NSString/CFString
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void freeKeychainContent(void *ptr, void *info) | |
{ | |
SecKeychainItemFreeContent(NULL, ptr); | |
} | |
- (NSString *)passwordFromKeychainItem:(SecKeychainItemRef)keychainItem | |
{ | |
void *passwordData; | |
UInt32 passwordLength; | |
OSStatus status = SecKeychainItemCopyContent(keychainItem, | |
NULL, NULL, | |
&passwordLength, &passwordData); | |
if (status != errSecSuccess) return nil; | |
// Password data must be freed using special keychain APIs | |
// Do so with a specially crafted CFString | |
CFAllocatorContext context = { | |
0, | |
NULL, | |
NULL, NULL, // don't do retain/release | |
NULL, | |
NULL, NULL, // no need to alloc or realloc | |
freeKeychainContent, | |
NULL }; | |
CFAllocatorRef deallocator = CFAllocatorCreate(NULL, &context); | |
NSString *result = CFStringCreateWithBytesNoCopy(NULL, | |
passwordData, passwordLength, | |
kCFStringEncodingUTF8, false, | |
deallocator); | |
CFRelease(deallocator); | |
return [(NSString *)result autorelease]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment