我应该如何在 C# 中计算文件哈希(md5 和 SHA1)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13569406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How should I compute files hash(md5 & SHA1) in C#
提问by n1kita
This is my first C# project and I'm almost newbie. I use openfiledialoge for selecting file and get the filepath by GetFullPath method and store it in a variable called for example fpath. I need to calculate the hash of the file that its path is stored in fpath variable.I think it can be done via GetHashCode. Can anybody give me a snippet or a little guide?
这是我的第一个 C# 项目,我几乎是新手。我使用 openfiledialoge 来选择文件并通过 GetFullPath 方法获取文件路径并将其存储在一个名为 fpath 的变量中。我需要计算其路径存储在 fpath 变量中的文件的哈希值。我认为它可以通过 GetHashCode 来完成。谁能给我一个片段或一个小指南?
回答by Saddam Abu Ghaida
using (FileStream stream = File.OpenRead(file))
{
SHA256Managed sha = new SHA256Managed();
byte[] hash = sha.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", String.Empty);
}
回答by Brian
Here's some code I used to respond to another questionon SO
/// <summary>
/// Gets a hash of the file using SHA1.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static string GetSHA1Hash(string filePath)
{
using (var sha1 = new SHA1CryptoServiceProvider())
return GetHash(filePath, sha1);
}
/// <summary>
/// Gets a hash of the file using SHA1.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static string GetSHA1Hash(Stream s)
{
using (var sha1 = new SHA1CryptoServiceProvider())
return GetHash(s, sha1);
}
/// <summary>
/// Gets a hash of the file using MD5.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static string GetMD5Hash(string filePath)
{
using (var md5 = new MD5CryptoServiceProvider())
return GetHash(filePath, md5);
}
/// <summary>
/// Gets a hash of the file using MD5.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static string GetMD5Hash(Stream s)
{
using (var md5 = new MD5CryptoServiceProvider())
return GetHash(s, md5);
}
private static string GetHash(string filePath, HashAlgorithm hasher)
{
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
return GetHash(fs, hasher);
}
private static string GetHash(Stream s, HashAlgorithm hasher)
{
var hash = hasher.ComputeHash(s);
var hashStr = Convert.ToBase64String(hash);
return hashStr.TrimEnd('=');
}
回答by KeithS
GetHashCode() is, by default, for internal use only, to check whether two references to an object are in fact the same object. The deafult hash implementation is based on stack/heap location and is thus not going to be deterministic between runs of the program (or even comparing two different references with exactly the same data). So, it should not be used for computing checksums.
默认情况下,GetHashCode() 仅供内部使用,用于检查对一个对象的两个引用是否实际上是同一个对象。默认的散列实现基于堆栈/堆位置,因此在程序运行之间不是确定性的(甚至将两个不同的引用与完全相同的数据进行比较)。因此,它不应该用于计算校验和。
.NET has an array of built-in libraries that serve this purpose; they're in the System.Security.Cryptography namespace. The two you want are the MD5 and SHA1 classes:
.NET 有一系列用于此目的的内置库;它们位于 System.Security.Cryptography 命名空间中。你想要的两个是 MD5 和 SHA1 类:
byte[] hashBytes;
using(var inputFileStream = File.Open(filePath))
{
var md5 = MD5.Create();
hashBytes = md5.ComputeHash(inputFileStream);
}
The SHA1class works the same way.
该SHA1班的工作方式相同。
A word of caution; both MD5 and SHA1 are considered "broken" and should not be used in any system requiring a "secure" hash. Consider using the SHA-256 or SHA-512 algorithms in the overall system instead. If you don't need a secure hash, there are faster checksum hashes like FNV-1a or MurmurHash that will provide good collision resistance.
一个警告;MD5 和 SHA1 都被视为“已损坏”,不应在任何需要“安全”散列的系统中使用。考虑在整个系统中使用 SHA-256 或 SHA-512 算法。如果您不需要安全散列,可以使用更快的校验和散列,如 FNV-1a 或 MurmurHash,它们将提供良好的抗碰撞性。
回答by Tony
Here is a complete code using C# managed library to compute the hash.
这是使用 C# 托管库计算散列的完整代码。
using system.IO;
using System.Security.Cryptography;
public string GetSha1Hash(string filePath)
{
using (FileStream fs = File.OpenRead(filePath))
{
SHA1 sha = new SHA1Managed();
return BitConverter.ToString(sha.ComputeHash(fs));
}
}

