title: Private key is null when accessing via code, why?
body: <p>I have a certificate installed on my machine and when I go to view it, I see the message "You have a private key that corresponds to this certificate" however, when I try to access that private key in code, it is null.  I use the following code to get my certificate:</p>
  
  <pre><code>var x509Certificate = GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=SomeCert");
  </code></pre>
  
  <p>Where:</p>
  
  <pre><code>public X509Certificate2 GetCertificate(string storeName, string storeLocation, string subjectName)
  {
       var store = new X509Store(getStoreName(storeName), getStoreLocation(storeLocation));
       X509Certificate2Collection certificates = null;
       store.Open(OpenFlags.ReadOnly);
  
       try
       {
            X509Certificate2 result = null;
            certificates = store.Certificates;
            return getCertificateResult(certificates, subjectName, result);
       }
       finally
       {
            if (certificates != null)
            {
                 foreach (var cert in certificates)
                 {
                      cert.Reset();
                 }
            }
            store.Close();
       }
  }
  </code></pre>
  
  <p>And:</p>
  
  <pre><code>private static X509Certificate2 getCertificateResult(IEnumerable certificates, string subjectName, X509Certificate2 result)
  {
       foreach (var cert in certificates.Cast&lt;X509Certificate2&gt;().Where(cert =&gt; cert.SubjectName.Name != null &amp;&amp; cert.SubjectName.Name.ToLower() == subjectName.ToLower()))
       {
            if (result != null)
            {
               throw new ApplicationException(string.Format("There is more than one certificate found for subject Name {0}", subjectName));
            }
            result = new X509Certificate2(cert);
       }
  
       if (result == null)
       {
            throw new ApplicationException(string.Format("No certificate was found for subject Name {0}", subjectName));
       }
       return result;
  }
  </code></pre>
  
  <p>I get my certificate back fine, however when I try to access the private key, doing the following:</p>
  
  <pre><code>x509Certificate.PrivateKey
  </code></pre>
  
  <p>The value for PrivateKey is null.  What am I doing wrong?  I need this value to sign a SAML2 request.</p>
  
  <p><em>Note:  I understand that I have some abstractions in there but the point is that I get the certificate back (it's found) but the private key is null.  If there is any more information about my abstraction that is preventing the question from being answered, I can provide more detail.</em></p>