Exemple #1
0
        /// <summary>
        /// 获取一个文件的Hash值
        /// </summary>
        /// <param name="filePath">要计算Hash值的文件</param>
        /// <param name="hashType">HashType[默认值:SHA1Managed]</param>
        /// <returns>所得Hash值</returns>
        public static string GetFileHash(string filePath, MD5HashType hashType = MD5HashType.SHA1Managed)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException(string.Empty, filePath);
            }

            try
            {
                using (HashAlgorithm entry = HashEx.CreateHashEntry(hashType))
                {
                    using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        //计算指定Stream 对象的哈希值
                        var arrbytHashValue = entry.ComputeHash(fileStream);

                        //由以连字符分隔的十六进制对构成的String,其中每一对表示value 中对应的元素;例如“F-2C-4A”
                        var md5HashValue = BitConverter.ToString(arrbytHashValue);

                        //替换-为string.Empty(去年-)
                        md5HashValue = md5HashValue.Replace("-", string.Empty);
                        return(md5HashValue);
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw new Exception("获取文件的Hash值失败", ex);
            }
        }
Exemple #2
0
        /// <summary>
        /// 获取二进制数据的Hash值
        /// </summary>
        /// <param name="data">要计算Hash值0的二进制数据</param>
        /// <param name="offset">字节数据中的偏移量,从该位置起使用数据</param>
        /// <param name="count">数组中用途数据的字节数</param>
        /// <param name="hashType">HashType[默认值:SHA1Managed]</param>
        /// <returns>所得Hash值</returns>
        public static string GetHash(byte[] data, int offset, int count, MD5HashType hashType = MD5HashType.SHA1Managed)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

            using (HashAlgorithm entry = HashEx.CreateHashEntry(hashType))
            {
                //计算指定Stream 对象的哈希值
                var arrbytHashValue = entry.ComputeHash(data, offset, count);

                //由以连字符分隔的十六进制对构成的String,其中每一对表示value 中对应的元素;例如“F-2C-4A”
                var md5HashValue = BitConverter.ToString(arrbytHashValue);

                //替换-为string.Empty(去年-)
                md5HashValue = md5HashValue.Replace("-", string.Empty);
                return(md5HashValue);
            }
        }