Work With HashAlgorithm as an implementation of ICryptoTransform in .Net

81 Views Asked by At

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.

1

There are 1 best solutions below

0
On

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.

public static void HashFilesUsingCryptoStream1(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);
            using (StreamWriter writer = new StreamWriter(cs))
                writer.Write(fileBytes);//The stream must be closed first to ensure all data is computed and flushed.
            var hashBytes = ms.ToArray();
            Console.WriteLine($"Number of Bytes in Hash algorithms: {hashBytes.Length}");
            Console.WriteLine("Hash: " + Convert.ToBase64String(hashBytes));
        }