我尝试练习C#编程。我试着计算一个字符串“a”的MD5.has。但如何修复此代码,因为它输出4144e195f46de78a3623da7364d04f11而不是0cc175b9c0f1b6a831c399e269772661?
//Title of this code
//Rextester.Program.Main is the entry point for your code. Don't change it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
using System.Security.Cryptography;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
string a="a";
Console.WriteLine(CalculateMD5Hash(a));
Console.ReadKey();
}
public static string CalculateMD5Hash(string input)
{
using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] retval = md5.ComputeHash(Encoding.Unicode.GetBytes(input));
StringBuilder sb = new StringBuilder();
for (int i=0;i<retval.Length;++i)
{
sb.Append(retval[i].ToString("x2"));
}
return sb.ToString();
}
}
}
}
答案 0 :(得分:0)
要获得0cc175b9c0f1b6a831c399e269772661
,您只需使用Encoding.UTF8
。
using (var md5 = System.Security.Cryptography.MD5.Create())
{
byte[] hashValue = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
var sb = new StringBuilder();
foreach (byte b in hashValue)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
请查看.NET使用UTF-16对字符串进行编码的事实。