MD5(Message Digest Algorithm 5)是一种常用的哈希算法,用于将任意长度的数据转换为固定长度的哈希值。MD5加密在以下场景下使用:
在C#中,可以使用System.Security.Cryptography命名空间下的MD5类来实现MD5加密。以下是使用MD5类的属性和方法:
属性:
方法:
C#private void btnHash_Click(object sender, EventArgs e)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] bytes = Encoding.Default.GetBytes(txt1.Text);//将要加密的字符串转换为字节数组
byte[] encryptdata = md5.ComputeHash(bytes);//将字符串加密后也转换为字符数组
txt2.Text= Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为加密字符串
}
C#private void btnHash_Click(object sender, EventArgs e)
{
string ret = GetMD5Hash(txt1.Text);
txt2.Text= ret;
}
public string GetMD5Hash(string input)
{
using (MD5 md5Hash = MD5.Create())
{
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
builder.Append(data[i].ToString("x2"));
}
return builder.ToString();
}
}
C#public bool VerifyMD5Hash(string input, string hash)
{
string hashOfInput = GetMD5Hash(input);
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
return comparer.Compare(hashOfInput, hash) == 0;
}
C#bool ret = VerifyMD5Hash("123456", "e10adc3949ba59abbe56e057f20f883e");
注意,MD5算法目前已经不再被认为是安全的加密算法,因为其易受到碰撞攻击。
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!