MD5加密操作
//导入命名空间
using System.Security.Cryptography;
MD5加密字符串
方式一:
public string GetMD5String(string pwd)
{
MD5CryptoServiceProvider md5=new MD5CryptoServiceProvide();
byte[] data=System.Text.Encoding.ASCII.GetBytes(pwd);
byte[] md5data=md5.ComputeHash(data);
StringBuilder builder=new StringBUilder();
for(int i=0;i<md5data.Length-1;i++)
{
builder.Append(md5data[i].ToString("X2"));
}
return builder;
}
方式二:
public string GetMd5(string msg)
{
string cryptStr = "";
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] bytes = Encoding.UTF8.GetBytes(msg);
byte[] cryptBytes = md5.ComputeHash(bytes);
for (int i = 0; i < cryptBytes.Length; i++)
{
cryptStr += cryptBytes[i].ToString("X2");
}
return cryptStr;
}
MD5加密文件
string GetFileMd5(string path)
{
string ctyptStr = "";
byte[] cryptBytes;
using (FileStream fs = new FileStream(path,FileMode.Open))
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
cryptBytes = md5.ComputeHash(fs);
}
for (int i = 0; i < cryptBytes.Length; i++)
{
ctyptStr += cryptBytes[i].ToString("X2");
}
return ctyptStr;
}