如何从文本文件创建MD5哈希摘要?

Cra*_*rze 23 c# hash md5

使用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("-", "");            
}
Run Code Online (Sandbox Code Playgroud)

rou*_*tic 16

这是我目前正在使用的例行程序.

    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();
    }
Run Code Online (Sandbox Code Playgroud)


Jes*_*cer 11

精炼到位. filename是你的文本文件的名称:

using (var md5 = MD5.Create())
{
    return BitConverter.ToString(md5.ComputeHash(File.ReadAllBytes(filename))).Replace("-", "");
}
Run Code Online (Sandbox Code Playgroud)

  • ToBase64String没有返回我想要的内容.但是,字节数组周围的BitConverter.ToString可以解决问题 (4认同)