Hash結果的表示
我們常用的MD5 hash結果都是以32個字符來表示的16進制串,因此需要對上面得到的byte[]進行轉換。這個過程可以使用Convert.ToString(Int32, Int32)來進行十進制數向16進制轉換的過程。也可以用更簡單的byte.ToString("x2")來完成。
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();
}
完整的代碼
CurrentProcessHashTest
1 using System;
2 using System.Diagnostics;
3 using System.IO;
4 using System.Security.Cryptography;
5 using System.Text;
6
7 namespace Nocturne.Samples.CurrentProcessHashTest
8 {
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 Process currProcess = Process.GetCurrentProcess();
14 string filePath = currProcess.MainModule.FileName;
15 string hash = string.Empty;
16
17 using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
18 {
19 MD5 algorithm = MD5.Create();
20
21 byte[] hashData = algorithm.ComputeHash(fs);
22
23 hash = ByteArrayToHexString(hashData);
24
25 fs.Close();
26 }
27
28 Console.WriteLine("Hash:" + hash.ToString());
29
30 Console.ReadKey();
31 }
32
33 private static string ByteArrayToHexString(byte[] bytes)
34 {
35 int length = bytes.Length;
36
37 StringBuilder sb = new StringBuilder();
38
39 foreach (byte data in bytes)
40 {
41 sb.Append(data.ToString("x2"));
42 }
43
44 return sb.ToString();
45 }
46 }
47 }