Generate sha256 with openssl / C++

In Encryption on September 27, 2011 by patrellery Tagged: , ,

Here’s a simple code if you need to generate sha256 in C++ with openssl enable.

#include "openssl/sha.h"

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;

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


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: