我正在尝试访问安装在远程计算机上的证书存储中的 X509 证书的私钥。
虽然我可以访问远程服务器上的证书存储和证书,但当我调用 X509Certificate2 对象的 PrivateKey 属性时,我收到错误“System.Security.Cryptography.CryptographicException:密钥集不存在”。我已经完成了针对此错误的答案,但似乎没有一个对我有用。我已经验证调用我的代码的用户对远程机器上的私钥文件和文件夹具有权限。下面是我的代码
string storeName = "My";
if (!string.IsNullOrEmpty(machineName))
{
storeName = string.Format(@"\\{0}\My", machineName);
}
IntPtr storeHandle = NativeMethods.CertOpenStore(NativeMethods.CERT_STORE_PROV_SYSTEM, 0, 0, NativeMethods.CERT_SYSTEM_STORE_LOCAL_MACHINE, storeName);
if (storeHandle == IntPtr.Zero)
{
throw new CryptographicException(string.Format("Cannot connect to certificate Store: {0}", machineName));
}
IntPtr currentCertContext = IntPtr.Zero;
currentCertContext = NativeMethods.CertEnumCertificatesInStore(storeHandle, currentCertContext);
if (currentCertContext != IntPtr.Zero)
{
var cert = new X509Certificate2(currentCertContext);
var key = cert.PrivateKey; //Throws error
}
NativeMethods.CertCloseStore(storeHandle, 0);