Pacobart
Pacobart

Reputation: 261

How would I hash a folder using SHA1

Is there a way to use SHA1 to hash a folder with all of the contents within it? I am able to do this using MD5 but am afraid of the collisions MD5 suffers from. I am trying to build an app that checks local files to see if they match an online version using hashes.

Here is the code I am using with MD5:

var path = leftCheckTextbox.Text;
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];

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

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

leftHash = BitConverter.ToString(md5.Hash).Replace("-", "").ToLower();

Upvotes: 0

Views: 3275

Answers (1)

Alexander Simonov
Alexander Simonov

Reputation: 1584

Just change all MD5 to SHA1 in your source code.

Upvotes: 10

Related Questions