MD5 C++ Class

5th August 2014 by Ian Martin

MD5+C%2b%2b+Class Image

MD5 C++ Class

5th August 2014 by Ian Martin

The MD5 class was derived from various C++ examples. The class is thread safe (an instance must be created for each thread) and uses no memory allocation.

Introduction

The MD5 algorithm produces a 128 bit hash of a byte array (often text).

Don't Use MD5

MD5 is now considered a "broken" hash and should now no longer be used in high security situations.

OK, If You Must Use MD5...

If you still wish to use MD5, for example to hash user passwords, always add a salt before hashing, to prevent a dictionary attack. The MD5 class was derived from various C++ examples. The class is thread safe (an instance must be created for each thread) and uses no memory allocation. In the MD5.h file, note the definition of an unsigned 32 bit integer; you may need to modify this.
typedef unsigned int MD5_UINT32;
There are 6 public functions, all named Compute, in two groups:-
  • to return the MD5 hash as an ASCII (8 bit) string
  • to return the MD5 hash as a wide (UTF-16) string
For each type above there is a Compute function that accepts a "wide" (UTF-16) string; there is an optional parameter to specify if the string should be converted to UTF-8 before hashing. If the string is known to be 8-bit (Unicode 0xff or less), set this to the default "false". Use the CMD5 class (files MD5.cpp and MD5.h). The CMD5 class also uses the CUnicode class (file Unicode.h) which has a single static public function. To use, create an instance of CMD5. Do not share that instance with other threads. Creation of the instance on the stack is recommended. Each public method returns an "unsafe" pointer to either an ASCII or UTF-16 string which is contained in the class instance and is only safe to be used whilst the class remains in scope, or before it is deleted or re-used. The classes may be downloaded here (6.1Kb zip). The code below demonstrates the use of all 6 public functions.



#include "md5.h"



//create an instance of MD5 on the stack

//which we will re-use for each example

CMD5 mx;



unsigned char test_array[5] = { 1, 2, 3, 5, 7 };



const wchar_t* res1 = mx.Compute("test string");

//

// res1 is safe to use until mx is re-used

// normally this would be copied to a safe location

// or used immediately

//



// version using 'wide' source string. Specify whether to 

// convert the string to utf-8

// (needed if any characters above u+ff are present)

const wchar_t* res2 = mx.Compute(L"test string", false);

// version using byte array

const wchar_t* res3 = mx.Compute(test_array,5);



//methods returning 8 bit string MD5

const char* res4 = mx.Compute_8("test string");

const char* res5 = mx.Compute_8(L"test string", false);

const char* res6 = mx.Compute_8(test_array, 5);