C#实现MD5加密
MD5简介:
Message Digest Algorithm MD5(中文名为消息摘要算法第五版)为计算机安全领域广泛使用的一种散列函数,用以提供消息的完整性保护。
MD5最广泛被用于各种软件的密码认证和钥匙识别上,MD5具有很好的安全性(因为它具有不可逆的特征,加过密的密文经过解密后和加密前的东东相同的可能性极小)。
MD5 算法的哈希值大小为 128 位。
MD5 相关类:
System.Security.Cryptography.MD5
System.Security.Cryptography.MD5CryptoServiceProvider()
System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strSource, "MD5")
三种简单实现:
protected void btn01_Click(object sender, EventArgs e)
{
byte[] result = System.Text.Encoding.Default.GetBytes("123456");
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] output = md5.ComputeHash(result);
//转换成字符串,32位
this.lbl01.Text = BitConverter.ToString(output).Replace("-", "");
}
protected void btn02_Click(object sender, EventArgs e)
{
lbl02.Text = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("123456", "MD5");
}
protected void btn03_Click(object sender, EventArgs e)
{
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
byte[] result = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes("123456"));
for (int i = 0; i < result.Length; i++)
{
//16进制转换
sb.Append(result[i].ToString("X"));
}
lbl03.Text = sb.ToString();
}