According to Microsoft documentation, HashAlgorithm
class implement ICryptoTransform
interface, so we should be able to use it with CryptoStream
. But when I use it, I get the input stream without any hashing. Where is my mistake?
My code is as following:
public static void HashFilesUsingCryptoStream(string inputPath)
{
var fileBytes = File.ReadAllBytes(inputPath);
using ICryptoTransform hashAlg = SHA1.Create();
using var ms = new MemoryStream();
using var cs = new CryptoStream(ms, hashAlg, CryptoStreamMode.Write);
cs.Write(fileBytes);
var hashBytes = ms.ToArray();
Console.WriteLine($"Number of Bytes in Hash algorithms: {hashBytes.Length}");
Console.WriteLine("Hash: " + Encoding.UTF8.GetString(hashBytes));
}
Thank you.
According to comment to the question, I can solve my problem as following (The difference is adding stream writer helper class and also disposing it right after writing the content to the stream.