C ++:如何将带有md5哈希的wstring转换为byte * array?

时间:2012-02-20 17:31:53

标签: c++ hash wstring

std::wstring hashStr(L"4727b105cf792b2d8ad20424ed83658c");

//....

byte digest[16];

如何在摘要中获取我的md5哈希? 我的回答是:

wchar_t * EndPtr;

for (int i = 0; i < 16; i++) {
std::wstring bt = hashStr.substr(i*2, 2);
digest[i] = static_cast<BYTE>(wcstoul(bt.c_str(), &EndPtr, 16));
}

2 个答案:

答案 0 :(得分:1)

您需要阅读hashStr中的两个字符,将它们从十六进制转换为二进制值,然后将该值放入digest中的下一个位置 - 此订单中的内容:

for (int i=0; i<16; i++) {
    std::wstring byte = hashStr.substr(i*2, 2);
    digest[i] = hextobin(byte);
}

答案 1 :(得分:0)

C-way(我没有测试它,但它应该可以工作(虽然我可能已经搞砸了)但你仍然会得到这个方法。

memset(digest, 0, sizeof(digest));

for (int i = 0; i < 32; i++)
{
    wchar_t numwc = hashStr[i];
    BYTE    numbt;

    if (numwc >= L'0' && numwc <= L'9')             //I assume that the string is right (i.e.: no SGJSGH chars and stuff) and is in uppercase (you can change that though)
    {
        numbt = (BYTE)(numwc - L'0');
    }
    else
    {
        numbt = 0xA + (BYTE)(numwc - L'A');
    }

    digest[i/2] += numbt*(2<<(4*((i+1)%2)));
}