How is sha1 hash generated
I have a situation where I would like to check if a file has been changed before re-uploading it to Box (the change may have occurred outside of Box, and I want to see if it is worth replacing the current version on Box). The best way to do this would be to compare a hash, especially as it is easy to get the sha1 hash from Box.
However, if I generate a sha1 hash of the unmodified file using nodeJs crypto, it is not the same as the sha1 hash created by Box. Does Box include other data (such as filename or dates) when generating the hash, if so is there a description of how I could create a matching hash if the data of the file itself has not changed?
-
//This is how I do it in C#. You may have to google how the SHA1Managed object does it. It returns the same sha1 string as the Box sha1.
//Cut-and-pasting relevant snippets from what I have...
using SSC = System.Security.Cryptography;
using SI = System.IO;public static string GetSha1HashOfFile(string pathToFile)
{
using (SSC.SHA1Managed sha1 = new SSC.SHA1Managed())
{
using (SI.FileStream stream = SI.File.OpenRead(pathToFile))
{
return GetSha1Hash(sha1, stream);
}
}
}public static string GetSha1Hash(SSC.SHA1Managed sha1, SI.Stream stream)
{
byte[] hash = sha1.ComputeHash(stream);
return HashByteArrayToString(hash);
}public static string HashByteArrayToString(byte[] hashByteArray)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder(hashByteArray.Length * 2);
foreach (byte b in hashByteArray)
{
// can be "x2" if you want lowercase
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
Please sign in to leave a comment.
Comments
1 comment