Created
November 2, 2018 12:50
-
-
Save maldevel/ea73fb0d960a93ed0dcd0e65bf1222b7 to your computer and use it in GitHub Desktop.
Dexter SHA 256 Hash snippet
This file contains 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
//https://github.com/twelvesec/dexter | |
//GNU General Public License v3.0 | |
//@maldevel | |
//... | |
std::string libHash::sha256(std::string input) { | |
std::string hash; | |
sha256_context ctx; | |
BYTE tmp[SHA256_HASH_SIZE]; | |
DWORD size = SHA256_HASH_SIZE; | |
char part[10] = { 0 }; | |
int outputSize = (SHA256_HASH_SIZE * 2) + 1; | |
char *str; | |
if (CryptAcquireContext(&ctx.hCryptProv, NULL, NULL, PROV_RSA_AES, CRYPT_VERIFYCONTEXT) == FALSE) {//CRYPT_VERIFYCONTEXT | |
return ""; | |
} | |
if (CryptCreateHash(ctx.hCryptProv, CALG_SHA_256, 0, 0, &ctx.hHash) == FALSE) | |
{ | |
CryptReleaseContext(ctx.hCryptProv, 0); | |
ctx.hCryptProv = 0; | |
return ""; | |
} | |
if (CryptHashData(ctx.hHash, (BYTE*)input.c_str(), (DWORD)input.length(), 0) == FALSE) | |
{ | |
CryptReleaseContext(ctx.hCryptProv, 0); | |
ctx.hCryptProv = 0; | |
CryptDestroyHash(ctx.hHash); | |
ctx.hHash = 0; | |
return ""; | |
} | |
if (CryptGetHashParam(ctx.hHash, HP_HASHVAL, tmp, &size, 0) == FALSE) | |
{ | |
CryptReleaseContext(ctx.hCryptProv, 0); | |
ctx.hCryptProv = 0; | |
CryptDestroyHash(ctx.hHash); | |
ctx.hHash = 0; | |
return ""; | |
} | |
CryptReleaseContext(ctx.hCryptProv, 0); | |
ctx.hCryptProv = 0; | |
CryptDestroyHash(ctx.hHash); | |
ctx.hHash = 0; | |
if ((str = (char*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, outputSize)) == NULL) { | |
return ""; | |
} | |
for (int i = 0; i < SHA256_HASH_SIZE; i++) | |
{ | |
if (_snprintf_s(part, 10, _TRUNCATE, "%.2x", tmp[i]) == -1) {//%02x | |
HeapFree(GetProcessHeap(), 0, str); | |
str = NULL; | |
return ""; | |
} | |
if (strncat_s(str, outputSize, part, _TRUNCATE) != 0) { | |
HeapFree(GetProcessHeap(), 0, str); | |
str = NULL; | |
return ""; | |
} | |
} | |
hash = std::string(str); | |
HeapFree(GetProcessHeap(), 0, str); | |
str = NULL; | |
return hash; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment