1 #include <windows.h> 2 #include <wincrypt.h> 3 #include <stdio.h> 4 5 BOOL GetFileHash(LPCSTR lpFileName, LPSTR lpHash) 6 { 7 BOOL bResult = FALSE; 8 9 HANDLE hFile = CreateFile(lpFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); 10 11 if (hFile != INVALID_HANDLE_VALUE) 12 { 13 DWORD dwFileSize = GetFileSize(hFile, NULL); 14 15 if (dwFileSize > 0) 16 { 17 PBYTE lpBuffer = (PBYTE)VirtualAlloc(NULL, dwFileSize, MEM_COMMIT, PAGE_READWRITE); 18 19 if (lpBuffer != NULL) 20 { 21 DWORD dwNumOfRead; 22 23 if (ReadFile(hFile, lpBuffer, dwFileSize, &dwNumOfRead, NULL) != FALSE) 24 { 25 HCRYPTPROV hProv; 26 27 if (CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) != FALSE) 28 { 29 HCRYPTHASH hHash; 30 31 if (CryptCreateHash(hProv, CALG_MD5, NULL, NULL, &hHash) != FALSE) 32 { 33 if (CryptHashData(hHash, lpBuffer, dwFileSize, NULL) != FALSE) 34 { 35 BYTE bData[16]; DWORD dwDataLen; 36 37 if (CryptGetHashParam(hHash, HP_HASHVAL, bData, &dwDataLen, NULL) != FALSE) 38 { 39 if (dwDataLen == 16) 40 { 41 LPSTR lpStr = lpHash; 42 43 for (DWORD i = 0; i < dwDataLen; i++, lpStr += 2) 44 { 45 sprintf(lpStr, "%02X", bData[i]); 46 } 47 48 bResult = TRUE; 49 } 50 } 51 } 52 53 CryptDestroyHash(hHash); 54 } 55 56 CryptReleaseContext(hProv, NULL); 57 } 58 } 59 60 VirtualFree(lpBuffer, 0, MEM_RELEASE); 61 } 62 } 63 64 CloseHandle(hFile); 65 } 66 67 return bResult; 68 }