取文件MD5 WINAPI

 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 }

 

转载于:https://www.cnblogs.com/crsky/p/6118510.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值