Skip to content

Instantly share code, notes, and snippets.

@Sukelluskello
Forked from maldevel/libHash.cpp
Created November 4, 2018 07:48
Show Gist options
  • Save Sukelluskello/25e8e77f4a24dd8fa194a6f2e2173c0f to your computer and use it in GitHub Desktop.
Save Sukelluskello/25e8e77f4a24dd8fa194a6f2e2173c0f to your computer and use it in GitHub Desktop.
Dexter SHA 256 Hash snippet
//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