title: Getting Exception "Invalid Provider type specified" or "Key does not exist" while getting Private key from X509Certificate2 Occasionally
body: <p>I am getting one of the following Exceptions while trying to get a private key from X509Certificate2 certificate:</p>
  
  <blockquote>
    <p>System.Security.Cryptography.CryptographicException: Invalid provider type specified.</p>
  </blockquote>
  
  <p>OR</p>
  
  <blockquote>
    <p>System.Security.Cryptography.CryptographicException: Key does not exist at the following line of code: RSACryptoServiceProvider rsaKey = (RSACryptoServiceProvider)digiSignCert.PrivateKey;</p>
  </blockquote>
  
  <p>Stacktrace:</p>
  
  <blockquote>
    <p>System.Security.Cryptography.CryptographicException: Key does not exist. at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle&amp; safeProvHandle, SafeKeyHandle&amp; 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)</p>
  </blockquote>
  
  <p>Code:</p>
  
  <pre><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
  }
  </code></pre>
  
  <p>Expected result: <code>(RSACryptoServiceProvider)privateCert.PrivateKey</code> should always produce a private key. </p>
  
  <p>Actual result: Sometimes the aforementioned exceptions are thrown at this line:</p>
  
  <p><code>rsaKey = (RSACryptoServiceProvider)privateCert.PrivateKey;</code></p>
  
  <p>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.</p>