I have a program in C
, which calculates sha256
hash of input file. It is using the openSSL
library. Here is the core of the program:
#include <openssl/sha.h>
SHA256_CTX ctx;
unsigned char buffer[512];
SHA256_Init(&ctx);
SHA256_Update(&ctx, buffer, len);
SHA256_Final(buffer, &ctx);
fwrite(&buffer,32,1,stdout);
I need to change it to calculate sha512
hash instead.
Can I just (naively) change all the names of the functions from SHA256
to SHA512
, and then in the last step fwrite
64 bytes, instead of the 32
bytes ? Is that all, or do I have to make more changes ?
Note that SHA512_foo interfaces (as well as SHA256_foo interfaces) are deprecated as of OpenSSL 3.0. Applications should instead use EVP_DigestInit_ex(3), EVP_DigestUpdate(3) and EVP_DigestFinal_ex(3)
See https://docs.openssl.org/master/man3/SHA256_Init/
So to provide working code for modern openssl:
#include <openssl/evp.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
int main() {
#define DATA1 "Hello EVP"
#define DATA2 "Goodbye MD5"
unsigned char md_value[EVP_MAX_MD_SIZE];
unsigned int mdlen;
EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
const EVP_MD *md;
md = EVP_get_digestbyname("SHA512");
assert(md);
assert(mdctx);
assert(EVP_DigestInit_ex2(mdctx, md, NULL) != 0);
assert(EVP_DigestUpdate(mdctx, DATA1, sizeof(DATA1)) != 0);
assert(EVP_DigestUpdate(mdctx, DATA2, sizeof(DATA2)) != 0);
assert(EVP_DigestFinal_ex(mdctx, md_value, &mdlen) != 0);
EVP_MD_CTX_free(mdctx);
for (int i = 0; i < mdlen; i++)
printf("%02x", md_value[i]);
putchar('\n');
}
I compiled with gcc -o/tmp/foo /tmp/foo.c -lcrypto
and validated with printf "Hello EVP\0Goodbye MD5\0" | sha512sum