PE数字证书验证
1 #include "stdafx.h" 2 #include <windows.h> 3 #include <Wintrust.h> 4 #include <SoftPub.h> 5 #include <Mscat.h> 6 7 #pragma comment(lib,"WinTrust.lib") 8 9 BOOL CheckFileTrust( LPCWSTR lpFileName ) 10 { 11 BOOL bRet = FALSE; 12 WINTRUST_DATA wd = { 0 }; 13 WINTRUST_FILE_INFO wfi = { 0 }; 14 WINTRUST_CATALOG_INFO wci = { 0 }; 15 CATALOG_INFO ci = { 0 }; 16 17 HCATADMIN hCatAdmin = NULL; 18 if ( !CryptCATAdminAcquireContext( &hCatAdmin, NULL, 0 ) ) 19 { 20 return FALSE; 21 } 22 23 HANDLE hFile = CreateFileW( lpFileName, GENERIC_READ, FILE_SHARE_READ, 24 NULL, OPEN_EXISTING, 0, NULL ); 25 if ( INVALID_HANDLE_VALUE == hFile ) 26 { 27 CryptCATAdminReleaseContext( hCatAdmin, 0 ); 28 return FALSE; 29 } 30 31 DWORD dwCnt = 100; 32 BYTE byHash[100]; 33 CryptCATAdminCalcHashFromFileHandle( hFile, &dwCnt, byHash, 0 ); 34 CloseHandle( hFile ); 35 36 LPWSTR pszMemberTag = new WCHAR[dwCnt * 2 + 1]; 37 for ( DWORD dw = 0; dw < dwCnt; ++dw ) 38 { 39 wsprintfW( &pszMemberTag[dw * 2], L"%02X", byHash[dw] ); 40 } 41 42 HCATINFO hCatInfo = CryptCATAdminEnumCatalogFromHash( hCatAdmin, 43 byHash, dwCnt, 0, NULL ); 44 if ( NULL == hCatInfo ) 45 { 46 wfi.cbStruct = sizeof( WINTRUST_FILE_INFO ); 47 wfi.pcwszFilePath = lpFileName; 48 wfi.hFile = NULL; 49 wfi.pgKnownSubject = NULL; 50 51 wd.cbStruct = sizeof( WINTRUST_DATA ); 52 wd.dwUnionChoice = WTD_CHOICE_FILE; 53 wd.pFile = &wfi; 54 wd.dwUIChoice = WTD_UI_NONE; 55 wd.fdwRevocationChecks = WTD_REVOKE_NONE; 56 wd.dwStateAction = WTD_STATEACTION_IGNORE; 57 wd.dwProvFlags = WTD_SAFER_FLAG; 58 wd.hWVTStateData = NULL; 59 wd.pwszURLReference = NULL; 60 } 61 else 62 { 63 CryptCATCatalogInfoFromContext( hCatInfo, &ci, 0 ); 64 wci.cbStruct = sizeof( WINTRUST_CATALOG_INFO ); 65 wci.pcwszCatalogFilePath = ci.wszCatalogFile; 66 wci.pcwszMemberFilePath = lpFileName; 67 wci.pcwszMemberTag = pszMemberTag; 68 69 wd.cbStruct = sizeof( WINTRUST_DATA ); 70 wd.dwUnionChoice = WTD_CHOICE_CATALOG; 71 wd.pCatalog = &wci; 72 wd.dwUIChoice = WTD_UI_NONE; 73 wd.fdwRevocationChecks = WTD_STATEACTION_VERIFY; 74 wd.dwProvFlags = 0; 75 wd.hWVTStateData = NULL; 76 wd.pwszURLReference = NULL; 77 } 78 GUID action = WINTRUST_ACTION_GENERIC_VERIFY_V2; 79 HRESULT hr = WinVerifyTrust( NULL, &action, &wd ); 80 bRet = SUCCEEDED( hr ); 81 82 if ( NULL != hCatInfo ) 83 { 84 CryptCATAdminReleaseContext( hCatInfo, 0 ); 85 } 86 CryptCATAdminReleaseCatalogContext( hCatAdmin, hCatInfo, 0 ); 87 delete[] pszMemberTag; 88 return bRet; 89 }