Last active
January 3, 2020 23:11
-
-
Save roughconsensusandrunningcode/eab09551779e7926dce17ea07c10b373 to your computer and use it in GitHub Desktop.
C# - Create a file and compute its hash at the same time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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