获取字符串的MD5值

 1 bool GetMD5(LPCTSTR lpsz,const int strLen,LPTSTR lpMD5,const int bufLen)
 2 {
 3     memset(lpMD5,0,bufLen);
 4 
 5     int mbStrLen = WideCharToMultiByte(CP_UTF8,0,lpsz,strLen,NULL,0,NULL,NULL);
 6     CHAR* mbStr = new CHAR[mbStrLen+1];
 7     memset(mbStr,0,mbStrLen+1);
 8     WideCharToMultiByte(CP_UTF8,0,lpsz,strLen,mbStr,mbStrLen,NULL,NULL);
 9 
10     bool bSucc = false;
11     HCRYPTPROV hProv = 0;
12     HCRYPTHASH hHash = 0;    
13     do{
14         if (!CryptAcquireContext(&hProv,
15             NULL,
16             NULL,
17             PROV_RSA_FULL,
18             CRYPT_VERIFYCONTEXT)){
19                 break;
20         }
21 
22         if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash)){
23             break;
24         }
25 
26         if (!CryptHashData(hHash, (BYTE*)mbStr, mbStrLen, 0)){
27             break;
28         }
29 
30         BYTE rgbHash[16];
31         DWORD cbHash = 16;
32         const CHAR rgbDigits[] = "0123456789abcdef";
33         if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0)){
34             if(cbHash>bufLen){
35                 break;
36             }
37             for (DWORD i = 0,index = 0; i < cbHash; i++){
38                 lpMD5[index++]=rgbDigits[rgbHash[i] >> 4];
39                 lpMD5[index++]=rgbDigits[rgbHash[i] & 0xf];
40             }
41         }
42         bSucc = true;
43     }while(0);
44 
45     CryptDestroyHash(hHash);
46     CryptReleaseContext(hProv, 0);
47 
48     return bSucc;    
49 }

 

注意这个是在Unicode环境下的代码,需要进行宽窄字符转换,如果是多字节字符环境则不需要字符装换。

posted @ 2013-10-23 20:37  ssp1024  阅读(1091)  评论(0编辑  收藏  举报