SecurityXploded Blog

CryptoCode: Create SHA256 Hash using OpenSSL

In the previous CryptoCode series articles, I had written about generating MD5/SHA1/SHA256 hashes, encryption/decryption algorithms using Windows Cryptography functions. Today I am writing about creating SHA256 hash using OpenSSL’s Cryptography Library.


OpenSSL is very popular library providing SSL & Cryptography based functions which is consumed by top softwares. OpenSSL library is FREE to use in commercial and non-commercial products so you don’t have to worry about licensing terms. This is another living example of good old saying that ‘Best Things in Life are FREE’.


Before we get into code, I will explain few steps on setting up OpenSSL Cryptography Library for your project.

  • Download the latest OpenSSL source
  • Include the headers in your project.   [ #include <openssl/sha.h>  //for all SHA hash functions ]
  • Add following source files to your project [ sha256.c (\openssl\crypto\sha\) and mem_clr.c (for cleanup) ]


Note that these steps are exclusively for creation of SHA256 hash. For other hash functions you need to include and integrate relevant files from OpenSSL source.

Once we have setup the OpenSSL library, now we will look into function which creates SHA256 hash for input buffer using OpenSSL Crypto Library


//
// Create SHA256 hash for input buffer using OpenSSL functions
//

void CreateSha256Hash(BYTE *byteBuffer, DWORD dwSize)
{

 BYTE byteResultHash[SHA256_DIGEST_LENGTH];
 SHA256_CTX c;

 //initialize hash functions
 SHA256_Init(&c);

 //add the input buffer for hash creation
 SHA256_Update(&c, byteBuffer, dwSize);

 //Finalize and get the hash data
 SHA256_Final(byteResultHash, &c);

}



Above code is pretty much self explanatory which takes input buffer and generates SHA256 hash using OpenSSL functions.The constant SHA256_DIGEST_LENGTH is the length of SHA256 hash which is 32 bytes (256 bits).

Here you can call SHA256_Update function as many times to repetitively add data and finally use SHA256_Final to get the SHA256 hash for entire input data.  This is useful while generating hash for the input file where you can read the bunch of data every time in a loop and call SHA256_Update function to add the data. When all data from file have been updated you can call SHA256_Final function to get the SHA256 hash for the file.


In the next posts, I will write more examples on using other hash functions/encryption algorithms from OpenSSL. Do drop your comments on suggestions or  on any problems following the above code.


See Also

CryptoCode: Index of All Crypto Articles


Leave a Reply