计算字符串和文件MD5值的小例子
时间:2020-12-26 11:21:09|栏目:.NET代码|点击: 次
复制代码 代码如下:
//计算字符串的MD5值
public string GetMD5(string sDataIn)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] bytValue, bytHash;
bytValue = System.Text.Encoding.UTF8.GetBytes(sDataIn);
bytHash = md5.ComputeHash(bytValue);
md5.Clear();
string sTemp = "";
for (int i = 0; i < bytHash.Length; i++)
{
sTemp += bytHash[i].ToString("X").PadLeft(2, '0');
}
return sTemp.ToLower();
}
//计算文件的MD5值
public string MD5Value(String filepath)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] md5ch;
using (FileStream fs = File.OpenRead(filepath))
{
md5ch = md5.ComputeHash(fs);
}
md5.Clear();
string strMd5 = "";
for (int i = 0; i < md5ch.Length - 1; i++)
{
strMd5 += md5ch[i].ToString("x").PadLeft(2, '0');
}
return strMd5;
}