我试图在MD5中生成C#哈希,但无法检索我所期望的字符串。
使用MD5哈希发生器,字符串Hello World!返回ed076287532e86365e841e92bfc50d8c的散列。
使用此代码:
string hash;
using (MD5 md5 = MD5.Create())
{
hash = Encoding.UTF8.GetString(md5.ComputeHash(Encoding.Default.GetBytes("Hello World!")));
}返回有问题的�\ab�S.�6^����\r�。
我怀疑这与我对字符串的编码有关。如何检索期望值?
编辑:如您所见,我在使用MD5哈希方面没有多少经验--这个问题的目的是教育自己,而不是使用代码来保护信息。
发布于 2015-08-26 07:34:41
ComputeHash()返回一个字节数组。使用一种方法将其转换为所需的十六进制格式,例如BitConverter.ToString和一些字符串操作,以消除连字符:
string hash;
using (MD5 md5 = MD5.Create())
{
hash = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes("Hello World!")));
}
hash = hash.Replace("-", "");输出:ED076287532E86365E841E92BFC50D8C
发布于 2015-08-26 07:28:59
ComputeHash()返回一个字节数组。您必须以十六进制方式将该字节数组转换为字符串。
public string CalculateMD5Hash(string input)
{
// step 1, calculate MD5 hash from input
using(MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder(2 * hash.Length);
for (int i = 0; i < hash.Length; i++)
{
// use "x2" for all lower case.
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
}发布于 2015-08-26 07:35:15
如果要对散列进行string表示,则必须对其byte[]表示进行编码:
using System.Security.Cryptography;
...
public string MD5Hash(String input) {
using (MD5 md5 = MD5.Create()) {
return String.Concat(md5
.ComputeHash(Encoding.UTF8.GetBytes(input))
.Select(item => item.ToString("x2")));
}
}
...
// hash == "ed076287532e86365e841e92bfc50d8c"
String hash = MD5Hash("Hello World!");https://stackoverflow.com/questions/32220395
复制相似问题