Skip to content

Instantly share code, notes, and snippets.

@ppsdatta
Last active June 18, 2021 13:48
Show Gist options
  • Save ppsdatta/5029366e3c8fba3e4aa20409feea92ac to your computer and use it in GitHub Desktop.
Save ppsdatta/5029366e3c8fba3e4aa20409feea92ac to your computer and use it in GitHub Desktop.
A SHA256 hash generator in C using openssl
#include <openssl/hmac.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <string.h>
#define EXPECTED "0d696548764b6f910bdd3c07d8e465112c0783a03f2c1cf5ef893b8aa27f3290"
int main()
{
unsigned char *message = (unsigned char *)"this is highly sensitive user data";
unsigned char *key = (unsigned char *)"security is awesome but difficult";
int len;
int i;
char *digest;
unsigned char *result = HMAC(
EVP_sha256(),
(const void *)key,
strlen(key),
message,
strlen(message),
NULL,
&len);
if (len <= 0)
return 1;
digest = malloc(len * 2 + 1);
if (!digest)
return 1;
memset(digest, 0, len * 2 + 1);
for (i = 0; i < len; i++)
{
sprintf(&(digest[i * 2]), "%02x", result[i]);
}
printf("ACTUAL = %s\nEXPECTED = %s\n", digest, EXPECTED);
free(digest);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment