荣耀之链论坛

 找回密码
 立即注册
搜索
查看: 562|回复: 0

计算文件MD5

[复制链接]

1374

主题

2504

帖子

1万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
10697
发表于 2023-6-25 21:20 | 显示全部楼层 |阅读模式
https://www.cnblogs.com/lishouxiangjs/p/3414170.html


  1. /// <summary>
  2.   /// 提供用于计算指定文件哈希值的方法
  3.   /// <example>例如计算文件的MD5值:
  4.   /// <code>
  5.   ///   String hashMd5=HashHelper.ComputeMD5("MyFile.txt");
  6.   /// </code>
  7.   /// </example>
  8.   /// <example>例如计算文件的CRC32值:
  9.   /// <code>
  10.   ///   String hashCrc32 = HashHelper.ComputeCRC32("MyFile.txt");
  11.   /// </code>
  12.   /// </example>
  13.   /// <example>例如计算文件的SHA1值:
  14.   /// <code>
  15.   ///   String hashSha1 =HashHelper.ComputeSHA1("MyFile.txt");
  16.   /// </code>
  17.   /// </example>
  18.   /// </summary>
  19.   public sealed class HashHelper
  20.   {
  21.       /// <summary>
  22.       ///  计算指定文件的MD5值
  23.       /// </summary>
  24.       /// <param name="fileName">指定文件的完全限定名称</param>
  25.       /// <returns>返回值的字符串形式</returns>
  26.       public static String ComputeMD5(String fileName)
  27.       {
  28.           String hashMD5 = String.Empty;
  29.           //检查文件是否存在,如果文件存在则进行计算,否则返回空值
  30.           if (System.IO.File.Exists(fileName))
  31.           {
  32.               using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
  33.               {
  34.                   //计算文件的MD5值
  35.                   System.Security.Cryptography.MD5 calculator=System.Security.Cryptography.MD5.Create();
  36.                   Byte[] buffer = calculator.ComputeHash(fs);
  37.                   calculator.Clear();
  38.                   //将字节数组转换成十六进制的字符串形式
  39.                   StringBuilder stringBuilder = new StringBuilder();
  40.                   for (int i = 0; i < buffer.Length; i++)
  41.                   {
  42.                       stringBuilder.Append(buffer[i].ToString("x2"));
  43.                   }
  44.                  hashMD5= stringBuilder.ToString();
  45.               }//关闭文件流
  46.           }//结束计算
  47.           return hashMD5;
  48.       }//ComputeMD5
  49.       /// <summary>
  50.       ///  计算指定文件的CRC32值
  51.       /// </summary>
  52.       /// <param name="fileName">指定文件的完全限定名称</param>
  53.       /// <returns>返回值的字符串形式</returns>
  54.       public static String ComputeCRC32(String fileName)
  55.       {
  56.           String hashCRC32 = String.Empty;
  57.           //检查文件是否存在,如果文件存在则进行计算,否则返回空值
  58.           if (System.IO.File.Exists(fileName))
  59.           {
  60.               using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
  61.               {
  62.               //计算文件的CSC32值
  63.               Crc32 calculator = new Crc32();
  64.               Byte[] buffer = calculator.ComputeHash(fs);
  65.               calculator.Clear();
  66.               //将字节数组转换成十六进制的字符串形式
  67.               StringBuilder stringBuilder = new StringBuilder();
  68.               for (int i = 0; i < buffer.Length; i++)
  69.               {
  70.                   stringBuilder.Append(buffer[i].ToString("x2"));
  71.               }
  72.               hashCRC32 = stringBuilder.ToString();
  73.               }//关闭文件流
  74.           }
  75.           return hashCRC32;
  76.       }//ComputeCRC32
  77.       /// <summary>
  78.       ///  计算指定文件的SHA1值
  79.       /// </summary>
  80.       /// <param name="fileName">指定文件的完全限定名称</param>
  81.       /// <returns>返回值的字符串形式</returns>
  82.       public static String ComputeSHA1(String fileName)
  83.       {
  84.           String hashSHA1 = String.Empty;
  85.           //检查文件是否存在,如果文件存在则进行计算,否则返回空值
  86.           if (System.IO.File.Exists(fileName))
  87.           {
  88.               using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
  89.               {
  90.                   //计算文件的SHA1值
  91.                   System.Security.Cryptography.SHA1 calculator = System.Security.Cryptography.SHA1.Create();
  92.                   Byte[] buffer = calculator.ComputeHash(fs);
  93.                   calculator.Clear();
  94.                   //将字节数组转换成十六进制的字符串形式
  95.                   StringBuilder stringBuilder = new StringBuilder();
  96.                   for (int i = 0; i < buffer.Length; i++)
  97.                   {
  98.                       stringBuilder.Append(buffer[i].ToString("x2"));
  99.                   }
  100.                   hashSHA1 = stringBuilder.ToString();
  101.               }//关闭文件流
  102.           }
  103.           return hashSHA1;
  104.       }//ComputeSHA1
  105.   }//end class: HashHelper
  106.    /// <summary>
  107.    /// 提供 CRC32 算法的实现
  108.    /// </summary>
  109.    public class Crc32 : System.Security.Cryptography.HashAlgorithm
  110.    {
  111.        public const UInt32 DefaultPolynomial = 0xedb88320;
  112.        public const UInt32 DefaultSeed = 0xffffffff;
  113.        private UInt32 hash;
  114.        private UInt32 seed;
  115.        private UInt32[] table;
  116.        private static UInt32[] defaultTable;
  117.        public Crc32()
  118.        {
  119.            table = InitializeTable(DefaultPolynomial);
  120.            seed = DefaultSeed;
  121.            Initialize();
  122.        }
  123.        public Crc32(UInt32 polynomial, UInt32 seed)
  124.        {
  125.            table = InitializeTable(polynomial);
  126.            this.seed = seed;
  127.            Initialize();
  128.        }
  129.        public override void Initialize()
  130.        {
  131.            hash = seed;
  132.        }
  133.        protected override void HashCore(byte[] buffer, int start, int length)
  134.        {
  135.            hash = CalculateHash(table, hash, buffer, start, length);
  136.        }
  137.        protected override byte[] HashFinal()
  138.        {
  139.            byte[] hashBuffer = UInt32ToBigEndianBytes(~hash);
  140.            this.HashValue = hashBuffer;
  141.            return hashBuffer;
  142.        }
  143.        public static UInt32 Compute(byte[] buffer)
  144.        {
  145.            return ~CalculateHash(InitializeTable(DefaultPolynomial), DefaultSeed, buffer, 0, buffer.Length);
  146.        }
  147.        public static UInt32 Compute(UInt32 seed, byte[] buffer)
  148.        {
  149.            return ~CalculateHash(InitializeTable(DefaultPolynomial), seed, buffer, 0, buffer.Length);
  150.        }
  151.        public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer)
  152.        {
  153.            return ~CalculateHash(InitializeTable(polynomial), seed, buffer, 0, buffer.Length);
  154.        }
  155.        private static UInt32[] InitializeTable(UInt32 polynomial)
  156.        {
  157.            if (polynomial == DefaultPolynomial && defaultTable != null)
  158.            {
  159.                return defaultTable;
  160.            }
  161.            UInt32[] createTable = new UInt32[256];
  162.            for (int i = 0; i < 256; i++)
  163.            {
  164.                UInt32 entry = (UInt32)i;
  165.                for (int j = 0; j < 8; j++)
  166.                {
  167.                    if ((entry & 1) == 1)
  168.                        entry = (entry >> 1) ^ polynomial;
  169.                    else
  170.                        entry = entry >> 1;
  171.                }
  172.                createTable[i] = entry;
  173.            }
  174.            if (polynomial == DefaultPolynomial)
  175.            {
  176.                defaultTable = createTable;
  177.            }
  178.            return createTable;
  179.        }
  180.        private static UInt32 CalculateHash(UInt32[] table, UInt32 seed, byte[] buffer, int start, int size)
  181.        {
  182.            UInt32 crc = seed;
  183.            for (int i = start; i < size; i++)
  184.            {
  185.                unchecked
  186.                {
  187.                    crc = (crc >> 8) ^ table[buffer[i] ^ crc & 0xff];
  188.                }
  189.            }
  190.            return crc;
  191.        }
  192.        private byte[] UInt32ToBigEndianBytes(UInt32 x)
  193.        {
  194.            return new byte[] { (byte)((x >> 24) & 0xff), (byte)((x >> 16) & 0xff), (byte)((x >> 8) & 0xff), (byte)(x & 0xff) };
  195.        }
  196.    }//end class: Crc32
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

荣耀之链

GMT+8, 2025-9-10 22:52 , Processed in 0.013005 second(s), 20 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表