C# 中的 MD5 雜湊
· 3 分鐘閱讀
這篇備忘錄記錄了在 C# 中實現 MD5 雜湊的方法。
資訊
MD5 (Message-Digest Algorithm 5) 是一種廣泛使用的加密雜湊函數,它生成一個 128 位(16 字節)的雜湊值。儘管 MD5 在加密安全方面已被認為不再安全(存在碰撞攻擊),但它仍然經常用於文件完整性校驗或非安全數據的快速雜湊。
1. 使用 System.Security.Cryptography.MD5 類
C# 提供了內置的 MD5 類(位於 System.Security.Cryptography 命名空間)來計算 MD5 雜湊值。
範例:對字串進行 MD5 雜湊
using System;
using System.Security.Cryptography;
using System.Text;
public class Md5Hasher
{
public static string CalculateMd5Hash(string input)
{
// 創建 MD5 雜湊算法的實例
using (MD5 md5 = MD5.Create())
{
// 將輸入字串轉換為字節數組
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
// 計算雜湊值
byte[] hashBytes = md5.ComputeHash(inputBytes);
// 將字節數組轉換為十六進制字串
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2")); // "x2" 格式化為兩位十六進制
}
return sb.ToString();
}
}
public static void Main(string[] args)
{
string text = "Hello, MD5!";
string hash = CalculateMd5Hash(text);
Console.WriteLine($"原始字串: {text}");
Console.WriteLine($"MD5 雜湊: {hash}");
// 預期的 MD5 雜湊值 for "Hello, MD5!" (小寫)
// 9e2469446d3288a7c207b04cfd6e01a4
}
}
範例:對文件進行 MD5 雜湊
對文件內容計算 MD5 雜湊通常用於驗證文件是否在傳輸過程中被修改。
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class FileMd5Hasher
{
public static string CalculateFileMd5Hash(string filePath)
{
if (!File.Exists(filePath))
{
return "文件不存在。";
}
using (MD5 md5 = MD5.Create())
{
using (FileStream stream = File.OpenRead(filePath))
{
byte[] hashBytes = md5.ComputeHash(stream);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2"));
}
return sb.ToString();
}
}
}
public static void Main(string[] args)
{
string filePath = "example.txt"; // 替換為你的文件路徑
// 創建一個範例文件
File.WriteAllText(filePath, "這是一個測試文件的內容。");
string fileHash = CalculateFileMd5Hash(filePath);
Console.WriteLine($"文件路徑: {filePath}");
Console.WriteLine($"文件 MD5 雜湊: {fileHash}");
// 清理範例文件
File.Delete(filePath);
}
}
2. 安全注意事項
- 不適用於密碼儲存:由於 MD5 存在嚴重的安全漏洞(例如碰撞攻擊),絕對不應該將其用於儲存用戶密碼。對於密碼,應使用專為此目的設計的單向雜湊函數,如 PBKDF2、bcrypt 或 scrypt。
- 不適用於數字簽名或認證:同樣,MD5 不應在需要強加密安全的場景中使用。
- 用途:主要用途應該限於文件完整性校驗(驗證文件是否被意外更改)或生成非安全數據的快速雜湊。
總結
C# 中的 MD5 類提供了一種簡單直觀的方式來計算 MD5 雜湊值。雖然它在安全性方面存在限制,但在正確的應用場景下(如文件校驗),它仍然是一個有用的工具。務必牢記其安全限制,避免在加密敏感的上下文中使用它。
読み込み中...