C# 计算文件的 Hash 值

50 篇文章 1 订阅
8 篇文章 0 订阅

http://blog.sina.com.cn/s/blog_752ca76a0100qcrr.html


/// <summary>
 

/// 提供用于计算指定文件哈希值的方法
  ///<example>例如计算文件的MD5值:
  /// <code>
  ///   StringhashMd5=HashHelper.ComputeMD5("MyFile.txt");
  /// </code>
  /// </example>
  ///<example>例如计算文件的CRC32值:
  /// <code>
  ///   String hashCrc32 =HashHelper.ComputeCRC32("MyFile.txt");
  /// </code>
  /// </example>
  ///<example>例如计算文件的SHA1值:
  /// <code>
  ///   String hashSha1=HashHelper.ComputeSHA1("MyFile.txt");
  /// </code>
  /// </example>
  /// </summary>
  public sealed class HashHelper
  {
      ///<summary>
      ///  计算指定文件的MD5值
      ///</summary>
      /// <paramname="fileName">指定文件的完全限定名称</param>
      ///<returns>返回值的字符串形式</returns>
      public static StringComputeMD5(String fileName)
      {
          StringhashMD5 = String.Empty;

         //检查文件是否存在,如果文件存在则进行计算,否则返回空值
          if(System.IO.File.Exists(fileName))
         {
             using (System.IO.FileStream fs = new System.IO.FileStream(fileName,System.IO.FileMode.Open, System.IO.FileAccess.Read))
             {
                 //计算文件的MD5值
                 System.Security.Cryptography.MD5calculator=System.Security.Cryptography.MD5.Create();
                 Byte[] buffer = calculator.ComputeHash(fs);
                 calculator.Clear();
                 //将字节数组转换成十六进制的字符串形式
                 StringBuilder stringBuilder = new StringBuilder();
                 for (int i = 0; i < buffer.Length; i++)
                 {
                     stringBuilder.Append(buffer[i].ToString("x2"));
                 }
                hashMD5= stringBuilder.ToString();
             }//关闭文件流

         }//结束计算

          returnhashMD5;
      }//ComputeMD5

      ///<summary>
      ///  计算指定文件的CRC32值
      ///</summary>
      /// <paramname="fileName">指定文件的完全限定名称</param>
      ///<returns>返回值的字符串形式</returns>
      public static StringComputeCRC32(String fileName)
      {
          StringhashCRC32 = String.Empty;

         //检查文件是否存在,如果文件存在则进行计算,否则返回空值
          if(System.IO.File.Exists(fileName))
         {
             using (System.IO.FileStream fs = new System.IO.FileStream(fileName,System.IO.FileMode.Open, System.IO.FileAccess.Read))
             {
             //计算文件的CSC32值
             Crc32 calculator = new Crc32();
             Byte[] buffer = calculator.ComputeHash(fs);
             calculator.Clear();
             //将字节数组转换成十六进制的字符串形式
             StringBuilder stringBuilder = new StringBuilder();
             for (int i = 0; i < buffer.Length; i++)
             {
                 stringBuilder.Append(buffer[i].ToString("x2"));
             }

             hashCRC32 = stringBuilder.ToString();
             }//关闭文件流
         }
          returnhashCRC32;
      }//ComputeCRC32

      ///<summary>
      ///  计算指定文件的SHA1值
      ///</summary>
      /// <paramname="fileName">指定文件的完全限定名称</param>
      ///<returns>返回值的字符串形式</returns>
      public static StringComputeSHA1(String fileName)
      {
          StringhashSHA1 = String.Empty;

         //检查文件是否存在,如果文件存在则进行计算,否则返回空值
          if(System.IO.File.Exists(fileName))
         {
             using (System.IO.FileStream fs = new System.IO.FileStream(fileName,System.IO.FileMode.Open, System.IO.FileAccess.Read))
             {
                 //计算文件的SHA1值
                 System.Security.Cryptography.SHA1 calculator =System.Security.Cryptography.SHA1.Create();
                 Byte[] buffer = calculator.ComputeHash(fs);
                 calculator.Clear();
                 //将字节数组转换成十六进制的字符串形式
                 StringBuilder stringBuilder = new StringBuilder();
                 for (int i = 0; i < buffer.Length; i++)
                 {
                     stringBuilder.Append(buffer[i].ToString("x2"));
                 }

                 hashSHA1 = stringBuilder.ToString();

             }//关闭文件流
         }

          returnhashSHA1;
      }//ComputeSHA1

  }//end class:HashHelper

   /// <summary>
   /// 提供 CRC32 算法的实现
   /// </summary>
   public class Crc32 :System.Security.Cryptography.HashAlgorithm
   {
       public const UInt32DefaultPolynomial = 0xedb88320;
       public const UInt32DefaultSeed = 0xffffffff;
       private UInt32 hash;
       private UInt32 seed;
       private UInt32[] table;
       private static UInt32[]defaultTable;
       public Crc32()
       {
           table= InitializeTable(DefaultPolynomial);
           seed =DefaultSeed;
          Initialize();
       }
       public Crc32(UInt32polynomial, UInt32 seed)
       {
           table= InitializeTable(polynomial);
          this.seed = seed;
          Initialize();
       }
       public override voidInitialize()
       {
           hash =seed;
       }
       protected override voidHashCore(byte[] buffer, int start, int length)
       {
           hash =CalculateHash(table, hash, buffer, start, length);
       }
       protected override byte[]HashFinal()
       {
           byte[]hashBuffer = UInt32ToBigEndianBytes(~hash);
          this.HashValue = hashBuffer;
           returnhashBuffer;
       }
       public static UInt32Compute(byte[] buffer)
       {
           return~CalculateHash(InitializeTable(DefaultPolynomial), DefaultSeed,buffer, 0, buffer.Length);
       }
       public static UInt32Compute(UInt32 seed, byte[] buffer)
       {
           return~CalculateHash(InitializeTable(DefaultPolynomial), seed, buffer, 0,buffer.Length);
       }
       public static UInt32Compute(UInt32 polynomial, UInt32 seed, byte[] buffer)
       {
           return~CalculateHash(InitializeTable(polynomial), seed, buffer, 0,buffer.Length);
       }
       private static UInt32[]InitializeTable(UInt32 polynomial)
       {
           if(polynomial == DefaultPolynomial &&defaultTable != null)
          {
              return defaultTable;
          }
          UInt32[] createTable = new UInt32[256];
           for(int i = 0; i < 256; i++)
          {
              UInt32 entry = (UInt32)i;
              for (int j = 0; j < 8; j++)
              {
                  if ((entry & 1) == 1)
                      entry = (entry >> 1) ^polynomial;
                  else
                      entry = entry >> 1;
              }
              createTable[i] = entry;
          }
           if(polynomial == DefaultPolynomial)
          {
              defaultTable = createTable;
          }
           returncreateTable;
       }
       private static UInt32CalculateHash(UInt32[] table, UInt32 seed, byte[] buffer, intstart, int size)
       {
           UInt32crc = seed;
           for(int i = start; i < size; i++)
          {
              unchecked
              {
                  crc = (crc >> 8) ^ table[buffer[i] ^crc & 0xff];
              }
          }
           returncrc;
       }
       private byte[]UInt32ToBigEndianBytes(UInt32 x)
       {
           returnnew byte[] { (byte)((x>> 24) & 0xff),(byte)((x >> 16) &0xff), (byte)((x >> 8)& 0xff), (byte)(x & 0xff)};
       }
   }//end class:Crc32


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值