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!
If you are debugging your application, try to open the Visual Studio as administrator. It solved the problem for me.
Sounds like your certificate uses CNG key storage to store the private key. In this case, PrivateKey
property will throw this exception when attempting to access the property.
In order to access the key properly, you have to use extension methods to access the key: https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2(v=vs.110).aspx#Extension Methods
Moreover, these extension methods are preferred when accessing any private key storage type, either legacy (CSP) or CNG. That is, do not access PrivateKey
and PublicKey
properties directly, instead, access them via these methods.
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:
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.
Select Application Pools in the Connections tree on the left and find the identity in the middle panel. It'll be probably "NETWORK SERVICE".
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With