Click here to Skip to main content
Licence 
First Posted 29 Aug 2002
Views 143,263
Bookmarked 52 times

Use Windows Crypto API to calculate a MD5 string.

By | 29 Aug 2002 | Article
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

About the Author

Victor M. Valenzuela

Web Developer

Spain Spain

Member

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.


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralThanks PinmemberAsaf G0:05 6 May '08  
QuestionHow to decrypt data? Pinmemberivax0:49 4 Oct '05  
AnswerRe: How to decrypt data? PinmemberJohn A. Johnson0:06 26 Oct '05  
GeneralA better solution : here is the code PinmemberElmue10:43 22 Apr '04  
GeneralRe: A better solution : here is the code PinmemberHughJampton6:11 25 Apr '05  
GeneralRe: A better solution : here is the code PinsussAnonymous12:32 25 Apr '05  
GeneralRe: A better solution : here is the code PinmemberHughJampton15:00 25 Apr '05  
GeneralExcellent code - one simple modification PinmemberDouglas R. Keesler15:41 5 Jun '05  

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 Pinmemberpscholl6:01 6 Jun '08  
GeneralRe: A better solution : here is the code PinmemberElmue14:40 6 Jun '08  
GeneralProblem with this constructor. PinmemberMr.Prakash16:28 20 Jan '04  
GeneralCompile Error ! Pinmemberfreedem15:00 2 Dec '03  
GeneralRe: Compile Error ! PinmemberVictor M. Valenzuela21:28 2 Dec '03  
GeneralRe: Compile Error ! PinmemberMihai Moga20:44 29 Mar '06  
GeneralRe: Compile Error ! Pinmemberbahram_cho20:42 6 Apr '07  
Generalcompilation Errors Pinmemberrohitgad7:40 24 Sep '03  
GeneralRe: compilation Errors PinmemberVinayak9:54 16 Jun '04  
GeneralRe: compilation Errors PinmemberScott B.18:59 21 Mar '06  
GeneralDifferent Output PinmemberAtif Goheer16:42 5 Aug '03  
GeneralRe: Different Output Pinmemberqihongbo22:04 28 Sep '03  
GeneralThanks PinmemberPaul Hooper14:40 25 Apr '03  
GeneralCrypto.h PinsussAnonymous3:15 4 Nov '02  
GeneralRe: Crypto.h PinmemberStefan-Mihai MOGA0:49 27 Jun '05  
GeneralNeeds improvements PinmemberVagif Abilov2:46 30 Aug '02  

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

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120528.1 | Last Updated 30 Aug 2002
Article Copyright 2002 by Victor M. Valenzuela
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid