Skip to content

Instantly share code, notes, and snippets.

@BloodhoundAllfather
Last active January 15, 2023 00:28
Show Gist options
  • Save BloodhoundAllfather/45ce4cdc39b47aa457783df462a8d0a6 to your computer and use it in GitHub Desktop.
Save BloodhoundAllfather/45ce4cdc39b47aa457783df462a8d0a6 to your computer and use it in GitHub Desktop.
SHA1 hash using Windows APIs
#include <Windows.h>
#include <Wincrypt.h>
#pragma comment(lib, "advapi32.lib")
#define SHA1LEN 20
// generates SHA1 hash and returns 20-byte heap-memory if successful, otherwise NULL
unsigned char* sha1(unsigned char* data, int len)
{
HCRYPTPROV hProv = 0;
HCRYPTHASH hHash = 0;
BYTE* sha1sum;
DWORD sha1len = SHA1LEN;
BOOL hashCalculated;
if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
return NULL;
if (!CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash))
{
CryptReleaseContext(hProv, 0);
return NULL;
}
if (!CryptHashData(hHash, data, len, 0))
{
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
return NULL;
}
sha1sum = (BYTE*)malloc(SHA1LEN);
hashCalculated = CryptGetHashParam(hHash, HP_HASHVAL, sha1sum, &sha1len, 0);
CryptDestroyHash(hHash);
CryptReleaseContext(hProv, 0);
if (hashCalculated)
return sha1sum;
else
{
free(sha1sum);
return NULL;
}
}
int main()
{
char text[] = "abcd";
unsigned char* sha1sum = sha1((BYTE*)text, strlen(text));
// use the hash here
// when you're done with the hash, free the memory
free(sha1sum);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment