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

发布于 2024-08-19 13:34:19 字数 347 浏览 2 评论 0原文

我想使用 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 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("-", "");            
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

深海少女心 2024-08-26 13:34:19

这是我目前正在使用的例程。

    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();
    }

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();
    }
ぽ尐不点ル 2024-08-26 13:34:19

简短而切题。 filename 是您的文本文件的名称:

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

Short and to the point. filename is your text file's name:

using (var md5 = MD5.Create())
{
    return BitConverter.ToString(md5.ComputeHash(File.ReadAllBytes(filename))).Replace("-", "");
}
飞烟轻若梦 2024-08-26 13:34:19

这可以通过带有重载的 GetHashCode 来实现,允许传递 filePath、StreamReader 或 Stream:

private static string GetHashCode(string filePath, HashAlgorithm cryptoService = null)
    => GetHashCode(fStream: new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), cryptoService);

private static string GetHashCode(StreamReader fileStreamReader, HashAlgorithm cryptoService = null)
    => GetHashCode(fileStreamReader.BaseStream, cryptoService);


/// <summary>
/// Compute hash code for file.
/// </summary>
/// <param name="fStream"></param>
/// <param name="cryptoService">This can be either MD5, SHA1, SHA256, SHA384 or SHA512</param>
/// <returns>Hash string</returns>
private static string GetHashCode(Stream fStream, HashAlgorithm cryptoService = null)
{

    // create or use the instance of the crypto service provider
    // this can be either MD5, SHA1, SHA256, SHA384 or SHA512
    using (cryptoService ??= System.Security.Cryptography.SHA512.Create())
    {
        using var tmpStream = fStream;
        var hash = cryptoService.ComputeHash(tmpStream);
        var hashString = Convert.ToBase64String(hash);
        return hashString.TrimEnd('=');
    }
} // method

用法:

WriteLine("Default Sha512 Hash Code   : {0}", GetHashCode(FilePath));

或者:

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()));

This can be achieved by GetHashCode with overloads, allowing to pass either a filePath, a StreamReader or a Stream:

private static string GetHashCode(string filePath, HashAlgorithm cryptoService = null)
    => GetHashCode(fStream: new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), cryptoService);

private static string GetHashCode(StreamReader fileStreamReader, HashAlgorithm cryptoService = null)
    => GetHashCode(fileStreamReader.BaseStream, cryptoService);


/// <summary>
/// Compute hash code for file.
/// </summary>
/// <param name="fStream"></param>
/// <param name="cryptoService">This can be either MD5, SHA1, SHA256, SHA384 or SHA512</param>
/// <returns>Hash string</returns>
private static string GetHashCode(Stream fStream, HashAlgorithm cryptoService = null)
{

    // create or use the instance of the crypto service provider
    // this can be either MD5, SHA1, SHA256, SHA384 or SHA512
    using (cryptoService ??= System.Security.Cryptography.SHA512.Create())
    {
        using var tmpStream = fStream;
        var hash = cryptoService.ComputeHash(tmpStream);
        var hashString = Convert.ToBase64String(hash);
        return hashString.TrimEnd('=');
    }
} // method

Usage:

WriteLine("Default Sha512 Hash Code   : {0}", GetHashCode(FilePath));

Or:

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()));
执笔绘流年 2024-08-26 13:34:19

这是一个不需要将整个文件读入内存的 .NET 标准版本:

    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等来计算其他哈希值。

Here is a .NET Standard version that doesn't require reading the entire file into memory:

    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;
    }

You can convert the byte[] array into a string using the methods shown above. Also: You can change "MD5" in the third line to SHA1, SHA256, etc. to calculate other hashes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文