0

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.

Mehdi Mowlavi
  • 434
  • 1
  • 11
  • 1
    Have you tried using a `StreamWriter` to write to the `CryptoStream` (making sure that you `Dispose` the stream writer before going any further). I'm guessing that someone needs to flush the stream after the write. The `CryptoStream` example I'm looking at is https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.cryptostream – Flydog57 Jan 16 '23 at 18:10
  • @Flydog Thanks. I tried it now and Yes, it works. I just changed the using (var cs=..) {} to old version of it and added the stream writer and it works! Where is the point in it? – Mehdi Mowlavi Jan 16 '23 at 18:15

1 Answers1

0

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));
        }
Mehdi Mowlavi
  • 434
  • 1
  • 11