1+ using System ;
2+ using System . IO ;
3+ using System . Security . Cryptography ;
4+ using System . Text ;
5+
6+ namespace QuantumExamples . Cryptography
7+ {
8+ public class HashExample
9+ {
10+ public static void RunExample ( )
11+ {
12+ const string originalMessage = "This is a message to hash!" ;
13+
14+ // Demonstrate various hash algorithms
15+ DemonstrateBasicHashing ( originalMessage ) ;
16+ DemonstrateStreamHashing ( originalMessage ) ;
17+ DemonstrateOneShotHashing ( originalMessage ) ;
18+ }
19+
20+ private static void DemonstrateBasicHashing ( string message )
21+ {
22+ byte [ ] messageBytes = Encoding . UTF8 . GetBytes ( message ) ;
23+
24+ using ( SHA256 sha256 = SHA256 . Create ( ) )
25+ {
26+ byte [ ] hash = sha256 . ComputeHash ( messageBytes ) ;
27+ Console . WriteLine ( "SHA256 hash: {0}" , Convert . ToBase64String ( hash ) ) ;
28+ }
29+
30+ using ( SHA1 sha1 = SHA1 . Create ( ) )
31+ {
32+ byte [ ] hash = sha1 . ComputeHash ( messageBytes ) ;
33+ Console . WriteLine ( "SHA1 hash: {0}" , Convert . ToBase64String ( hash ) ) ;
34+ }
35+
36+ using ( MD5 md5 = MD5 . Create ( ) )
37+ {
38+ byte [ ] hash = md5 . ComputeHash ( messageBytes ) ;
39+ Console . WriteLine ( "MD5 hash: {0}" , Convert . ToBase64String ( hash ) ) ;
40+ }
41+ }
42+
43+ private static void DemonstrateStreamHashing ( string message )
44+ {
45+ using SHA256 sha256 = SHA256 . Create ( ) ;
46+ using MemoryStream stream = new MemoryStream ( ) ;
47+ byte [ ] messageBytes = Encoding . UTF8 . GetBytes ( message ) ;
48+ stream . Write ( messageBytes , 0 , messageBytes . Length ) ;
49+ stream . Position = 0 ;
50+
51+ byte [ ] hash = sha256 . ComputeHash ( stream ) ;
52+ Console . WriteLine ( "Stream-based SHA256 hash: {0}" , Convert . ToBase64String ( hash ) ) ;
53+ }
54+
55+ private static void DemonstrateOneShotHashing ( string message )
56+ {
57+ byte [ ] messageBytes = Encoding . UTF8 . GetBytes ( message ) ;
58+
59+ byte [ ] sha256Hash = SHA256 . HashData ( messageBytes ) ;
60+ Console . WriteLine ( "One-shot SHA256 hash: {0}" , Convert . ToBase64String ( sha256Hash ) ) ;
61+
62+ byte [ ] sha1Hash = SHA1 . HashData ( messageBytes ) ;
63+ Console . WriteLine ( "One-shot SHA1 hash: {0}" , Convert . ToBase64String ( sha1Hash ) ) ;
64+
65+ byte [ ] md5Hash = MD5 . HashData ( messageBytes ) ;
66+ Console . WriteLine ( "One-shot MD5 hash: {0}" , Convert . ToBase64String ( md5Hash ) ) ;
67+ }
68+ }
69+ }
0 commit comments