为文件夹创建哈希

时间:2010-09-02 09:13:04

标签: c# security

我需要为包含一些文件的文件夹创建哈希。我已经为每个文件完成了这个任务,但我正在搜索为文件夹中的所有文件创建一个哈希的方法。任何想法如何做到这一点?

(当然我可以为每个文件创建哈希并将其连接到一些大哈希,但这不是我喜欢的方式)

提前致谢。

7 个答案:

答案 0 :(得分:29)

这会散列所有文件(相对)路径和内容,并正确处理文件排序。

它很快 - 就像一个4MB目录的30ms一样。

using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Linq;

...

public static string CreateMd5ForFolder(string path)
{
    // assuming you want to include nested folders
    var files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
                         .OrderBy(p => p).ToList();

    MD5 md5 = MD5.Create();

    for(int i = 0; i < files.Count; i++)
    {
        string file = files[i];

        // hash path
        string relativePath = file.Substring(path.Length + 1);
        byte[] pathBytes = Encoding.UTF8.GetBytes(relativePath.ToLower());
        md5.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0);

        // hash contents
        byte[] contentBytes = File.ReadAllBytes(file);
        if (i == files.Count - 1)
            md5.TransformFinalBlock(contentBytes, 0, contentBytes.Length);
        else
            md5.TransformBlock(contentBytes, 0, contentBytes.Length, contentBytes, 0);
    }

    return BitConverter.ToString(md5.Hash).Replace("-", "").ToLower();
}

答案 1 :(得分:11)

Dunc的答案很有效;但是,它不处理空目录。以下代码返回MD5&#39; d41d8cd98f00b204e9800998ecf8427e&#39; (空长目录的MD5表示0长度字符流)。

public static string CreateDirectoryMd5(string srcPath)
{
    var filePaths = Directory.GetFiles(srcPath, "*", SearchOption.AllDirectories).OrderBy(p => p).ToArray();

    using (var md5 = MD5.Create())
    {
        foreach (var filePath in filePaths)
        {
            // hash path
            byte[] pathBytes = Encoding.UTF8.GetBytes(filePath);
            md5.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0);

            // hash contents
            byte[] contentBytes = File.ReadAllBytes(filePath);

            md5.TransformBlock(contentBytes, 0, contentBytes.Length, contentBytes, 0);
        }

        //Handles empty filePaths case
        md5.TransformFinalBlock(new byte[0], 0, 0);

        return BitConverter.ToString(md5.Hash).Replace("-", "").ToLower();
    }
}

答案 2 :(得分:7)

创建文件的tarball,散列tarball。

> tar cf hashes *.abc
> md5sum hashes

或者将单个文件和管道输出散列为hash命令。

> md5sum *.abc | md5sum

编辑:上述两种方法都不对文件进行排序,因此可能会为每次调用返回不同的哈希值,具体取决于shell如何扩展星号。

答案 3 :(得分:1)

将文件名和文件内容连接成一个大字符串并散列,或者以块的形式进行散列以获得性能。

当然,您需要考虑以下几点:

  • 您需要按名称对文件进行排序,因此在案例文件顺序更改时不会得到两个不同的哈希值。
  • 使用此方法,您只需考虑文件名和内容。如果文件名不计数,你可以先按内容排序然后排序,如果有更多属性(ctime / mtime / hidden / archived ..)很重要,请将它们包含在待加工字符串中。

答案 4 :(得分:1)

如果你已经有所有文件的哈希值,只需按字母顺序对哈希值进行排序,连接它们并再次哈希它们以创建一个超级哈希值。

答案 5 :(得分:1)

这是使用流技术来避免内存和延迟问题的解决方案。

默认情况下,文件路径包含在哈希中,这不仅会考虑文件中的数据,还会考虑文件系统条目本身,从而避免了哈希冲突。这篇文章的标签为security,因此它应该很重要。

最后,此解决方案使您可以控制散列算法以及对哪些文件进行散列以及以什么顺序进行散列。

public static class HashAlgorithmExtensions
{
    public static async Task<byte[]> ComputeHashAsync(this HashAlgorithm alg, IEnumerable<FileInfo> files, bool includePaths = true)
    {
        using (var cs = new CryptoStream(Stream.Null, alg, CryptoStreamMode.Write))
        {
            foreach (var file in files)
            {
                if (includePaths)
                {
                    var pathBytes = Encoding.UTF8.GetBytes(file.FullName);
                    cs.Write(pathBytes, 0, pathBytes.Length);
                }

                using (var fs = file.OpenRead())
                    await fs.CopyToAsync(cs);
            }

            cs.FlushFinalBlock();
        }

        return alg.Hash;
    }
}

一个哈希文件夹中所有文件的示例:

async Task<byte[]> HashFolder(DirectoryInfo folder, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly)
{
    using(var alg = MD5.Create())
        return await alg.ComputeHashAsync(folder.EnumerateFiles(searchPattern, searchOption));
}

答案 6 :(得分:-1)

Quick and Dirty文件夹哈希不能分解为子订单或读取二进制数据。它基于文件和子文件夹的名称。

Public Function GetFolderHash(ByVal sFolder As String) As String
    Dim oFiles As List(Of String) = IO.Directory.GetFiles(sFolder).OrderBy(Function(x) x.Count).ToList()
    Dim oFolders As List(Of String) = IO.Directory.GetDirectories(sFolder).OrderBy(Function(x) x.Count).ToList()
    oFiles.AddRange(oFolders)

    If oFiles.Count = 0 Then
        Return ""
    End If

    Dim oDM5 As System.Security.Cryptography.MD5 = System.Security.Cryptography.MD5.Create()
    For i As Integer = 0 To oFiles.Count - 1
        Dim sFile As String = oFiles(i)
        Dim sRelativePath As String = sFile.Substring(sFolder.Length + 1)
        Dim oPathBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(sRelativePath.ToLower())

        If i = oFiles.Count - 1 Then
            oDM5.TransformFinalBlock(oPathBytes, 0, oPathBytes.Length)
        Else
            oDM5.TransformBlock(oPathBytes, 0, oPathBytes.Length, oPathBytes, 0)
        End If
    Next

    Return BitConverter.ToString(oDM5.Hash).Replace("-", "").ToLower()
End Function