MD5类示例
下面的代码示例计算字符串 MD5 哈希值,并将哈希返回为32字符的十六进制格式字符串。 此代码示例创建的哈希字符串与创建32字符的十六进制格式哈希字符串的任何平台上的任何 MD5 哈希函数兼容。
1. 引用Cryptography
using System.Security.Cryptography;
2. 计算字符串的哈希值的方法
static string GetMd5Hash(MD5 md5Hash, string input)
{
// 将输入字符串转换为字节数组并计算哈希。
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// 创建一个新的Stringbuilder来收集字节
//并创建一个字符串。
StringBuilder sBuilder = new StringBuilder();
//循环遍历散列数据的每个字节
//并将每个格式设置为十六进制字符串。
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
//返回十六进制字符串。
return sBuilder.ToString();
}
3. 针对字符串验证哈希值方法
static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
{
// 散列输入。
string hashOfInput = GetMd5Hash(md5Hash, input);
// 创建一个StringComparer,比较哈希值。
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
4. 计算具体字符串的哈希值
static void StringToHash()
{
string source = "Hello World!";
MD5 md5Hash = MD5.Create();
string hash = GetMd5Hash(md5Hash, source);
Console.WriteLine(source + " 的MD5哈希值是: " + hash + ".");
}
5. 比较具体字符串和哈希值
static void StringEqualsHash()
{
string source = "Hello World!";
string hash = "ed076287532e86365e841e92bfc50d8c";
MD5 md5Hash = MD5.Create();
if (VerifyMd5Hash(md5Hash, source, hash))
{
Console.WriteLine("哈希值是相同的。");
}
else
{
Console.WriteLine("哈希值是不相同的。");
}
}
具体代码
using System;
using System.Security.Cryptography;
using System.Text;
namespace MD5Sample
{
class Program
{
static void Main(string[] args)
{
StringToHash();
StringEqualsHash();
}
static string GetMd5Hash(MD5 md5Hash, string input)
{
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();
}
static bool VerifyMd5Hash(MD5 md5Hash, string input, string hash)
{
string hashOfInput = GetMd5Hash(md5Hash, input);
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
static void StringToHash()
{
string source = "Hello World!";
MD5 md5Hash = MD5.Create();
string hash = GetMd5Hash(md5Hash, source);
Console.WriteLine(source + " 的MD5哈希值是: " + hash + ".");
}
static void StringEqualsHash()
{
string source = "Hello World!";
string hash = "ed076287532e86365e841e92bfc50d8c";
MD5 md5Hash = MD5.Create();
if (VerifyMd5Hash(md5Hash, source, hash))
{
Console.WriteLine("哈希值是相同的。");
}
else
{
Console.WriteLine("哈希值是不相同的。");
}
}
}
}