Click here to Skip to main content
15,899,679 members
Articles / Desktop Programming / MFC
Article

Use Windows Crypto API to calculate a MD5 string.

Rate me:
Please Sign up or sign in to vote.
3.49/5 (29 votes)
29 Aug 2002 212K   6K   57   24
Use Windows Crypto API to calculate a MD5 string.

Introduction

The source code demonstrates how to invoke the Windows Crypto API to calculate a MD5 string.

The MD5 Message-Digest Algorithm is described in Internet RFC 132.

The sample uses the class Cmd5Capi, a very simple MFC class to wrap the standard win api necesary calls.

Includes required

#include <wincrypt.h> // Cryptographic API Prototypes and Definitions

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Spain Spain
Now, I works for Aurigae S.A a spanish services enterprise, specialized on information technologies for critical mission applications, mainly in the areas of payment system management, stock trading and telecommunications.

Comments and Discussions

 
GeneralThanks Pin
Asaf G6-May-08 0:05
Asaf G6-May-08 0:05 
QuestionHow to decrypt data? Pin
ivax4-Oct-05 0:49
ivax4-Oct-05 0:49 
AnswerRe: How to decrypt data? Pin
andyj11526-Oct-05 0:06
andyj11526-Oct-05 0:06 
GeneralA better solution : here is the code Pin
Elmue22-Apr-04 10:43
Elmue22-Apr-04 10:43 
GeneralRe: A better solution : here is the code Pin
HughJampton25-Apr-05 6:11
HughJampton25-Apr-05 6:11 
GeneralRe: A better solution : here is the code Pin
Anonymous25-Apr-05 12:32
Anonymous25-Apr-05 12:32 
GeneralRe: A better solution : here is the code Pin
HughJampton25-Apr-05 15:00
HughJampton25-Apr-05 15:00 
GeneralExcellent code - one simple modification Pin
Douglas R. Keesler5-Jun-05 15:41
Douglas R. Keesler5-Jun-05 15:41 

The MD5FinalToString() method returns an upper case hash, which is great for hashing files. You don't want to mess around with case matching to find out if the file was modified. However, if you're getting a hash from string input, most likely you are either creating an encryption key or storing a password validation string. In the latter event string case doesn't matter, but if you're creating an encryption key, mixed case makes a much stronger key. So I added a new function called MD5ToEncryptionKey(). It is basically a copy/paste of the aforementioned method, with a slight modification. Here is the code:

char* DCipher::MD5ToEncryptionKey()     //commented lines are my modifications
{
    unsigned char signature[16];
    MD5Final(signature);

	srand(16);      // Seed the Random Number Generator
	int val;        // Declare an integer

    ms8_MD5[0] = 0;
    char s8_Temp[5];
    for (int i=0; i<16; i++) 
    {
		val = rand() % 2;   // val = remainder of rand()/2
                           
		if(val < 1) // if even num, use upper - else use lower
			sprintf(s8_Temp, "%02X", signature[i]);
		else	
			sprintf(s8_Temp, "%02x", signature[i]);	
                             
        strcat(ms8_MD5, s8_Temp);
    }

    return ms8_MD5;
}

I simply seeded the random number generator to ensure the same random numbers would be generated on each call. Then by taking the modulus (remainder) of the random number divided by two, I determined whether it was odd or even. If an even random number use upper case hex, else use lower case hex (of course it has no effect on decimal digits).

Then I changed CalcMD5FromString() to return a call to this function.

One suggestion: if you use this for file encryption, change to function to accept an integer as a parameter and pass the file-size to the function, then you could seed the random number generator with that number. That way you would generate a different sequence of random numbers for each file, but ensure the sequence would repeat reliably for each file.

BTW, I incorporated this class into an overall file encryption class I was working on. The class is designed for internal file encryption. I use it in conjunction with my serialization overrides, to be able to read and save data with standard serialization methods, but always have the data encrypted on disk. The point of this class was to be able to generate encryption keys that were not generated of user input and were not stored anywhere. [It generates a 64-byte (512 bit) encryption key] I also wanted to be able to add a signature to the file that is not part of the encryption scheme, but would not allow files to be decrypted unless the signature matched - this is not for security, but for file control - so we don't try to decrypt files that don't belong to the app.

All of this has been incorporated into a single class which is achieved by creating an instance of the class, and then calling the method passing only the filepath and your apps signature. It's availabe in both generic class and DLL. I plan on posting an article on CP when I get time, offering this back to the public domain. It may be a couple weeks or so before I get time to write the article. If you want this, or need it sooner, post a message and I'll try to make a "article-less" download available.

It has some MFC in it, but very little. It could easily be modified for cross-platform projects.

Cheers to all!





In business, if two people always agree, one of them is unnecessary.

GeneralRe: A better solution : here is the code Pin
pscholl6-Jun-08 6:01
pscholl6-Jun-08 6:01 
GeneralRe: A better solution : here is the code Pin
Elmue6-Jun-08 14:40
Elmue6-Jun-08 14:40 
GeneralProblem with this constructor. Pin
Prakash Nadar20-Jan-04 16:28
Prakash Nadar20-Jan-04 16:28 
GeneralCompile Error ! Pin
freedem2-Dec-03 15:00
freedem2-Dec-03 15:00 
GeneralRe: Compile Error ! Pin
Victor M. Valenzuela2-Dec-03 21:28
Victor M. Valenzuela2-Dec-03 21:28 
GeneralRe: Compile Error ! Pin
Ștefan-Mihai MOGA29-Mar-06 20:44
professionalȘtefan-Mihai MOGA29-Mar-06 20:44 
GeneralRe: Compile Error ! Pin
bahram_cho6-Apr-07 20:42
bahram_cho6-Apr-07 20:42 
Generalcompilation Errors Pin
Rohit Gadagkar24-Sep-03 7:40
Rohit Gadagkar24-Sep-03 7:40 
GeneralRe: compilation Errors Pin
Vinayak16-Jun-04 9:54
Vinayak16-Jun-04 9:54 
GeneralRe: compilation Errors Pin
Scott B.21-Mar-06 18:59
Scott B.21-Mar-06 18:59 
GeneralDifferent Output Pin
tunafish245-Aug-03 16:42
tunafish245-Aug-03 16:42 
GeneralRe: Different Output Pin
qihongbo28-Sep-03 22:04
qihongbo28-Sep-03 22:04 
GeneralThanks Pin
Paul Hooper25-Apr-03 14:40
Paul Hooper25-Apr-03 14:40 
GeneralCrypto.h Pin
Anonymous4-Nov-02 3:15
Anonymous4-Nov-02 3:15 
GeneralRe: Crypto.h Pin
Ștefan-Mihai MOGA27-Jun-05 0:49
professionalȘtefan-Mihai MOGA27-Jun-05 0:49 
GeneralNeeds improvements Pin
Vagif Abilov30-Aug-02 2:46
professionalVagif Abilov30-Aug-02 2:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.