SHA1雜湊演算法

來源:互聯網
上載者:User

      SHA1雜湊演算法是一個用來進行數位簽章的演算法,對於長度小於2^64位的訊息,SHA1會產生一個160位的訊息摘要,這個訊息摘要可以用來驗證資料的完整性。SHA1有一些特性,一是不可以從訊息摘要中複原資訊,另外一個就是不同的訊息會產生不同的訊息摘要。所以如果在傳輸的過程中,資料發生了丟失或者損壞,通過訊息摘要就可以看出來。

      在.NET中對程式集進行強簽名的時候,需要產生一個公開金鑰,通過公開金鑰產生一個公開金鑰標記的時候也會用到SHA1演算法。這個演算法的具體原理,可以在網上找到,這裡介紹一下用.NET提供的類庫來使用這個演算法。主要有四種使用方式。

    1.通過SHA1CryptoServiceProvider

System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();

 

 //strSource為傳入的字串,位元組數組為加密後的

 byte[] bytResult = sha.ComputeHash(System.Text.Encoding.Default.GetBytes(strSource));

    2.通過SHA1類

System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create();

 

//注意編碼UTF8、UTF7、Unicode等的選擇 

byte[] bytResult = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strSource));

    3.通過HashPasswordForStoringInConfigFile方法

return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strSource, "SHA1");

     4.使用SHA1Managed

SHA1Managed sha = new SHA1Managed();

 

byte[] bytResult = sha.ComputeHash(strSource);

    四種方法產生的結果都一樣,唯一需要注意的就是傳入的字串的編碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.