MD5 雜湊結果為 16 位元組陣列,慣用 32 字元十六進位字串表示。轉換方法:
private static string ByteArrayToHexString(byte[] bytes)
{
int length = bytes.Length;
StringBuilder sb = new StringBuilder();
foreach (byte data in bytes)
{
sb.Append(data.ToString("x2"));
}
return sb.ToString();
}
使用 byte.ToString("x2") 可直接將每個位元組格式化為兩位十六進位字元。
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Nocturne.Samples.CurrentProcessHashTest
{
class Program
{
static void Main(string[] args)
{
Process currProcess = Process.GetCurrentProcess();
string filePath = currProcess.MainModule.FileName;
string hash = string.Empty;
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
MD5 algorithm = MD5.Create();
byte[] hashData = algorithm.ComputeHash(fs);
hash = ByteArrayToHexString(hashData);
fs.Close();
}
Console.WriteLine("Hash:" + hash);
Console.ReadKey();
}
private static string ByteArrayToHexString(byte[] bytes)
{
StringBuilder sb = new StringBuilder();
foreach (byte data in bytes)
{
sb.Append(data.ToString("x2"));
}
return sb.ToString();
}
}
}
Process.GetCurrentProcess().MainModule.FileName 取得執行檔路徑。FileStream 必須設為 FileMode.Open、FileAccess.Read。MD5.Create() 建立演算法實例,ComputeHash(Stream) 直接計算。StringBuilder 迴圈 ToString("x2") 高效拼接。