Created
June 1, 2015 10:22
-
-
Save mlehmk/310bf6800801eeef4a56 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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