[英]How can I compute MD5 hash of “a” in C#?
我試圖練習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();
}
}
}
}
要獲取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編碼字符串的事實。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.