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;
    if(!SHA256_Init(&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))
	{
		//ERROR

	}
*/

SHA512

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