PrivateKey threw an exception of type System.Security.Cryptography.CryptographicException

Viewed 14141

I'm trying to use self-signed certificate using the following code:

X509Certificate2 cert = ToCertificate("CN=localhost");


public static X509Certificate2 ToCertificate(this string subjectName,
                                                StoreName name = StoreName.My,
                                                StoreLocation location = StoreLocation.LocalMachine
                                                )
    {
        X509Store store = new X509Store(name, location);

        store.Open(OpenFlags.ReadOnly);

        try
        {
            var cert = store.Certificates.OfType<X509Certificate2>().FirstOrDefault(c => c.Subject.Equals(subjectName, StringComparison.OrdinalIgnoreCase));

            return cert != null ? new X509Certificate2(cert) : null;
        }
        catch (Exception)
        {

            throw;
        }
        finally
        {
            store.Certificates.OfType<X509Certificate2>().ToList().ForEach(c => c.Reset());
            store.Close();
        }
    }

I am getting the following exception:

PrivateKey = 'cert.PrivateKey' threw an exception of type 'System.Security.Cryptography.CryptographicException'

enter image description here

I Tried this fix, and this fix

But still having the problem!

4 Answers

If you are debugging your application, try to open the Visual Studio as administrator. It solved the problem for me.

Running on IIS Express, the program uses your credentials to access the certificate, while on IIS the pool identity's credentials are used. You can easily check the certificate ACL to see who is allowed or not.

Follow these steps:

  1. Check what Application Pool your web site uses

Open Internet Information Services Manager, select Sites in the Connections tree on the left. Select your site in the middle panel and click Basic settings under Actions on the right panel.

  1. Check what identity the Application Pool uses

Select Application Pools in the Connections tree on the left and find the identity in the middle panel. It'll be probably "NETWORK SERVICE".

  1. Add read permissions for the identity used by Application Pool to your certificate

Open the Microsoft Management Console (mmc), add the Certificates snap-in for local Computer account and find your certificate under Personal certificates. Open its context menu, All Tasks and Manage Private Keys.... Click Add.., enter the identity ("NETWORK SERVICE") and click Check Names and OK. Under Permissions for allow only the Read permission.

You can read details in this question: How to give ASP.NET access to a private key in a certificate in the certificate store?

refer: Certificate private key throws CryptographicException under IIS Web Server

Related