360 这类软件,能实现验证已下载的可执行文件中数字签名的功能。如果数字签名正常,则提示安全,如果没有数字签名,或根证书不可信等,都会提示文件未知。
那么在程序里面怎么实现呢?
// 代码共享如下,在Win2K sp4/WinXP sp2上调试通过。 BOOL CheckFileTrust( LPCWSTR lpFileName ) { BOOL bRet = FALSE; WINTRUST_DATA wd = { 0 }; WINTRUST_FILE_INFO wfi = { 0 }; WINTRUST_CATALOG_INFO wci = { 0 }; CATALOG_INFO ci = { 0 }; HCATADMIN hCatAdmin = NULL; if ( !CryptCATAdminAcquireContext( &hCatAdmin, NULL, 0 ) ) { return FALSE; } HANDLE hFile = CreateFileW( lpFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL ); if ( INVALID_HANDLE_VALUE == hFile ) { CryptCATAdminReleaseContext( hCatAdmin, 0 ); return FALSE; } DWORD dwCnt = 100; BYTE byHash[100]; CryptCATAdminCalcHashFromFileHandle( hFile, &dwCnt, byHash, 0 ); CloseHandle( hFile ); LPWSTR pszMemberTag = new WCHAR[dwCnt * 2 + 1]; for ( DWORD dw = 0; dw < dwCnt; ++dw ) { wsprintfW( &pszMemberTag[dw * 2], L"%02X", byHash[dw] ); } HCATINFO hCatInfo = CryptCATAdminEnumCatalogFromHash( hCatAdmin, byHash, dwCnt, 0, NULL ); if ( NULL == hCatInfo ) { wfi.cbStruct = sizeof( WINTRUST_FILE_INFO ); wfi.pcwszFilePath = lpFileName; wfi.hFile = NULL; wfi.pgKnownSubject = NULL; wd.cbStruct = sizeof( WINTRUST_DATA ); wd.dwUnionChoice = WTD_CHOICE_FILE; wd.pFile = &wfi; wd.dwUIChoice = WTD_UI_NONE; wd.fdwRevocationChecks = WTD_REVOKE_NONE; wd.dwStateAction = WTD_STATEACTION_IGNORE; wd.dwProvFlags = WTD_SAFER_FLAG; wd.hWVTStateData = NULL; wd.pwszURLReference = NULL; } else { CryptCATCatalogInfoFromContext( hCatInfo, &ci, 0 ); wci.cbStruct = sizeof( WINTRUST_CATALOG_INFO ); wci.pcwszCatalogFilePath = ci.wszCatalogFile; wci.pcwszMemberFilePath = lpFileName; wci.pcwszMemberTag = pszMemberTag; wd.cbStruct = sizeof( WINTRUST_DATA ); wd.dwUnionChoice = WTD_CHOICE_CATALOG; wd.pCatalog = &wci; wd.dwUIChoice = WTD_UI_NONE; wd.fdwRevocationChecks = WTD_STATEACTION_VERIFY; wd.dwProvFlags = 0; wd.hWVTStateData = NULL; wd.pwszURLReference = NULL; } GUID action = WINTRUST_ACTION_GENERIC_VERIFY_V2; HRESULT hr = WinVerifyTrust( NULL, &action, &wd ); bRet = SUCCEEDED( hr ); if ( NULL != hCatInfo ) { CryptCATAdminReleaseCatalogContext( hCatAdmin, hCatInfo, 0 ); } CryptCATAdminReleaseContext( hCatAdmin, 0 ); // 2007.4.10感谢童志明君指出一处内存泄漏 delete[] pszMemberTag; return bRet; }
这段代码是在一个老外的论坛上不经意搜索到的,一个貌似德国人(因为他的注释不是英文写的,德国亦仅猜测尔,西班牙、葡萄牙、法兰西、俄罗斯亦都有可能)写的Delphi代码,其中使用了WinTrust.dll中的导出函数。使用VS2005的朋友们可以包含WinTrust.h、SoftPub.h和Mscat.h,并添加导入库WinTrust.lib;使用VC6的朋友们可以参考MSDN上的函数及结构体声明,并用函数指针进行调用。
使用windows api来校验数字签名,可以判断文件是否有数字签名,是否通过验证,好像无法读取签名人信息:
Example C Program: Verifying the Signature of a PE File
http://msdn.microsoft.com/en-us/library/aa382384.aspx
C#: Determining if a file has a valid digital signature
http://geekswithblogs.net/robp/archive/2007/05/04/112250.aspx
备注:
本文转载自:http://topic.csdn.net/u/20110303/22/0400553c-c025-489e-a4d4-564b8b5f052c.html
http://www.cnblogs.com/flying_bat/archive/2007/09/20/900008.html