如何从证书中获取有效的 CNG 私钥句柄

问题描述

我正在尝试获取一个 CNG 私钥句柄来对每个证书的数据进行签名。 但首先,我很难获得有效的密钥句柄。

通过指纹的证书查找工作正常。我收到了提供私钥的自签名证书的上下文。

据报告 CryptAcquireCertificatePrivateKey调用成功,LKeyHandle内容非零且 LKeySpec 描述了 Ncrypt 密钥。

不过,NCryptIsKeyHandle 总是返回 False。因此,我的代码引发了异常。 请帮助我理解为什么 LKeyHandle 无效。

FCertStore := CertOpenStore(CERT_STORE_PROV_SYstem,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,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;

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)