如何创建一个MD5哈希从一个文本文件消化? [英] How do I create an MD5 hash digest from a text file?
本文介绍了如何创建一个MD5哈希从一个文本文件消化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用C#,我想创建一个文本文件的MD5哈希值。我怎样才能做到这一点?请包括code。非常感谢!
更新:感谢大家的帮助。我终于在以下code结算 -
//创建一个MD5哈希摘要的文件
公共字符串MD5HashFile(字符串FN)
{
字节[] =哈希MD5.Create()ComputeHash(File.ReadAllBytes(FN))。
返回BitConverter.ToString(散列).Replace( - ,);
}
解决方案
下面是我目前使用的程序。
使用System.Security.Cryptography; 公共字符串HashFile(字符串文件路径)
{
使用(的FileStream FS =新的FileStream(文件路径,FileMode.Open,FileAccess.Read,FileShare.Read))
{
返回HashFile(FS);
}
} 公共字符串HashFile(的FileStream流)
{
StringBuilder的SB =新的StringBuilder(); 如果(流!= NULL)
{
stream.Seek(0,SeekOrigin.Begin); MD5 MD5 = MD5CryptoServiceProvider.Create();
字节[] =哈希md5.ComputeHash(流);
的foreach(哈希字节B)
sb.Append(b.ToString(×2)); stream.Seek(0,SeekOrigin.Begin);
} 返回sb.ToString();
}
Using C#, I want to create an MD5 hash of a text file. How can I accomplish this? Please include code. Many thanks!
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屋!
查看全文