尝试将 RSA 私钥添加到 macOS 上的钥匙串失败并显示 -25303 errSecNoSuchAttr

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

我正在尝试将来自 .pem 编码证书的现有私钥添加到 macOS 钥匙串。但是当尝试以下时 returns 状态 -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;
    }

我尝试使用不同的属性,但无济于事。有什么我遗漏的吗?

这不是我真正想要的答案,但我无法在保持查询密钥的选项的同时使用 SecItemAdd 解决问题,所以最终我求助于 SecItemImport 来解决问题。