Skip to content

Instantly share code, notes, and snippets.

@roughconsensusandrunningcode
Last active January 3, 2020 23:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roughconsensusandrunningcode/eab09551779e7926dce17ea07c10b373 to your computer and use it in GitHub Desktop.
Save roughconsensusandrunningcode/eab09551779e7926dce17ea07c10b373 to your computer and use it in GitHub Desktop.
C# - Create a file and compute its hash at the same time
using System;
using System.IO;
using System.Security.Cryptography;
namespace HashDemo
{
class Program
{
public static void Main (string[] args)
{
string filename = Path.GetTempFileName();
SHA256 hash = SHA256.Create();
string digest;
string expected_digest = "BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD";
using (Stream stream = new FileStream(filename, FileMode.Create, FileAccess.Write)) {
using (CryptoStream cs = new CryptoStream(stream, hash, CryptoStreamMode.Write)){
// 'abc'
cs.Write(new byte[] {0x61, 0x62, 0x63}, 0, 3);
cs.FlushFinalBlock();
digest = BitConverter.ToString (hash.Hash).Replace ("-", "");
if (expected_digest != digest) {
Console.WriteLine ("Something has gone wrong...");
}
Console.WriteLine(digest);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment