Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the md5 hash in a string in this code C++?

Tags:

c++

string

md5

I have this code that show me correctly, the md5 of a string. I prefer to return a string to the function, but I have some problem converting the values of md5 into my string. This is the code:

string calculatemd5(string msg)
{
string result;
const char* test = msg.c_str();
int i;

MD5_CTX md5;

MD5_Init (&md5);
MD5_Update (&md5, (const unsigned char *) test, msg.length());
unsigned char buffer_md5[16];
MD5_Final ( buffer_md5, &md5);
printf("Input: %s", test);
printf("\nMD5: ");
for (i=0;i<16;i++){
    printf ("%02x", buffer_md5[i]);
    result[i]=buffer_md5[i];
}
std::cout <<"\nResult:"<< result[i]<<endl;
return result;
}

For example result[i] is a strange ascii char like this: . How can is possible solve this problem?

like image 722
user1056635 Avatar asked Nov 24 '11 12:11

user1056635


3 Answers

A cleaner way (and faster) might be like this:

std::string result;
result.reserve(32);  // C++11 only, otherwise ignore

for (std::size_t i = 0; i != 16; ++i)
{
  result += "0123456789ABCDEF"[hash[i] / 16];
  result += "0123456789ABCDEF"[hash[i] % 16];
}

return result;
like image 184
Kerrek SB Avatar answered Oct 12 '22 22:10

Kerrek SB


replace

for (i=0;i<16;i++){
    printf ("%02x", buffer_md5[i]);
    result[i]=buffer_md5[i];
}

with

char buf[32];
for (i=0;i<16;i++){
    sprintf(buf, "%02x", buffer_md5[i]);
    result.append( buf );
}

notice that when you print out result, print result, not result[i] to get whole string.

if you put the buffer_md5[i] value directly in result then you may get problems since a string may not have an embedded 0 (if there is one).

like image 31
AndersK Avatar answered Oct 12 '22 23:10

AndersK


Seems that you are using openssl.

Use constant MD5_DIGEST_LENGTH.

You can also use MD5 function instead of MD5_Init, MD5_Update and MD5_Final.

MD5() may take most of the time, but if you want to reduce time of sprintf, then do hex string manually.

Like this way:

    {
        static const char hexDigits[16] = "0123456789ABCDEF";
        unsigned char digest[MD5_DIGEST_LENGTH];
        char digest_str[2*MD5_DIGEST_LENGTH+1];
        int i;

        // Count digest
        MD5( (const unsigned char*)msg.c_str(), msg.length(), digest );

        // Convert the hash into a hex string form
        for( i = 0; i < MD5_DIGEST_LENGTH; i++ )
        {
            digest_str[i*2]   = hexDigits[(digest[i] >> 4) & 0xF];
            digest_str[i*2+1] = hexDigits[digest[i] & 0xF];
        }
        digest_str[MD5_DIGEST_LENGTH*2] = '\0';

        std::cout <<"\nResult:"<< digest_str <<endl;
    }   

not tested, so there may be bugs.

like image 35
SKi Avatar answered Oct 12 '22 22:10

SKi