Skip to content

Instantly share code, notes, and snippets.

@mlehmk
Created June 1, 2015 10:22
Show Gist options
  • Select an option

  • Save mlehmk/310bf6800801eeef4a56 to your computer and use it in GitHub Desktop.

Select an option

Save mlehmk/310bf6800801eeef4a56 to your computer and use it in GitHub Desktop.
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
public class HashingStream : CryptoStream
{
private readonly SHA256 _hasher;
private string _hash = null;
private byte[] _hashBytes = null;
private HashingStream(Stream stream, SHA256 hasher)
: base(stream, hasher, CryptoStreamMode.Read)
{
_hasher = hasher;
}
public HashingStream(Stream stream)
: this(stream, new SHA256Managed())
{
}
public string GetHash()
{
return _hash ?? (_hash = String.Concat(GetHashBytes().Select(x => x.ToString("x2"))));
}
public byte[] GetHashBytes()
{
if (!HasFlushedFinalBlock)
{
FlushFinalBlock();
}
return _hashBytes ?? (_hashBytes = _hasher.Hash);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
_hasher.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment