As you know from the article git Tip of the week:objects, Git calculates the hash value of the submitted content in this way:
The hash algorithm uses a SHA1
Before the calculation, a "Blob content length" is added to the content, which indicates a null character (NUL).
The computed hash value is a 40-bit 16-binary sequence (40-character hexadecimal sequence).
For example, to submit an empty file, Git calculated the hash value is e69de29bb2d1d6434b8b29ae775ad8c2e48c5391, the actual calculation of the content is "blob 0\0."
Enter the command in the Mac's Terminal: Echo-en "blob 0\0" | Shasum, the same hash value is calculated.
How do you compute the hash value in C # in the same way?
SHA1 hash algorithm--c# in the corresponding implementation is sha1managed.
Like Git, add a string--string before the content. Format ("Blob {0}\0{1}", Content.length, Content);
Generates a 40-bit 16-binary hash value--tostring ("X2").
The specific implementation code is as follows:
public class Autosave
{public
string Content {get; set;}
public string Hash {get; set;}
public void Generatehash ()
{
var computedcontent = string. Format ("Blob {0}\0{1}", Content.length, Content);
var hashbytes = new SHA1Managed (). ComputeHash (Encoding.UTF8.GetBytes (computedcontent));
var sb = new StringBuilder ();
for (int i = 0; i < hashbytes.length i++)
{
sb. Append (Hashbytes[i]. ToString ("X2"));
}
This. Hash = sb. ToString ();
}
}
The test code is as follows:
public class Autosavetest
{
[Fact] public
void Generatehash_test ()
{
var autosave = new Autosave ();
AutoSave. Content = "";
AutoSave. Generatehash ();
Assert.equal ("e69de29bb2d1d6434b8b29ae775ad8c2e48c5391", AutoSave. Hash);
}
Test results:
1 passed, 0 failed, 0 skipped, took 1.13 seconds (xunit.net build 1705).
Get!
This article URL address: http://www.bianceng.cn/Programming/csharp/201410/45474.htm