using System; using System.IO; using System.Security.Cryptography; using System.Text; public class EncryptMD5 { /// /// 获取字符串MD5值 /// /// /// 编码方式 utf8 /// true 大写;false 小写 /// public static string Encrypt(string sText, Encoding encoding, bool uppercase = false) { byte[] buffer = encoding.GetBytes(sText); string s = Encrypt(buffer); if (!uppercase) s = s.ToLower(); return s; } /// /// 获取字符串MD5值 /// /// /// public static string Encrypt(byte[] buffer) { //使用MD5这个抽象类的Creat()方法创建一个虚拟的MD5类的对象。 using (MD5 md5 = MD5.Create()) { //使用MD5实例的ComputerHash()方法处理字节数组。 byte[] bufferNew = md5.ComputeHash(buffer); string s = BitConverter.ToString(bufferNew, 0, bufferNew.Length); return s.Replace("-", ""); } } /// /// 获取流MD5值 /// /// /// public static string Encrypt(Stream inputStream) { using (MD5 mi = MD5.Create()) { //开始加密 byte[] bufferNew = mi.ComputeHash(inputStream); string s = BitConverter.ToString(bufferNew, 0, bufferNew.Length); return s.Replace("-", ""); } } /// /// 获取文件MD5值 /// /// /// public static string EncryptFile(string filename) { using (FileStream fs = new FileStream(filename, FileMode.Open)) { return Encrypt(fs); } } }