public X509Certificate2 FindByThumbprint(string thumbprint)
{
lock (m_lock)
{
IntPtr hStore = IntPtr.Zero;
IntPtr pCertContext = IntPtr.Zero;
IntPtr pDupCertContext = IntPtr.Zero;
// find the certificate.
try
{
// open store.
hStore = OpenStore(true, false, false);
if (hStore == IntPtr.Zero)
{
return null;
}
// find existing certificate.
pCertContext = FindCertificate(hStore, thumbprint);
if (pCertContext == IntPtr.Zero)
{
return null;
}
// duplicate the certificate context.
pDupCertContext = NativeMethods.CertDuplicateCertificateContext(pCertContext);
if (pDupCertContext == IntPtr.Zero)
{
int dwError = Marshal.GetLastWin32Error();
throw ServiceResultException.Create(
StatusCodes.BadUnexpectedError,
"Could not duplicate the certificate context. Error={0:X8}",
dwError);
}
// create the certificate.
X509Certificate2 certificate = new X509Certificate2(pDupCertContext);
return certificate;
}
finally
{
if (pCertContext != IntPtr.Zero)
{
NativeMethods.CertFreeCertificateContext(pCertContext);
}
if (pDupCertContext != IntPtr.Zero)
{
NativeMethods.CertFreeCertificateContext(pDupCertContext);
}
if (hStore != IntPtr.Zero)
{
NativeMethods.CertCloseStore(hStore, 0);
}
}
}
}