using System.Text;
using System.Security.Cryptography;
using System.Windows.Forms;
string sourceData;
byte[] sourceBytes;
byte[] hashBytes;
sourceData = "MySourceData";
sourceBytes = ASCIIEncoding.ASCII.GetBytes(sourceData);
hashBytes = new MD5CryptoServiceProvider().ComputeHash(sourceBytes);
結果為 128-bit (16 位元組) 雜湊值。
lblHashResult.Text = sourceData + "\n" + ByteArrayToString(hashBytes) + "\n";
private string ByteArrayToString(byte[] input)
{
StringBuilder sb = new StringBuilder(input.Length * 2);
for (int i = 0; i < input.Length; i++)
sb.Append(input[i].ToString("X2"));
return sb.ToString();
}
sourceData = "NotMySourceData";
sourceBytes = ASCIIEncoding.ASCII.GetBytes(sourceData);
byte[] newHash = new MD5CryptoServiceProvider().ComputeHash(sourceBytes);
bool equal = false;
// 比較邏輯見下篇
| 類別 | 演算法 | 長度 |
|---|---|---|
| MD5CryptoServiceProvider | MD5 | 128-bit |
| SHA1CryptoServiceProvider | SHA-1 | 160-bit |
| SHA256Managed | SHA-256 | 256-bit |
| SHA512Managed | SHA-512 | 512-bit |
安全性需求高者建議使用 SHA-256 或以上;MD5 僅適合非安全性關鍵的完整性檢查。