1. 程式人生 > >.Net Core 最優 MD5 開啟方式!初學者建議收藏(支援 SHA1,SHA256,.Net Framework)

.Net Core 最優 MD5 開啟方式!初學者建議收藏(支援 SHA1,SHA256,.Net Framework)

 

        public static string GetMd5Hash(string input)
        {
            using (MD5 md5Hash = MD5.Create())
            {
                // Convert the input string to a byte array and compute the hash.
                byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

                // Create a new Stringbuilder to collect the bytes
                // and create a string.
                StringBuilder sBuilder = new StringBuilder();

                // Loop through each byte of the hashed data 
                // and format each one as a hexadecimal string.
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }

                // Return the hexadecimal string.
                return sBuilder.ToString();
            }
        }

  這是一段 MSDN 官方的 MD5 示例,例子很簡單且很容易理解。但是,這個例子也有很多的問題,首先上例至少建立了 3 個臨時快取區!且每次執行 GetMd5Hash 都會建立一個 MD5 例項,並在方法執行完成後釋放它。這些都造成了很大的系統資源浪費和增加了 GC 的壓力。

  鑑於官方給的 Demo 並不優秀,且網上也沒有給出很好使用方式,這裡我就拿出我多年使用的 MD5 開啟方式,這個方法同時支援 SHA1,SHA256 等,即支援 System.Security.Cryptography 名稱空間下的 HashAlgorithm(雜湊演算法) 實現。也同時支援 .Net Framework 2.0 之後的所有 .Net 平臺。 

  我不想看你的鬼廢話,直接給我上最終程式碼》》》

  先說明,這個文章是基於 System.Security.Cryptography 名稱空間的實現,不是自己寫一個 MD5 演算法哦。

  現在我們開始,首先我們先定義一個輔助類:

using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;

static class THashAlgorithmInstances<THashAlgorithm> where THashAlgorithm : HashAlgorithm
{
    /// <summary>
    /// 執行緒靜態變數。
    /// 即:這個變數在每個執行緒中都是唯一的。
    /// 再結合泛型類實現:該變數在不同泛型或不同的執行緒下的值都是不一樣的。
    /// 這樣做的目的是為了避開多執行緒問題。
/// 關於垃圾回收:當 .NET 執行緒被釋放時,程式中的所有執行緒靜態變數都會被回收,GC 回收時同時將釋放資源,所以不必擔心釋放問題,GC 會幫助我們的。
    /// 這裡描述的 .NET 執行緒釋放不是指 .NET 執行緒回收至執行緒池。很多時候 .NET 的執行緒在程式關閉之前都不會真正釋放,而是線上程池中繼續駐留。
    /// 執行緒唯一真的能避免多執行緒問題嗎?答:多個執行緒所用儲存空間都不一樣,那麼髒值就不可能存在,如果這都能出現多執行緒問題,我直播吃....豬紅(本人極其厭惡吃豬紅