.NET(C#):用CryptoStream計算雜湊值

來源:互聯網
上載者:User

我們都知道用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

前兩行是源字串的資料,最後一行是雜湊值。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.