Search code examples
macospasswordskeychain

SecKeychainFindGenericPassword not working for osx


Following a piece of code I am using to get the password stored in my custom Keychain

-(OSStatus *)getPasswordFromKeyChain:(NSString *)username{
OSStatus status;

[self createKeyChainIfNotExists];

const char *cService_name = "Mac Google Analytics App";
UInt32 service_length = strlen(cService_name);

const char *cUser_name = [username cStringUsingEncoding:NSUTF8StringEncoding];
UInt32 username_length = strlen(cUser_name);

void *passwordData = nil; 
SecKeychainItemRef itemRef = nil;
UInt32 passwordLength = nil;

status = SecKeychainFindGenericPassword(
                                        mSecKeychainRef,            // default keychain
                                        service_length,  // length of service name
                                        cService_name,    // service name
                                        username_length,// length of account name
                                        cUser_name,    // account name
                                        &passwordLength,  // length of password
                                        passwordData,        // pointer to password data
                                        NULL             // the item reference
                                        );

return status;
}

I wonder what is wrong in this code, as the it never comes out of this call:

SecKeychainFindGenericPassword

It's pointed to the error shown here.


Solution

  • Pass null for the default keychain, and you need a pointer to the passwordData. That should at least get you a return status to tell if the strings are correct for your service & account.

        status = SecKeychainFindGenericPassword(NULL,            // default keychain
                                                service_length,  // length of service name
                                                cService_name,    // service name
                                                username_length,// length of account name
                                                cUser_name,    // account name
                                                &passwordLength,  // length of password
                                                &passwordData,        // pointer to password data
                                                NULL             // the item reference
                                                );