This tutorial will guide you on how to hash a string by using OpenSSL’s MD5 hash function. This tutorial will create two C++ example files which will compile and run in Ubuntu environment.
- Make sure that we have both OpenSSL & libssl-dev installed in the system.
~$ dpkg --get-selections | grep openssl
openssl install~$ dpkg --get-selections | grep libssl
libssl-dev install
libssl-doc install
libssl1.0.0 install - Install the modules in case there are not available in your system:
~$ sudo apt-get install openssl~$ sudo apt-get install libssl-dev
- Here are the openssl md5 sample source code.
Example #1: md5_sample1.cpp1234567891011121314151617181920#include <stdio.h>#include <string.h>#include <openssl/md5.h>int main(){unsigned char digest[MD5_DIGEST_LENGTH];char string[] = "happy";MD5((unsigned char*)&string, strlen(string), (unsigned char*)&digest);char mdString[33];for(int i = 0; i < 16; i++)sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);printf("md5 digest: %s\n", mdString);return 0;}
Example #2: md5_sample2.cpp1234567891011121314151617181920212223#include <stdio.h>#include <string.h>#include <openssl/md5.h>int main() {unsigned char digest[16];const char* string = "happy";printf("string length: %d\n", strlen(string));MD5_CTX ctx;MD5_Init(&ctx);MD5_Update(&ctx, string, strlen(string));MD5_Final(digest, &ctx);char mdString[33];for (int i = 0; i < 16; i++)sprintf(&mdString[i*2], "%02x", (unsigned int)digest[i]);printf("md5 digest: %s\n", mdString);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 md5_sample1.cpp -o sample1 -lcrypto
~$ ./sample1
md5 digest: 5eb53bbbe01eeed093cb22bb8f5acdc3
~$ gcc md5_sample2.cpp -o sample2 -lcrypto
~$ ./sample2
md5 digest: 5eb53bbbe01eeed093cb22bb8f5acdc3
Great example! Thank you 🙂
Excellent!
Why you set the length of mdString as 33?? can´t md5 be longer??
thanks!
MD5 hash value is expressed as a hex number, 32 digits long. In this tutorial, the allocation of 33 will give 1 additional space for null terminated string in C++.