title: Exception when trying to read a PrivateKey from Windows certstore
body: <p>I created a private and public key pair using OpenSSL and then I generated a .p12 file to import it into my Windows certstore. The key pair and .p12 files were created in Windows XP and I am trying to use it in Windows 7.
  I am trying to access the key from within a Web Service (.svc) in IIS.
  If I try to read the private key from a standalone app, I can do it without any problems, but when I try to read it from my web app, I always get the following exception:</p>
  
  <pre><code>'cert.PrivateKey' threw an exception of type 'System.Security.Cryptography.CryptographicException'
  </code></pre>
  
  <p>And this is the whole stacktrace:</p>
  
  <pre><code>en System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
  en System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle&amp; safeProvHandle, SafeKeyHandle&amp; safeKeyHandle)
  en System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
  en System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)
  en System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
  en ValidKeyDll.ValidKey.getLlaveDeAlmacen(String almacen, Boolean esLlavePrivada) en C:\Users\desarrollo\Documents\ValidKeyDll\ValidKeyDll\ValidKey.cs:línea 58
  en ValidKeyDll.ValidKey.firmaCadena(String almacen, String cadenaFirmar) en C:\Users\desarrollo\Documents\ValidKeyDll\ValidKeyDll\ValidKey.cs:línea 117
  </code></pre>
  
  <p>And this is my part of the code that reads the key:</p>
  
  <pre><code>X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
  store.Open(OpenFlags.ReadOnly);
  RSACryptoServiceProvider csp = null;
  foreach (X509Certificate2 cert in store.Certificates)
  {
     if (cert.Subject.Contains(almacen))
     {
        if (cert.NotAfter.CompareTo(System.DateTime.Now) &lt;= 0)
           throw new CertificadoVencidoException();
  
        if (isPrivateKey)
           csp = (RSACryptoServiceProvider)cert.PrivateKey;
        else
           csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
  
        break;
     }
  }
  </code></pre>
  
  <p>I suppose it has to do with some kind of permission issue, but I caanot find out what it is... Please if anyone has any suggestions it will be greatly appreciated.</p>
  
  <p>THINGS TO CONSIDER:</p>
  
  <ul>
  <li>The private key IS exportable.</li>
  <li>The user IIS_IUSRS has permissions on the certificate.</li>
  </ul>