//md5.h#include <tchar.h>#include<wincrypt.h>//calculated hash, successfully returned 0, failed to return GetLastError ()//CONST BYTE *pbdata,//input Data//DWORD Dwdatalen,//input data byte length//alg_id Algid//Hash algorithm: Calg_md5,calg_sha//LPTSTR Pszhash,//output 16 binary hash string, MD5 length is 32+1, sha length is 40+1// DWORD Gethash (CONST BYTE*pbdata, DWORD Dwdatalen, alg_id algid, LPTSTR Pszhash) {DWORD Dwreturn=0; Hcryptprov Hprov; if(! CryptAcquireContext (&Hprov, NULL, NULL, Prov_rsa_full, Crypt_verifycontext)) return(Dwreturn =GetLastError ()); Hcrypthash Hhash; //ALG Id:calg_md5,calg_sha if(! Cryptcreatehash (Hprov, Algid,0,0, &Hhash)) {Dwreturn=GetLastError (); CryptReleaseContext (Hprov,0); returnDwreturn; } if(! Crypthashdata (Hhash, pbdata, Dwdatalen,0) ) {Dwreturn=GetLastError (); Cryptdestroyhash (Hhash); CryptReleaseContext (Hprov,0); returnDwreturn; } DWORD dwsize; DWORD Dwlen=sizeof(dwsize); Cryptgethashparam (Hhash, Hp_hashsize, (BYTE*) (&dwsize), &dwlen,0); BYTE* Phash =NewByte[dwsize]; Dwlen=dwsize; Cryptgethashparam (Hhash, Hp_hashval, Phash,&dwlen,0); lstrcpy (Pszhash, _t ("")); TCHAR sztemp[3]; for(DWORD i =0; i < Dwlen; ++i) {//wsprintf (sztemp, _t ("%x%x"), Phash[i] >> 4, Phash[i] & 0xf);wsprintf (Sztemp, _t ("%02x"), Phash[i]); Lstrcat (Pszhash, sztemp); } Delete[]phash; Cryptdestroyhash (Hhash); CryptReleaseContext (Hprov,0); returnDwreturn;} BOOL GetFileMd5 (LPCTSTR lpfilename, LPTSTR pszhash) {HANDLE hfile=CreateFile (lpfilename,generic_read,file_share_read,null,open_existing,null,null); if(hfile = = INVALID_HANDLE_VALUE)//if the CreateFile call fails { //prompts the CreateFile call to fail and outputs the error number. In Visual Studio, you can use the error number to get an error message in Tools > Error lookup. CloseHandle (hfile); returnFALSE; } DWORD dwfilesize= GetFileSize (hfile,0);//get the size of a file if(dwFileSize = =0xFFFFFFFF)//if getting file size fails { returnFALSE; } BYTE* Lpreadfilebuffer =NewByte[dwfilesize]; DWORD lpreadnumberofbytes; if(ReadFile (hfile,lpreadfilebuffer,dwfilesize,&lpreadnumberofbytes,null) = =0)//Read File { returnFALSE; } if(Gethash (Lpreadfilebuffer, dwFileSize, CALG_MD5, Pszhash)) {returnFALSE; } Delete[]lpreadfilebuffer; CloseHandle (hfile); //Close file handle returnTRUE;} BOOL GetStringMd5 (TCHAR*pszstr, LPTSTR Pszhash) { if(Gethash (byte*) Pszstr, _tcslen (PSZSTR), CALG_MD5, Pszhash)) {returnFALSE; } returnTRUE;}
#include <windows.h>#include"stdio.h"#include"md5.h"#include<locale.h>intMain () {//Test MD5TCHAR szmd5[ A] = {0}; SetLocale (Lc_all,"CHS"); //Test String MD5TCHAR Szstr[_max_fname] = _t ("This is a string"); GetStringMd5 (Szstr, szMD5); wprintf (L"string: The MD5 value for%s is:%s\n", Szstr, szMD5); //test File MD5TCHAR Szfile[max_path] = _t ("d:\\temp\\settings.db"); GetFileMd5 (Szfile, szMD5); wprintf (L"file: The MD5 value for%s is:%s\n", Szfile, szMD5);}
VC uses CryptoAPI to calculate MD5