首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 獲取當前進程 Hash 值的方法 (二) 完整代碼實現

     編輯:關於C語言

位元組陣列轉十六進位字串

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") 高效拼接。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved