如何从文本文件创建 MD5 哈希摘要? [英] How do I create an MD5 hash digest from a text file?
本文介绍了如何从文本文件创建 MD5 哈希摘要?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 C#,我想创建一个文本文件的 MD5 哈希值.我怎样才能做到这一点?
Using C#, I want to create an MD5 hash of a text file. How can I accomplish this?
更新:感谢大家的帮助.我终于确定了以下代码 -
Update: Thanks to everyone for their help. I've finally settled upon the following code -
// 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("-", "");
}
推荐答案
这是我目前使用的例程.
Here's the routine I'm currently using.
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();
}
这篇关于如何从文本文件创建 MD5 哈希摘要?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文