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

Anas Tina picture Anas Tina · Jul 11, 2017 · Viewed 10.5k times · Source

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!

Answer

Eduardo Lanfredi picture Eduardo Lanfredi · Sep 4, 2018

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