[英]How do I create an MD5 hash digest from a text file?
使用 C#,我想创建一个文本文件的 MD5 哈希。 我怎样才能做到这一点?
更新:感谢大家的帮助。 我终于确定了以下代码 -
// Create an MD5 hash digest of a file
public string MD5HashFile(string fn)
{
byte[] hash = MD5.Create().ComputeHash(File.ReadAllBytes(fn));
return BitConverter.ToString(hash).Replace("-", "");
}
这是我目前使用的例程。
using System.Security.Cryptography;
public string HashFile(string filePath)
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
return HashFile(fs);
}
}
public string HashFile( FileStream stream )
{
StringBuilder sb = new StringBuilder();
if( stream != null )
{
stream.Seek( 0, SeekOrigin.Begin );
MD5 md5 = MD5CryptoServiceProvider.Create();
byte[] hash = md5.ComputeHash( stream );
foreach( byte b in hash )
sb.Append( b.ToString( "x2" ) );
stream.Seek( 0, SeekOrigin.Begin );
}
return sb.ToString();
}
精炼到位。 filename
是您的文本文件的名称:
using (var md5 = MD5.Create())
{
return BitConverter.ToString(md5.ComputeHash(File.ReadAllBytes(filename))).Replace("-", "");
}
internal static string GetHashCode(string filePath, HashAlgorithm cryptoService)
{
// create or use the instance of the crypto service provider
// this can be either MD5, SHA1, SHA256, SHA384 or SHA512
using (cryptoService)
{
using (var fileStream = new FileStream(filePath,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
var hash = cryptoService.ComputeHash(fileStream);
var hashString = Convert.ToBase64String(hash);
return hashString.TrimEnd('=');
}
}
}
WriteLine("MD5 Hash Code : {0}", GetHashCode(FilePath, new MD5CryptoServiceProvider()));
WriteLine("SHA1 Hash Code : {0}", GetHashCode(FilePath, new SHA1CryptoServiceProvider()));
WriteLine("SHA256 Hash Code: {0}", GetHashCode(FilePath, new SHA256CryptoServiceProvider()));
WriteLine("SHA384 Hash Code: {0}", GetHashCode(FilePath, new SHA384CryptoServiceProvider()));
WriteLine("SHA512 Hash Code: {0}", GetHashCode(FilePath, new SHA512CryptoServiceProvider()));
这是一个不需要将整个文件读入内存的 .NET Standard 版本:
private byte[] CalculateMD5OfFile(FileInfo targetFile)
{
byte[] hashBytes = null;
using (var hashcalc = System.Security.Cryptography.MD5.Create())
{
using (FileStream inf = targetFile.OpenRead())
hashcalc.ComputeHash(inf);
hashBytes = hashcalc.Hash;
}
return hashBytes;
}
您可以使用上面显示的方法将 byte[] 数组转换为字符串。 另外:您可以将第三行中的“MD5”更改为 SHA1、SHA256 等以计算其他哈希值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.