Skip to content

Instantly share code, notes, and snippets.

@ilude
Created October 21, 2011 00:56
Show Gist options
  • Save ilude/1302829 to your computer and use it in GitHub Desktop.
Save ilude/1302829 to your computer and use it in GitHub Desktop.
Git Hash Tests
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using NUnit.Framework;
namespace GitHash.Tests
{
[TestFixture]
public class HashingTests
{
[Test]
public void Test()
{
var info = new FileInfo("../../test.txt");
var data = info.OpenText().ReadToEnd().Replace("\r\n", "\n");
using (var hasher = new SHA1Managed())
using (var stream = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
{
Write(stream, "blob {0}", data.Length);
Write(stream, (byte) 0);
Write(stream, data);
stream.FlushFinalBlock();
var buffer = new StringBuilder();
foreach (var b in hasher.Hash)
{
buffer.Append(b.ToString("x2"));
}
Console.Out.WriteLine(buffer);
}
}
private void Write(Stream stream, Stream input)
{
var buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0) {
stream.Write(buffer, 0, read);
}
}
private void Write(Stream stream, byte b)
{
stream.WriteByte(b);
}
private void Write(Stream stream, string format, params object[] args)
{
if (args != null && args.Length > 0)
{
format = string.Format(format, args);
}
var buffer = Encoding.UTF8.GetBytes(format);
stream.Write(buffer, 0, buffer.Length);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment