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'
I Tried this fix, and this fix
But still having the problem!