Calculate MD5 programmatically (c++ and golang)

By | November 29, 2022

MD5 is 128 bit hash digest calculated by Message Digest Method 5 algorithm. It is not so secure as SHA-256 algorithm but significantly faster. It is still widely used as thumbprint to verify data integrity and detect accidental data corruption. Here is c++ example how to calculate MD5 hash of string using openssl API. Templates of MD5 hash functions are defined in evp.h openssl include file.


#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
int main(int n, char ** s)
{
   char md5hex[EVP_MAX_MD_SIZE * 2 + 1];
   if(n<2)
   {
      printf("Please specify argument string to calculate MD5 checksum\n");
      return -1;
   }
   EVP_MD_CTX * pEvpContext;
   pEvpContext = EVP_MD_CTX_create();

   unsigned char unMdValue[EVP_MAX_MD_SIZE];
   unsigned int uiMdLength;

   // Initialization
   EVP_MD_CTX_init( pEvpContext );
   EVP_DigestInit_ex(pEvpContext, EVP_md5(), NULL );

   // Calculate MD5 for given string
   EVP_DigestUpdate( pEvpContext, s[1], strlen(s[1]) );

   // Save MD5 into temp variable
   EVP_DigestFinal_ex ( pEvpContext, unMdValue, &uiMdLength );

   EVP_MD_CTX_destroy(pEvpContext);

   // Copy the digest from the temp variable into the return value
   unsigned int md5hexSize = sizeof(md5hex);
   memset(md5hex, ‘\0’, md5hexSize);

   // if the size is bigger than the return buffer size, just exit
   if ( 2*uiMdLength > md5hexSize) {
      return false;
   }

   for ( unsigned int i = 0; i < uiMdLength; i++ )
   {
      sprintf(&md5hex[i*2], "%02x", unMdValue[i] );
   }
   printf("Line: %s\nIts MD5: %s\n", s[1], md5hex);
   return 0;
}

Compilation:


# g++ -o md5 md5.cpp -lssl -lcrypto

Execution:


# ./md5 "String to calculate MD% hash"
Line: String to calculate MD% hash
Its MD5: 82ccf9d87f24070dd945aa5daf41f8a8

Compare with md5sum command:


# echo -n "String to calculate MD% hash" | md5sum
82ccf9d87f24070dd945aa5daf41f8a8 –

Now Go example.


import (
   "crypto/md5"
   "fmt"
   "os"
)

func main() {
   argLen := len(os.Args)
   if argLen == 1 {
      fmt.Println("Specify string as an argument to calculate its MD5")
      os.Exit(-1)
   }
   byteArray := []byte(os.Args[1])
   fmt.Printf("%x", md5.Sum(byteArray))
}

Compilation:


C:\projects\Go\hash>go build md5.go

Execution:


C:\projects\Go\hash>md5 “String to calculate MD% hash”
82ccf9d87f24070dd945aa5daf41f8a8

Leave a Reply

Your email address will not be published. Required fields are marked *