MD5加密操作:MD5加密算法原理MD5的全称是Message-Digest Algorithm 5(信息-摘要算法),它的作用是让大容量信息在用数字签名软件签署私人密匙前被"压缩"成一种保密的格式(就是把一个任意长度的字节串变换成一定长的大整数)。
//导入命名空间
using System.Security.Cryptography;
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 = ; i < cryptBytes.Length; i++)
{
ctyptStr += cryptBytes[i].ToString("X2");
}
return ctyptStr;
}
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=;i<md5data.Length-;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 = ; i < cryptBytes.Length; i++)
{
cryptStr += cryptBytes[i].ToString("X2");
}
return cryptStr;
}
我们也可以用Foreach进行循环
public string GetMD5String(string code)
{
//在登录的时候调用的
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
//将字符串 转换 byte[]
byte[] bytes = Encoding.Default.GetBytes(code);
byte[] md5Byte = md5.ComputeHash(bytes);
//byte[] 转换 字符串
StringBuilder sb = new StringBuilder();
foreach (byte item in md5Byte)
{
sb.Append(item.ToString("X2"));
}
return sb.ToString(); }
我可以在主窗体调用
private void btnexit_Click(object sender, EventArgs e)
{
Md5加密 md = new Md5加密();
string num= md.GetMD5String("");
MessageBox.Show(num);
}