简体   繁体   中英

Cant get private key from certificate

So, I having trouble to get the private key from the certificate. This is my first time working with certificates and I have tried to find a solution to this but I cant make i work. It's a console application and a need the key to sign a SOAP message/request.

Here is a code sample; (Let me know if you need anything more)

    public static X509Certificate2 FindCertificate(string issuedBy)
    {
        var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
        store.Open(OpenFlags.ReadOnly);

        //We gets the certificate from store
        var certificate = store.Certificates.Cast<X509Certificate2>().FirstOrDefault(c => c.Issuer.Contains($"CN={issuedBy}"));
        if (certificate.HasPrivateKey) // Result: True
        {
            //PrivateKey throws error: Keyset dosent exist
            var key = certificate.PrivateKey;

        }

        if (certificate == null)
        {
            throw new ArgumentException($"Could not find certificate issued by: '{issuedBy}'", nameof(issuedBy));
        }

        var expireDate = DateTime.Parse(certificate.GetExpirationDateString());

        if (expireDate < DateTime.Now)
        {
            throw new Exception($"Certificate has already expired: '{expireDate}'");
        }

      

        return certificate;
    }

我现在只需在管理员模式下启动 Visual Studio 就可以让它工作。

An alternative to your own solution (so you don't have to run VS in administrator mode is to give your own user privileges to read the private key.

  1. Open the certificate manager for your machine certificates (type in "certificates" in Windows home menu search and choose "Manage computer certificates"
  2. Find the certificate and right click -> "All Tasks" -> "Manage Private Keys..." 在此处输入图片说明
  3. Click "Add..."
  4. Type in your username (and click "Check Names" to see if you typed it in correctly) 在此处输入图片说明
  5. Click "OK" and "OK"

Now you should be able to run your application (and VS) normally with access to the private key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM