title: Slow performance of X509Certificate2.PrivateKey
body: <p>I'm loading a certificate from the certificate store. So I have a X509Certificate2 object.
  Next I load the private key which I use for signing a message. The code I'm using is:</p>
  
  <pre><code>public static RSACryptoServiceProvider GetPrivateKey(X509Certificate2 cert)
  {
      var enhCsp = new RSACryptoServiceProvider().CspKeyContainerInfo;
      var privateKey = (RSACryptoServiceProvider)cert.PrivateKey; //very slow
      var cspparams = new CspParameters(enhCsp.ProviderType, enhCsp.ProviderName, privateKey.CspKeyContainerInfo.KeyContainerName);
      return new RSACryptoServiceProvider(cspparams);
  }
  </code></pre>
  
  <p>The issue I'm having is that the line:
  <code>var privateKey = (RSACryptoServiceProvider)cert.PrivateKey;</code>
  takes very very long. Around 9 seconds on my laptop. It would seem that this does not happen every time I try to access the private key. Sometimes it's in the order of milliseconds and other times it takes as long as described.</p>
  
  <p>Any insight into why? Is there a way to avoid that?</p>
  
  <p><strong>UPDATE:</strong>
  I've been experimenting a bit after noticing this <a href="https://support.microsoft.com/en-us/kb/948080" rel="nofollow noreferrer" title="issue">KB article</a> and some other SO <a href="https://stackoverflow.com/questions/5303874/rotten-performance-of-rsacryptoserviceprovider-verifydata" title="issues">issues</a>.
  It really seems like that delay is never there when there is no network connectivity.
  I wonder if I really have to go decompiling .NET assemblies to sort this out...</p>
  
  <p><strong>UPDATE 1:</strong>
  It appears as though certificates/key pairs that are issued by a real authority are not affected. I'm seeing this issue when trying to load private key for issuers which I've manually added to the trusted root certification authorities</p>