在C#中计算git blob哈希

时间:2018-11-05 05:09:40

标签: c# git sha1

我正在尝试使用以下方法计算文件的sha1。结果与“ git ls-tree HEAD”报告的结果不同。我的代码有什么问题?

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

0 个答案:

没有答案