/ C#

C#计算字符串、文件MD5

首先引入库

using System.Security.Cryptography; using System.IO;

1.计算字符串MD5

string GetMD5(string str) { string str = ""; byte[] data = Encoding.GetEncoding("utf-8").GetBytes(str); MD5 md5 = new MD5CryptoServiceProvider(); byte[] bytes = md5.ComputeHash(data); for (int i = 0; i < bytes.Length; i++) { str += bytes[i].ToString("x2"); } return str; }

2.计算文件MD5

string GetMD5(string path) { FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hash_byte = md5.ComputeHash(file); string str = System.BitConverter.ToString(hash_byte); str = str.Replace("-", ""); return str; }

C#计算字符串、文件MD5
Share this