1. 程式人生 > >C#實現計算給定報文的HASH值,其中包括SHA1、SHA256、MD5等函式的使用

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值。

輸出結果: