Generate a hash of a string, file, whatever.

Salting your hash

Combine your salt with what is being hashed (e.g. typically you do this with a password).  SHA256 and other hash generation algorithms don't take salt but if you add the salt to the end of what is being hashed you will get a different result, hence it is salted.

Generating SHA256 Hash Of A File Or String

//#include <openssl/sha.h>  (Also add the -lcrypto linker option)

//********** GENERATE SAHA256 HASH **********
//input_data			The data you want to generate a hash of
//data_length			The length of the data in bytes
//message_digest		The resulting hash.  Create as: unsigned char output_buffer[65];	(32 byte hash for SHA256, converted to 2 chars of hex per byte + trailing null
bool generate_sha256_hash (void *input_data, unsigned long data_length, char *output_buffer)
	unsigned char message_digest[SHA256_DIGEST_LENGTH];		//32 bytes for SHA256
    SHA256_CTX context;
        return false;

    if(!SHA256_Update(&context, (unsigned char*)input_data, data_length))		//<This can be called repeatedly if you have lots of data, e.g. a large file you want to hash
        return false;

    if(!SHA256_Final(message_digest, &context))
        return false;

	//Convert from binary to hex string (2 characters of hex per byte)
    int i = 0;
    for(i = 0; i < SHA256_DIGEST_LENGTH; i++)
        sprintf((char*)output_buffer + (i * 2), "%02x", message_digest[i]);
    output_buffer[64] = 0;
    return true;
/* Example of using it
char sha256_hash[65];
char test_string[] = "my test string";
	if(!generate_sha256_hash(test_string, 14, sha256_hash))



Should just be a case of renaming the functions and increasing the size of the output string buffer


We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.


Your email address will not be published.