Search code examples
objective-cmacoskeychain

Trying to add RSA private key to Keychain on macOS fails with -25303 errSecNoSuchAttr


I am trying to add an existing private key, coming from a .pem encoded certificate to the macOS keychain. But when trying the following it returns the status -25303 errSecNoSuchAttr

    std::vector<unsigned char> private_key_data = .. private data loaded ..

    NSString *keychain_label = "private-key.keychain.label";
    NSData *keychain_label_data = [keychain_label dataUsingEncoding:NSUTF8StringEncoding];

    OSStatus status = errSecBadReq;

    // store private key
    NSData *private_key_data = [[NSData alloc] initWithBytes:private_key_data.data() length:private_key_data.size()];
    NSDictionary *private_key_entry_query = @{
        (__bridge id) kSecClass : (__bridge id) kSecClassKey,
        (__bridge id) kSecAttrKeyType : (__bridge id) kSecAttrKeyTypeRSA,
        (__bridge id) kSecAttrApplicationTag : keychain_label_data,
        (__bridge id) kSecAttrKeyClass : (id)kSecAttrKeyClassPrivate,
        (__bridge id) kSecValueData : private_key_data,
        (__bridge id) kSecAttrKeySizeInBits : [NSNumber numberWithUnsignedInteger:2048],
        (__bridge id) kSecAttrEffectiveKeySize : [NSNumber numberWithUnsignedInteger:2048],
        (__bridge id) kSecAttrCanDerive : (__bridge id) kCFBooleanFalse,
        (__bridge id) kSecAttrCanEncrypt : (__bridge id) kCFBooleanTrue,
        (__bridge id) kSecAttrCanDecrypt : (__bridge id) kCFBooleanFalse,
        (__bridge id) kSecAttrCanVerify : (__bridge id) kCFBooleanTrue,
        (__bridge id) kSecAttrCanSign : (__bridge id) kCFBooleanFalse,
        (__bridge id) kSecAttrCanWrap : (__bridge id) kCFBooleanTrue,
        (__bridge id) kSecAttrCanUnwrap : (__bridge id) kCFBooleanFalse
    };

    status = SecItemAdd((__bridge CFDictionaryRef)private_key_entry_query, nullptr);
    if (status != errSecSuccess)
    {
        return false;
    }

I tried playing around with the different attributes but to no avail. Is there anything I am missing?


Solution

  • Not really the answer I was looking for, but I was unable to solve using SecItemAdd while maintaining the option to query the key, so eventually I resorted to SecItemImport to make things work.