public bool Delete(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(false, false, false);
if (hStore == IntPtr.Zero)
{
return false;
}
// find certificate in the store.
pCertContext = FindCertificate(hStore, thumbprint);
if (pCertContext == IntPtr.Zero)
{
return false;
}
// 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);
}
// verify that everything is ok.
CERT_CONTEXT certificate1 = (CERT_CONTEXT)Marshal.PtrToStructure(pCertContext, typeof(CERT_CONTEXT));
CERT_CONTEXT certificate2 = (CERT_CONTEXT)Marshal.PtrToStructure(pDupCertContext, typeof(CERT_CONTEXT));
int bResult = NativeMethods.CertCompareCertificate(
X509_ASN_ENCODING,
certificate1.pCertInfo,
certificate2.pCertInfo);
if (bResult == 0)
{
throw ServiceResultException.Create(
StatusCodes.BadUnexpectedError,
"Duplicated certificate does not match original. Thumbprint={0}",
thumbprint);
}
// delete certificate.
bResult = NativeMethods.CertDeleteCertificateFromStore(pDupCertContext);
if (bResult == 0)
{
int dwError = Marshal.GetLastWin32Error();
throw ServiceResultException.Create(
StatusCodes.BadUnexpectedError,
"Could not delete the certificate from the store.\r\nType={0}, Name={1}, Error={2:X8}",
m_storeType,
m_symbolicName,
dwError);
}
pDupCertContext = IntPtr.Zero;
return true;
}
finally
{
if (pCertContext != IntPtr.Zero)
{
NativeMethods.CertFreeCertificateContext(pCertContext);
}
if (pDupCertContext != IntPtr.Zero)
{
NativeMethods.CertFreeCertificateContext(pDupCertContext);
}
if (hStore != IntPtr.Zero)
{
NativeMethods.CertCloseStore(hStore, 0);
}
}
}
}