C#实现计算给定报文的HASH值,其中包括SHA1、SHA256、MD5等函数的使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
HashAlgorithm hash = HashAlgorithm.Create();
Console.WriteLine("Enter a File Name:");
string fileName = Console.ReadLine();
FileStream fs = new FileStream(fileName, FileMode.Open);
byte[] hashBytes = hash.ComputeHash(fs);
fs.Close();
Console.Write("Hash:"+BitConverter.ToString(hashBytes));
Console.ReadLine();
}
}
}
注:该句HashAlgorithm hash=HashAlgorithm.Create();是实现是SHA1类的实例,生成的是160位的散列码。
如果将上句改为:HashAlgorithm hash=HashAlgorithm.Create("SHA256");
则是生成256位的散列码。
或者:SHA256Managed hash=new SHA256Managed(); 生成256位的散列码。
将上例中的语句HashAlgorithm hash=HashAlgorithm.Create();
改为:MD5 md5 = new MD5CryptoServiceProvider();
语句byte[] hashBytes=hash.ComputeHash(fs);改为: byte[] hashBytes = md5.ComputeHash(fs);
则是hash函数MD5的哈希值(128位)。
输出结果:
为便于应用和操作,可以将以上实验内容改为 Windows界面输入和输出
private void button1_Click(object sender, EventArgs e)
{
//textBox1为输入密码的文本框
byte[] result = Encoding.Default.GetBytes(this.textBox1.Text.Trim());
HashAlgorithm hash = HashAlgorithm.Create();
byte[] output = hash.ComputeHash(result);
//textBox2为输出加密文本的文本框
this.textBox2.Text = BitConverter.ToString(output);
}
将上例中的语句:
HashAlgorithm hash = HashAlgorithm.Create();
byte[] output = hash.ComputeHash(result);
改为:
MD5 md5 = new MD5CryptoServiceProvider();
byte[] output = md5.ComputeHash(result);
则是应用MD5,计算报文的HASH值。
输出结果: