title: PrivateKey threw an exception of type System.Security.Cryptography.CryptographicException
body: <p>I'm trying to use self-signed certificate using the following code:</p>
  
  <pre><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&lt;X509Certificate2&gt;().FirstOrDefault(c =&gt; c.Subject.Equals(subjectName, StringComparison.OrdinalIgnoreCase));
  
              return cert != null ? new X509Certificate2(cert) : null;
          }
          catch (Exception)
          {
  
              throw;
          }
          finally
          {
              store.Certificates.OfType&lt;X509Certificate2&gt;().ToList().ForEach(c =&gt; c.Reset());
              store.Close();
          }
      }
  </code></pre>
  
  <p>I am getting the following exception: </p>
  
  <pre><code>PrivateKey = 'cert.PrivateKey' threw an exception of type 'System.Security.Cryptography.CryptographicException'
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/lYAG6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lYAG6.png" alt="enter image description here"></a></p>
  
  <p>I Tried <a href="http://www.wrapcode.com/keyset-doesnt-exist-fix/" rel="noreferrer">this fix</a>, and <a href="https://stackoverflow.com/questions/12106011/system-security-cryptography-cryptographicexception-keyset-does-not-exist">this fix</a></p>
  
  <p>But still having the problem!</p>