Skip to content

Instantly share code, notes, and snippets.

@franzwong
Last active November 12, 2022 05:24
Show Gist options
  • Save franzwong/e97109fee6c67ca9c532c1f0869e6abb to your computer and use it in GitHub Desktop.
Save franzwong/e97109fee6c67ca9c532c1f0869e6abb to your computer and use it in GitHub Desktop.
Add generic password to MacOS Keychain with C
// Build: gcc -framework Security -framework Foundation -o add_generic_password add_generic_password.c
// Usage: ./add_generic_password <service name> <username> <password>
#include <CoreFoundation/CoreFoundation.h>
#include <Security/Security.h>
int main(int argc, const char* argv[]) {
if (argc < 4) {
fprintf(stderr, "Usage: ./add_generic_pasword <service name> <username> <password>");
return 1;
}
const char* serviceName = argv[1];
const char* userName = argv[2];
const char* password = argv[3];
CFStringRef keys[4];
keys[0] = kSecClass;
keys[1] = kSecAttrService;
keys[2] = kSecAttrAccount;
keys[3] = kSecValueData;
CFTypeRef values[4];
values[0] = kSecClassGenericPassword;
values[1] = CFStringCreateWithCString(kCFAllocatorDefault, serviceName, kCFStringEncodingUTF8);
values[2] = CFStringCreateWithCString(kCFAllocatorDefault, userName, kCFStringEncodingUTF8);
values[3] = CFStringCreateWithCString(kCFAllocatorDefault, password, kCFStringEncodingUTF8);
CFDictionaryRef query = CFDictionaryCreate(kCFAllocatorDefault, (const void**) keys, (const void**) values, 4, NULL, NULL);
OSStatus result = SecItemAdd(query, NULL);
printf("Result: %d\n", result);
CFRelease(values[1]);
CFRelease(values[2]);
CFRelease(values[3]);
CFRelease(query);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment