“System.Security.Cryptography.CryptographicException: Keyset does not exist” when reading private key from remote machine

主宰稳场 提交于 2019-12-10 23:55:17

问题


I am trying to access the private key of an X509 certificate intalled in a certificate store on a remote machine.

Whilst I can access the cert store and the certificate on the remote server, I get the error "System.Security.Cryptography.CryptographicException: Keyset does not exist" when I call the PrivateKey property of the X509Certificate2 object. I have been through answers given for this error but none of them seem to work for me. I have verified that the user calling my code has permissions on the private key file and folder on the remote machine. Below is my code

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

来源:https://stackoverflow.com/questions/21989024/system-security-cryptography-cryptographicexception-keyset-does-not-exist-whe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!