Stanislav Palatnik Stanislav Palatnik - 8 months ago 185
C++ Question

generate sha256 with openssl and C++

I'm looking to create a hash with sha256 using openssl and C++. I know there's a similar post about this here:

generate sha hash in openssl, but I'm looking to specifically create sha256.


Seems to be a problem witht he include paths. It can't find any openssl functions even though I included

#include "openssl/sha.h"

and I included the paths in my build

-I/opt/ssl/include/ -L/opt/ssl/lib/ -lcrypto


Here's how I did it:

void sha256(char *string, char outputBuffer[65])
    unsigned char hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    SHA256_Update(&sha256, string, strlen(string));
    SHA256_Final(hash, &sha256);
    int i = 0;
    for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
        sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
    outputBuffer[64] = 0;

int sha256_file(char *path, char outputBuffer[65])
    FILE *file = fopen(path, "rb");
    if(!file) return -534;

    byte hash[SHA256_DIGEST_LENGTH];
    SHA256_CTX sha256;
    const int bufSize = 32768;
    byte *buffer = malloc(bufSize);
    int bytesRead = 0;
    if(!buffer) return ENOMEM;
    while((bytesRead = fread(buffer, 1, bufSize, file)))
        SHA256_Update(&sha256, buffer, bytesRead);
    SHA256_Final(hash, &sha256);

    sha256_hash_string(hash, outputBuffer);
    return 0;

It's called like this:

static unsigned char buffer[65];
sha256("string", buffer);
printf("%s\n", buffer);