public void TestHashStreamWrite() { Random r = new Random(); byte[][] test = new byte[][] { new byte[300], new byte[1], new byte[500], new byte[11], new byte[1], new byte[1000], }; using (HashStream hs = new HashStream(new SHA256Managed())) using (MemoryStream ms = new MemoryStream()) using (HashStream hsWrap = new HashStream(new SHA256Managed(), ms)) { Assert.IsTrue(hs.CanWrite); long len = 0; foreach (byte[] bytes in test) { len += bytes.Length; r.NextBytes(bytes); hsWrap.Write(bytes, 0, bytes.Length); hs.Write(bytes, 0, bytes.Length); } for (int i = 0; i < 5; i++) { len += 1; byte val = (byte)r.Next(255); hsWrap.WriteByte(val); hs.WriteByte(val); } Assert.AreEqual(len, ms.Position); Hash expect = Hash.SHA256(ms.ToArray()); Hash actual = hs.Close(); Assert.AreEqual(expect, actual); Assert.AreEqual(expect.ToArray(), actual.ToArray()); Assert.AreEqual(expect.ToString(), actual.ToString()); //wrapped test actual = hsWrap.FinalizeHash(); Assert.AreEqual(expect, actual); Assert.AreEqual(expect.ToArray(), actual.ToArray()); Assert.AreEqual(expect.ToString(), actual.ToString()); } }
public void TestHashStreamRead() { Random r = new Random(); byte[] bytes = new byte[1000]; r.NextBytes(bytes); using (HashStream hs = new HashStream(new SHA256Managed(), new MemoryStream(bytes))) { for (int i = 0; i < 5; i++) { while (hs.Position < hs.Length) { hs.ReadByte(); int amt = r.Next(255); byte[] tmp = new byte[amt]; hs.Read(tmp, 0, tmp.Length); } } Hash expect = Hash.SHA256(bytes); Hash actual = hs.FinalizeHash(); Assert.AreEqual(expect, actual); Assert.AreEqual(expect.ToArray(), actual.ToArray()); Assert.AreEqual(expect.ToString(), actual.ToString()); //still valid after FinalizeHash(); however, hash is restarted hs.Position = 0; IOStream.Read(hs, bytes.Length); actual = hs.FinalizeHash(); Assert.AreEqual(expect, actual); Assert.AreEqual(expect.ToArray(), actual.ToArray()); Assert.AreEqual(expect.ToString(), actual.ToString()); } }