MD5 Hash From String

被刻印的时光 ゝ 提交于 2019-12-04 09:59:13

问题


Need to get MD5 hash from string.
Get an error MD5 is null.
I am tying to get a 32 character MD5 hash from a string.

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

回答1:


Need to get MD5 hash from string.

Then first you need to convert your string to binary data in some form. How you do that will depend on your requirements, but it'll probably be Encoding.GetBytes for some encoding... you need to work out which encoding though. Does this hash need to match the hash created somewhere else, for example?

Get an error MD5 is null.

That's because you're using MD5.Create incorrectly. The argument is an algorithm name. You should almost certainly just use the parameterless overload instead.

I suspect you want something like:

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



回答2:


The string passed to Create is not the "text to hash", but the algorithm to use. I suspect you want:

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



回答3:


The reason you are getting a null return is the string parameter to the Create method speciies the algorithm, not the text that is being hashed. There is no TextToHash algorithmn hence you get null as the return.



来源:https://stackoverflow.com/questions/12979212/md5-hash-from-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!