从远程机器读取私钥时出现“System.Security.Cryptography.CryptographicException:Keyset不存在”

时间:2014-02-24 13:20:15

标签: x509certificate x509certificate2 keyset

我正在尝试访问远程计算机上的证书存储中安装的X509证书的私钥。

虽然我可以访问远程服务器上的证书存储区和证书,但当我调用X509Certificate2对象的PrivateKey属性时,出现错误“System.Security.Cryptography.CryptographicException:Keyset不存在”。我已经通过了这个错误的答案,但它们似乎都不适合我。我已经验证调用我的代码的用户对远程计算机上的私钥文件和文件夹具有权限。以下是我的代码

            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);

0 个答案:

没有答案