来自字符串的MD5哈希

pap*_*zzo 23 .net md5

需要从字符串中获取MD5哈希值.
获取错误MD5为空.
我想从字符串中获取32个字符的MD5哈希值.

using (System.Security.Cryptography.MD5 md5 = 
       System.Security.Cryptography.MD5.Create("TextToHash"))
{
    byte[] retVal = md5.Hash;
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < retVal.Length; i++)
    {
        sb.Append(retVal[i].ToString("x2"));
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 46

需要从字符串中获取MD5哈希值.

然后首先需要以某种形式将字符串转换为二进制数据.你如何做到这将取决于你的要求,但它可能是Encoding.GetBytes一些编码...你需要弄清楚哪种编码.例如,这个哈希是否需要匹配在其他地方创建的哈希?

获取错误MD5为空.

那是因为你使用MD5.Create不当.参数是算法名称.您几乎肯定会使用无参数过载.

我怀疑你想要的东西:

byte[] hash;
using (MD5 md5 = MD5.Create())
{
    hash = md5.ComputeHash(Encoding.UTF8.GetBytes(text));
}
// Now convert the binary hash into text if you must...
Run Code Online (Sandbox Code Playgroud)

  • @xanadont:不.MD5是标准化算法.结果改变基本上是一个错误. (2认同)

Ree*_*sey 21

传递给的字符串Create不是"要散列的文本",而是要使用的算法.我怀疑你想要:

using (System.Security.Cryptography.MD5 md5 = 
   System.Security.Cryptography.MD5.Create())
{
    byte[] retVal = md5.ComputeHash(Encoding.Unicode.GetBytes("TextToHash"));
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < retVal.Length; i++)
    {
        sb.Append(retVal[i].ToString("x2"));
    }
}
Run Code Online (Sandbox Code Playgroud)