.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 的线程在程序关闭之前都不会真正释放,而是在线程池中继续驻留。
/// 线程唯一真的能避免多线程问题吗?答:多个线程所以用存储空间都不一样,那么脏值就不可能存在,如果这都能出现多线程问题,我直播吃....猪红(本人及其厌恶吃猪红