This tutorial will guide you on how to hash a string by using OpenSSL’s HMAC hash function. HMAC hashing allow user to hash with a secret key. HMAC can take most of the hash engine in order to hash your data with the secret key. This tutorial will create two C++ example files which will compile and run in Ubuntu environment.
- Here are the openssl HMAC sample source code.
Example #1: hmac_sample1.cpp12345678910111213141516171819202122232425262728#include <stdio.h>#include <string.h>#include <openssl/hmac.h>int main(){// The key to hashchar key[] = "012345678";// The data that we're going to hash using HMACchar data[] = "hello world";unsigned char* digest;// Using sha1 hash engine here.// You may use other hash engines. e.g EVP_md5(), EVP_sha224, EVP_sha512, etcdigest = HMAC(EVP_sha1(), key, strlen(key), (unsigned char*)data, strlen(data), NULL, NULL);// Be careful of the length of string with the choosen hash engine. SHA1 needed 20 characters.// Change the length accordingly with your choosen hash enginechar mdString[20];for(int i = 0; i < 20; i++)sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);printf("HMAC digest: %s\n", mdString);return 0;}
Example #2: hmac_sample2.cpp123456789101112131415161718192021222324252627282930313233343536373839#include <stdio.h>#include <string.h>#include <openssl/hmac.h>int main() {// The secret key for hashingconst char key[] = "012345678";// The data that we're going to hashchar data[] = "hello world";// Be careful of the length of string with the choosen hash engine. SHA1 needed 20 characters.// Change the length accordingly with your choosen hash engine.unsigned char* result;unsigned int len = 20;result = (unsigned char*)malloc(sizeof(char) * len);HMAC_CTX ctx;HMAC_CTX_init(&ctx);// Using sha1 hash engine here.// You may use other hash engines. e.g EVP_md5(), EVP_sha224, EVP_sha512, etcHMAC_Init_ex(&ctx, key, strlen(key), EVP_sha1(), NULL);HMAC_Update(&ctx, (unsigned char*)&data, strlen(data));HMAC_Final(&ctx, result, &len);HMAC_CTX_cleanup(&ctx);printf("HMAC digest: ");for (int i = 0; i != len; i++)printf("%02x", (unsigned int)result[i]);printf("\n");free(result);return 0;} - Let’s try to compile both sample cpp files and you should observe the following output screenshot.
Note: -lcrypto will include the crypto library from openssl~$ gcc hmac_sample1.cpp -o sample1 -lcrypto
~$ ./sample1
HMAC digest: e19e220122b37b708bfb95aca2577905acabf0c0
~$ gcc hmac_sample2.cpp -o sample2 -lcrypto
~$ ./sample2
HMAC digest: e19e220122b37b708bfb95aca2577905acabf0c0

hosen