MD5功能无法正常工作

MD5 function not functioning properly

本文关键字:工作 常工作 功能 MD5      更新时间:2023-10-16

这是我当前的MD5函数。在 Windows 8.1 上使用时,它始终返回一个值,但在 Windows 7 上运行时,它只返回大约 50% 的时间的值。这对我来说很奇特。有什么想法吗?

事实证明,它在win7和win8上都是狡猾的。显然,对CryptGetHashParam的调用有时会因ERROR_MORE_DATA而失败。

std::string MD5(std::string input)
{
    HCRYPTPROV CryptProv;
    HCRYPTHASH CryptHash;
    BYTE BytesHash[33];//!
    DWORD dwHashLen;
    std::string final;
    if (CryptAcquireContext(&CryptProv,NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_MACHINE_KEYSET))
    {
        if (CryptCreateHash(CryptProv, CALG_MD5, 0, 0, &CryptHash))
        {
            if (CryptHashData(CryptHash, (BYTE*)input.c_str(), input.length(), 0))
            {
                if (CryptGetHashParam(CryptHash, HP_HASHVAL, BytesHash, &dwHashLen, 0))
                {
                    final.clear();
                    std::string hexcharset = "0123456789ABCDEF";
                    for (int j = 0; j < 16; j++)
                    {
                        final += hexcharset.substr(((BytesHash[j] >> 4) & 0xF), 1);
                        final += hexcharset.substr(((BytesHash[j]) & 0x0F), 1);
                    }
                }
            }
        }
    }
    CryptDestroyHash(CryptHash);
    CryptReleaseContext(CryptProv, 0);
    return final;
}
int _tmain(int argc, _TCHAR* argv[])
{
    char *pp = "derp";
    std::string derp = MD5(std::string(pp));
    printf("%sn", derp.c_str());
    system("pause");
    return 0;
}

我有一个绝妙的主意:在这些条件中添加else子句,以便您知道哪个条件失败了。将输出放在这些子句中,以便您可以查看有关错误条件的详细信息。然后你就会知道你的函数出了什么问题。