Skip to content

Instantly share code, notes, and snippets.

@mikeabdullah
Created July 15, 2012 11:18
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeabdullah/3116322 to your computer and use it in GitHub Desktop.
Save mikeabdullah/3116322 to your computer and use it in GitHub Desktop.
Safely wrapping keychain passwords with NSString/CFString
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