1

I am trying to compute the sha1 of a file using the below method. The result is different from what is reported by "git ls-tree HEAD". What's wrong with my code?

    static public string ComputeSha1()
    {
        //"blob " + <size_of_file> + "\0" + <contents_of_file>
        var content = File.ReadAllBytes(@"c:\projects\myproj\Word.docx");
        var contentLength = Encoding.UTF8.GetByteCount(Encoding.UTF8.GetString(content));
        var blob = "blob " + contentLength + "\0" + Encoding.UTF8.GetString(content);

        using (SHA1 sha1 = SHA1.Create())
        {
            byte[] bytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(blob));

            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                builder.Append(bytes[i].ToString("x2"));
            }
            return builder.ToString();
        }
    }
LND
  • 142
  • 9
  • 1
    possible duplicate: https://stackoverflow.com/questions/1993903/how-do-i-do-a-sha1-file-checksum-in-c – jazb Nov 05 '18 at 05:44
  • Possible duplicate of [How do I do a SHA1 File Checksum in C#?](https://stackoverflow.com/questions/1993903/how-do-i-do-a-sha1-file-checksum-in-c) – phd Nov 05 '18 at 12:08
  • Stay away from `string`. Always use byte arrays. This is general advice dealing with git in languages with "unicode support" – max630 Nov 05 '18 at 12:44
  • @JohnB, @phd I actually have reviewed the link, plus others, that you provided but I decided my question is a little different. I guess I can isolate the difference by these more specific questions: 1. Am I setting the values of content and contentLength correctly? 2. Am I concatenating properly to set the value of blob correctly? @max630 I have seen comments somewhere else alluding to the same as yours. I have tried a number of variations to avoid `string` without success. Would you be kind enough to make the necessary corrections to my code? – LND Nov 05 '18 at 17:19

0 Answers0