I am getting one of the following Exceptions while trying to get a private key from X509Certificate2 certificate:
System.Security.Cryptography.CryptographicException: Invalid provider type specified.
OR
System.Security.Cryptography.CryptographicException: Key does not exist at the following line of code: RSACryptoServiceProvider rsaKey = (RSACryptoServiceProvider)digiSignCert.PrivateKey;
Stacktrace:
System.Security.Cryptography.CryptographicException: Key does not exist. at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle) at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair() at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize) at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey() at Api.CertificateUtil.GetSignedXml(String xml, X509Certificate2 privateCert)
Code:
public static RSACryptoServiceProvider rsaKey = null;
public X509Certificate2 _PrivateCert;
public APISearch()
{
byte[] privateCert = null;//We get the actual certificate file data here
GetPrivateCerificate(privateCert, "abc@123");
GetSignedXml(_PrivateCert);
}
public void GetPrivateCerificate(byte[] privateCert, string pwd)
{
_PrivateCert = new X509Certificate2(privateCert, pwd, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
}
public void GetSignedXml(X509Certificate2 privateCert)
{
rsaKey = (RSACryptoServiceProvider)privateCert.PrivateKey; //Occassional Exception
}
Expected result: (RSACryptoServiceProvider)privateCert.PrivateKey
should always produce a private key.
Actual result: Sometimes the aforementioned exceptions are thrown at this line:
rsaKey = (RSACryptoServiceProvider)privateCert.PrivateKey;
and sometimes the private key is successfully being fetched from the certificate file. As of now, we have been unable to track the pattern of this problem.