// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Security.Cryptography; using System.Text; namespace Encrypt { public class TestHashing { // hash: byte[] -> byte[] public static byte[] Hash(HashAlgorithm alg, byte[] content) { return alg.ComputeHash(content); } // Base64 encode: byte[] -> string private static string Encode(byte[] b) { return Convert.ToBase64String(b); } // hash: string -> Base64 string public static string Hash(HashAlgorithm alg, string content) { return Encode(Hash(alg, Encoding.UTF8.GetBytes(content))); } // test private const string TEXT = "This is some random text to be used to test encryption."; private static void Test(string label, HashAlgorithm alg) { Console.WriteLine(label + ":"); string hashval = Hash(alg, TEXT); Console.WriteLine(" " + hashval); string hashval2 = Hash(alg, TEXT + TEXT); Console.WriteLine(" " + hashval2); } private static void Test2() { if(Hash(new SHA256Managed(), TEXT) != "oJM3t4y26uLCLtiLLNP8bhZuZi24znFEdB+QnM2d0w4=") { throw new Exception("Ooops"); } } public static void Main(string[] args) { // managed implementations Test("SHA-2 256 bit (managed)", new SHA256Managed()); Test("SHA-2 384 bit (managed)", new SHA384Managed()); Test("SHA-2 512 bit (managed)", new SHA512Managed()); // CAPI implementations Test("SHA-2 256 bit (CAPI)", new SHA256CryptoServiceProvider()); Test("SHA-2 384 bit (CAPI)", new SHA384CryptoServiceProvider()); Test("SHA-2 512 bit (CAPI)", new SHA512CryptoServiceProvider()); // Test2(); } } }