harshc
harshc

Reputation: 97

OS X Keychain access using C/C++

I am trying to write a simple test application to access OS X keychain. Add/Update/Delete an entry using C/C++. I am just testing whether I can use this in a larger C/C++ code base that we have, where we need a secure secret storage, hence the language requirements.

I looked up the API that Apple has on this but that is mostly in Objective-C. Are there any solutions anyone is aware of? The only thing I could find was Apple's Security tool which seems old and am not sure if the APIs are still supported.

Thanks in advance.

Upvotes: 5

Views: 2416

Answers (1)

TheNextman
TheNextman

Reputation: 12566

A minimal example showing how to add a password to the keychain using C:

#include <CoreFoundation/CoreFoundation.h>
#include <Security/Security.h>

int main(int argc, const char* argv[]) {
    CFStringRef keys[3];
    keys[0] = kSecClass;
    keys[1] = kSecAttrAccount;
    keys[2] = kSecValueData;

    CFTypeRef values[3];
    values[0] = kSecClassGenericPassword;
    values[1] = CFSTR("accountname");
    values[2] = CFSTR("password");

    CFDictionaryRef query;
    query = CFDictionaryCreate(kCFAllocatorDefault, (const void**) keys, (const void**) values, 3, NULL, NULL);

    OSStatus result = SecItemAdd(query, NULL);

    printf("%d", result);

    return 0;
}

Upvotes: 6

Related Questions