MD5计算,一个扩展类,哪里都能用
作者:互联网
最近有同学问到如何计算一个字节数组的MD5值,现在分享一个扩展类,有了它,MD5计算再也不用其他了。
先看示例:
string s = "hello world"; var s_md5= s.ToMD5(); string f = @"C:\Windows\explorer.exe"; var f_md5 = f.ToMD5File(); byte[] b = System.IO.File.ReadAllBytes(f); var b_md5 = b.ToMD5();
使用起来是不是很简单?下面是完整代码:
using System.IO; using System.Security.Cryptography; using System.Text; namespace System { /// <summary> /// MD5扩展类 /// </summary> public static class MD5Extensions { /// <summary> /// 获取字符串的MD5值 /// </summary> /// <param name="text">字符串</param> /// <param name="encode">编码,缺省UTF8</param> /// <returns>MD5 值</returns> public static string ToMD5(this string text, Encoding encode = null) { if (encode == null) encode = Encoding.UTF8; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] encryptedBytes = md5.ComputeHash(encode.GetBytes(text)); return GetHashMD5(encryptedBytes); } /// <summary> /// 获取文件的MD5值 /// </summary> /// <param name="path"></param> /// <returns></returns> public static string ToMD5File(this string path) { try { using (Stream file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { return file.ToMD5(); } } catch (Exception e) { return e.ToString(); } } /// <summary> /// 获取流的MD5值 /// </summary> /// <param name="s">流</param> /// <returns>MD5值</returns> public static string ToMD5(this Stream stream) { byte[] hashbyte; using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) { hashbyte = md5.ComputeHash(stream); } return GetHashMD5(hashbyte); } /// <summary> /// 获取字节数组的MD5值 /// </summary> /// <param name="buffer">数组</param> /// <returns>MD5值</returns> public static string ToMD5(this byte[] buffer) { byte[] hashbyte; using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) { hashbyte = md5.ComputeHash(buffer, 0, buffer.Length); } return GetHashMD5(hashbyte); } /// <summary> /// Hash值转换MD5值格式 /// </summary> /// <param name="hashbyte">Hash值</param> /// <returns>MD5值</returns> private static string GetHashMD5(byte[] hashbyte) { string result = BitConverter.ToString(hashbyte); return result.Replace("-", ""); } } }
如果你比较懒,那么就nuget搜索MD5Extensions插入到项目中吧
标签:return,string,扩展,哪里,hashbyte,using,MD5,md5 来源: https://www.cnblogs.com/raoyutian/p/15840962.html