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

I have this code that shows me the correct md5 line. I prefer to return a string to a function, but I have a problem converting the md5 values ​​to 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]an ascii char is strange as follows: . How can I solve this problem?

+5
source share
4 answers

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

note that when printing the result, print result, not result[i]to get a whole line.

buffer_md5[i] , , 0 ( ).

+6

( ) :

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;
+9

, openssl.

MD5_DIGEST_LENGTH.

MD5 MD5_Init, MD5_Update MD5_Final.

MD5() , sprintf, .

:

    {
        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;
    }   

, .

+1

#include <sstream>

...

std::stringstream ss;

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

result = ss.str();

std::hex , . , :

for (i=0;i<16;i++){
        printf ("%02x", buffer_md5[i]);
        if (buffer_md5[i] < 10)
            ss << buffer_md5[i];
        else
            ss << 97 + buffer_md5[i] - 15;
    }
0

All Articles