I am currently creating an encrypted file format that needs to be signed. For this I need to calculate the hash code of the content I have written to a stream.
In the .net framework there is numerous hash algorithms that can be used, and it works fine, but it requires me to process the stream three times.
byte[] content = new byte[] { 0, 1, 2, 3, 4, 5, 6 };
using (Stream fileStream = File.Open("myfile.bin", FileMode.Create))
{
//Write content
fileStream.Write(content, 0, content.Length);
}
byte[] hashValue = null;
using (Stream fileStream = File.Open("myfile.bin", FileMode.Open))
{
HashAlgorithm hash = SHA256.Create();
hashValue = hash.ComputeHash(fileStream);
}
using (Stream fileStream = File.Open("myfile.bin", FileMode.Append))
{
fileStream.Write(hashValue, 0, hashValue.Length);
}
This is okay if it is encrypted to a file, but if it is encrypted to a network destination, the bytes are no longer available.
So basically I need to only process the data once. On CodeProject there is an article that has implemented CRC32 as a Stream that calculates the CRC32 code every time there is written data to it.
Something like:
byte[] content = new byte[] { 0, 1, 2, 3, 4, 5, 6 };
using (FileStream fileStream = File.Create("myfile.bin"))
using (Stream crcStream = new CRCStream(fileStream)) //Takes a base stream
{
//Write content
crcStream.Write(content, 0, content.Length);
//Write checksum
fileStream.Write(crcStream.WriteCRC, 0, 4);
}
Obviously CRC32 is not a hash alogorithm, but it would be nice to have something like a HashStream that takes a HashAlgorithm. The HashStream would update the hash value every time write/read is called.
Something like:
byte[] content = new byte[] { 0, 1, 2, 3, 4, 5, 6 };
HashAlgorithm hashAlgo = SHA256.Create();
using (File