C#语言程序设计之两种MD5加密方法的实现

MD5信息摘要算法(英语:MD5 Message-Digest Algorithm),一种被广泛使用的密码散列函数。MD5算法的原理可简要的叙述为:MD5码以512位分组来处理输入的信息,且每一分组又被划分为16个32位子分组,经过了一系列的处理后,算法的输出由四个32位分组组成,将这四个32位分组级联后将生成一个128位散列值。

public static string GetMd5Hash(string input)
{
    using (MD5 md5Hash = MD5.Create())
    {
		// Convert the input string to a byte array and compute the hash.
		byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

		// Create a new Stringbuilder to collect the bytes
		// and create a string.
		StringBuilder sb = new StringBuilder();

		// Loop through each byte of the hashed data
		// and format each one as a hexadecimal string.
		for (int i = 0; i < data.Length; i++)
		{
			sb.Append(data[i].ToString("x2"));
		}

		// Return the hexadecimal string.
		return sb.ToString();
	}
}

public static string GetMd5Hash(Stream stream)
{
	using (MD5 md5Hash = MD5.Create())
	{
		// Compute the hash.
		byte[] data = md5Hash.ComputeHash(stream);

		// Create a new Stringbuilder to collect the bytes
		// and create a string.
		StringBuilder sb = new StringBuilder();

		// Loop through each byte of the hashed data
		// and format each one as a hexadecimal string.
		for (int i = 0; i < data.Length; i++)
		{
			sb.Append(data[i].ToString("x2"));
		}

		// Return the hexadecimal string.
		return sb.ToString();
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *