private static string GetThumbprint(IntPtr pCertContext)
{
IntPtr pData = IntPtr.Zero;
int dwDataSize = 0;
try
{
if (pCertContext == IntPtr.Zero)
{
return String.Empty;
}
int bResult = NativeMethods.CertGetCertificateContextProperty(
pCertContext,
CERT_SHA1_HASH_PROP_ID,
IntPtr.Zero,
ref dwDataSize);
if (bResult == 0)
{
int dwError = Marshal.GetLastWin32Error();
if (dwError != ERROR_MORE_DATA)
{
throw ServiceResultException.Create(
StatusCodes.BadUnexpectedError,
"Could not get the size of the thumbprint from the certificate context. Error={0:X8}",
dwError);
}
}
pData = Marshal.AllocHGlobal(dwDataSize);
bResult = NativeMethods.CertGetCertificateContextProperty(
pCertContext,
CERT_SHA1_HASH_PROP_ID,
pData,
ref dwDataSize);
if (bResult == 0)
{
int dwError = Marshal.GetLastWin32Error();
throw ServiceResultException.Create(
StatusCodes.BadUnexpectedError,
"Could not get the thumbprint from the certificate context. Error={0:X8}",
dwError);
}
byte[] thumprint = new byte[dwDataSize];
Marshal.Copy(pData, thumprint, 0, thumprint.Length);
return Utils.ToHexString(thumprint).ToUpperInvariant();
}
finally
{
if (pData != IntPtr.Zero)
{
Marshal.FreeHGlobal(pData);
}
}
}