Melkor
Melkor

Reputation: 15

Why when I convert the same C++ string in MD5 hash I obtain every time a different output?

I have a string converted to an MD5 hash using a python script with the following command:

admininfo['password'] = hashlib.md5(admininfo['password'].encode("utf-8")).hexdigest()

This value is now stored in an online database.

Now I'm creating a C++ script to do a login on this database. During the login, I ask for the password and I convert it to an MD5 hash to compare it with the value from the online database.

But giving the same string, I obtain a different MD5 hash value every time.

How can I fix it?

cin >> Admin_pwd;
cout << endl;

unsigned char digest[MD5_DIGEST_LENGTH];
const char* string = Admin_pwd.c_str();

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);

First try:

md5 digest: dcbb3e6add7fb94b98c56d7f70b7c46e

Second try:

md5 digest: 2870f4de491ad17d53d6d6e9dae19ca9

Third try:

md5 digest: 84656428baf461093e9fca2c8b05a296

Upvotes: 0

Views: 673

Answers (2)

Igor Tandetnik
Igor Tandetnik

Reputation: 52461

Make it MD5((unsigned char*)string, ...); drop the ampersand. You are not passing the character data to MD5 - you are passing the value of the string pointer itself (namely, the address of the first character of the password), plus whatever garbage happens to be on the stack after it.

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

(unsigned char*)&string

You're hashing the pointer itself (and unspecified data after it), not the string that it points to.

And it changes on every execution (maybe).

You meant just (unsigned char*)string.

Upvotes: 3

Related Questions