Created
January 31, 2020 09:36
-
-
Save hash3liZer/9cf9a9568717a94ae6b030ee65b99134 to your computer and use it in GitHub Desktop.
Implementation of MD5 Hash Function in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Windows.h> | |
#include <Wincrypt.h> | |
#include <stdio.h> | |
using namespace std; | |
char* HashMD5(char* data, DWORD *result) | |
{ | |
DWORD dwStatus = 0; | |
DWORD cbHash = 16; | |
int i = 0; | |
HCRYPTPROV cryptProv; | |
HCRYPTHASH cryptHash; | |
BYTE hash[16]; | |
char *hex = "0123456789abcdef"; | |
char *strHash; | |
strHash = (char*)malloc(500); | |
memset(strHash, '\0', 500); | |
if (!CryptAcquireContext(&cryptProv, NULL, MS_DEF_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) | |
{ | |
dwStatus = GetLastError(); | |
printf("CryptAcquireContext failed: %d\n", dwStatus); | |
*result = dwStatus; | |
return NULL; | |
} | |
if (!CryptCreateHash(cryptProv, CALG_MD5, 0, 0, &cryptHash)) | |
{ | |
dwStatus = GetLastError(); | |
printf("CryptCreateHash failed: %d\n", dwStatus); | |
CryptReleaseContext(cryptProv, 0); | |
*result = dwStatus; | |
return NULL; | |
} | |
if (!CryptHashData(cryptHash, (BYTE*)data, strlen(data), 0)) | |
{ | |
dwStatus = GetLastError(); | |
printf("CryptHashData failed: %d\n", dwStatus); | |
CryptReleaseContext(cryptProv, 0); | |
CryptDestroyHash(cryptHash); | |
*result = dwStatus; | |
return NULL; | |
} | |
if (!CryptGetHashParam(cryptHash, HP_HASHVAL, hash, &cbHash, 0)) | |
{ | |
dwStatus = GetLastError(); | |
printf("CryptGetHashParam failed: %d\n", dwStatus); | |
CryptReleaseContext(cryptProv, 0); | |
CryptDestroyHash(cryptHash); | |
*result = dwStatus; | |
return NULL; | |
} | |
for (i = 0; i < cbHash; i++) | |
{ | |
strHash[i * 2] = hex[hash[i] >> 4]; | |
strHash[(i * 2) + 1] = hex[hash[i] & 0xF]; | |
} | |
CryptReleaseContext(cryptProv, 0); | |
CryptDestroyHash(cryptHash); | |
return strHash; | |
} | |
int main(){ | |
DWORD res; | |
char* hash; | |
hash = HashMD5("Value Here", &res); | |
cout << hash << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment