m_safeCertContext is an invalid handle

Sergio picture Sergio · Jan 14, 2009 · Viewed 20.1k times · Source

I've been wrestling with a problem, maybe you guys can point me in the right direction.

I'm trying to digitally sign a pdf, on the webserver, over an https connection.

At page load i'm doing as so:

HttpClientCertificate cs = Request.ClientCertificate;
X509Certificate card = new X509Certificate(cs.Certificate);
Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
 Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.GetRawCertData())};

I'm getting the error "m_safeCertContext is an invalid handle" at that last line of code.

Please note that:

  • I am getting the same error using 2 completely different certificates.
  • The certificate is being retrieved to the "card" variable ok.
  • I used to get the card to X509Certificate2 but i read yesterday somewhere I'm not being able to find that the error could be solved by casting as a X509Certificate and then downcasting to X509Certificate2. It was one of those "well... this does not makes any sense but i havent tried it yet" moments.
  • I have tried to add [System.Security.SecurityCritical, System.Security.SecurityTreatAsSafe] property to all methods and even the class to see if it would work... no such luck.

Can anyone one give me a hint?

Answer

DanM7 picture DanM7 · Nov 21, 2013

This can happen any time you access uninitialized fields in cryptography.

In your code, if Request.ClientCertificate returns an object with no raw certificate data then you will see the error when you call card.GetRawCertData() on your fourth line.

As a simple test, try the following:

var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2();
Console.WriteLine(cert.Thumbprint);

This will throw the following exception because there is no thumbprint available:

m_safeCertContext is an invalid handle.

with the given stack trace:

at System.Security.Cryptography.X509Certificates.X509Certificate.ThrowIfContextInvalid()
at System.Security.Cryptography.X509Certificates.X509Certificate.SetThumbprint()
at System.Security.Cryptography.X509Certificates.X509Certificate.GetCertHashString()
at System.Security.Cryptography.X509Certificates.X509Certificate2.get_Thumbprint()
at MyEncryptionUtility.EncryptionUtilityForm.button1_Click(Object sender, EventArgs e) in C:\MyEncryptionUtility\EncryptionUtilityForm.cs:line 2864