[英]How to return the md5 hash in a string in this code C++?
我有這個代碼正確顯示我,一個字符串的md5。 我更喜歡將一個字符串返回給函數,但是我將md5的值轉換為我的字符串時遇到了一些問題。 這是代碼:
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;
}
例如result[i]
是一個奇怪的ascii字符,如下所示: .
怎么可能解決這個問題?
更清潔的方式(更快)可能是這樣的:
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;
更換
for (i=0;i<16;i++){
printf ("%02x", buffer_md5[i]);
result[i]=buffer_md5[i];
}
同
char buf[32];
for (i=0;i<16;i++){
sprintf(buf, "%02x", buffer_md5[i]);
result.append( buf );
}
注意當你打印出結果,打印result
,而不是result[i]
得到整個字符串。
如果你將buffer_md5[i]
值直接放在結果中,那么你可能會遇到問題,因為字符串可能沒有嵌入0(如果有的話)。
似乎您正在使用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;
}
未經測試,因此可能存在錯誤。
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.