我們都知道用HashAlgorithm.ComputeHash方法可以計算資料的雜湊值。不過System.Security.Cryptography.HashAlgorithm類是繼承ICryptoTransform介面的,那麼,通過CryptoStream(或者直接操作ICryptoTransform)也是可以計算雜湊值的。
ICryptoTransform的輸入資料就是需要計算雜湊值的來源資料,不過ICryptoTransform的輸出資料和輸入資料是一樣的,真正的雜湊值存在HashAlgorithm的Hash屬性裡。
代碼:
//+ using System.IO;
//+ using System.Security.Cryptography;
var str = "Mgen!";
using (var sha1 = SHA1.Create())
using (var mstm = new MemoryStream())
using (var crystm = new CryptoStream(mstm, sha1, CryptoStreamMode.Write))
{
var data = Encoding.Unicode.GetBytes(str);
//輸出來源資料
Console.WriteLine(BitConverter.ToString(data));
crystm.Write(data, 0, data.Length);
crystm.FlushFinalBlock();
//輸出目標資料(等於來源資料)
Console.WriteLine(BitConverter.ToString(mstm.ToArray()));
//輸出雜湊值
Console.WriteLine(BitConverter.ToString(sha1.Hash));
}
輸出:
4D-00-67-00-65-00-6E-00-21-00
4D-00-67-00-65-00-6E-00-21-00
2B-5A-09-C1-E2-73-CF-BC-95-AA-0F-1B-A7-0D-9B-09-CB-61-F1-6F
前兩行是源字串的資料,最後一行是雜湊值。