Created
January 12, 2022 17:50
-
-
Save black-dragon74/72b74eafbdbfa0630710beae54896fb1 to your computer and use it in GitHub Desktop.
New way to Calculate SHA256Sum from OpenSSL v3
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
#include <stdio.h> | |
#include <string.h> | |
#include <openssl/sha.h> | |
#include <openssl/evp.h> | |
#if OPENSSL_VERSION_NUMBER < 0x10100000L | |
#define EVP_MD_CTX_new EVP_MD_CTX_create | |
#define EVP_MD_CTX_free EVP_MD_CTX_destroy | |
#endif | |
char msg[] = "HashMe"; | |
// Helper function to print the hash | |
void printHash(const char *hash) { | |
for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i) { | |
printf("%02x", hash[i]); | |
} | |
printf("\n"); | |
} | |
// This is the former way of calculating the hash, deprecated in OSSL3.x | |
void deprecatedHash() { | |
unsigned char hash[SHA256_DIGEST_LENGTH] = {0,}; | |
SHA256_CTX myCtx; | |
SHA256_Init(&myCtx); | |
SHA256_Update(&myCtx, msg, strlen(msg)); | |
SHA256_Final(hash, &myCtx); | |
printHash(hash); | |
} | |
// The preferred way from OSSL3.x+ | |
void hash() { | |
int sz = EVP_MD_size(EVP_sha256()); | |
unsigned char *hash = OPENSSL_malloc(sz); | |
if (hash == NULL) | |
return -1; | |
EVP_MD_CTX *ctx; | |
ctx = EVP_MD_CTX_new(); | |
if (ctx == NULL) | |
return -1; | |
// Error handling is not done here to keep the gist small and clean | |
// All 3 functions below are expected to return 1 on successful operation | |
EVP_DigestInit(ctx, EVP_sha256()); | |
EVP_DigestUpdate(ctx, msg, strlen(msg)); | |
EVP_DigestFinal(ctx, hash, &sz); | |
printHash(hash); | |
EVP_MD_CTX_free(ctx); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment