How to acquire a valid CNG private key handle from a certificate

508 Views Asked by At

I am trying to acquire a CNG private key handle to sign data per a certificate. But I am struggling to get a valid key handle, in the first place.

The certificate lookup via fingerprint is working. I am recieving the context of a self signed certificate providing a private key.

The call of CryptAcquireCertificatePrivateKey is reportedly successful, content of LKeyHandle is nonzero and LKeySpec describes a Ncrypt key.

Still, NCryptIsKeyHandle always returns False. Thus, my code raises a exception. Please help me to understand why LKeyHandle isn't considered valid.

FCertStore := CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, 0,
                            CERT_SYSTEM_STORE_CURRENT_USER or CERT_STORE_READONLY_FLAG,
                            PWideChar('My'));

SetLength(LFingerprintHex, 20);
LSize := HexToBin(PWideChar('d159975092f813d8a17f97fbb3152f600daecdbc'), @LFingerPrintHex[0], 20);
SetLength(LFingerPrintHex, LSize);

LFingerprint.cbData := Length(LFingerPrintHex);
LFingerprint.pbData := @LFingerPrintHex[0];

LCertContext := CertFindCertificateInStore(FCertStore, X509_ASN_ENCODING or PKCS_7_ASN_ENCODING,
                                            0, CERT_FIND_SHA1_HASH,
                                            @LFingerprint, nil);

if CryptAcquireCertificatePrivateKey(LCertContext, $40000 {CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG},
                                    nil, LKeyHandle, @LKeySpec, @LFreeHandle) and
    (LKeySpec = $FFFF {CERT_NCRYPT_KEY_SPEC}) and
    not NCryptIsKeyHandle(LKeyHandle) then
begin
    raise Exception.Create('invalid handle'); // but why?
end;
0

There are 0 best solutions below