Thursday, February 24, 2011

MD5 Hash -- using the Windows API

(1)
if <windows.h> fails, download and extract the header files from this 1.4MB self-extracting zip file, Microsoft Download Center, CSPDK

(2) use the sample below;

[...]
#include <windows.h>
#include <wincrypt.h>
[...]

#define MD5LEN 16

MD5(BYTE* data, ULONG len)
{
HCRYPTPROV hProv = 0;
HCRYPTPROV hHash = 0;

CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash);

CryptHashData(hHash, data, len, 0);

BYTE rgbHash[MD5LEN]= {0};
DWORD cbHash = MD5LEN;
CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0);

CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);

// rgbHash is now a 128 bits of MD5 hash
// use some hex -> string methods if desired

}


(3) for large files do;

(step 1) CryptCreateHash
(step 2) while (!EOF) { CryptHashData(...data...) }
(step 3) CryptGetHashParam(HP_HASHVAL);
(step 4) CryptDestryHash