// 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.Text; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Digests; namespace Encrypt { public class TestHashing { // hash: byte[] -> byte[] public static byte[] Hash(IDigest alg, byte[] content) { byte[] res = new byte[alg.GetDigestSize()]; alg.BlockUpdate(content, 0, content.Length); alg.DoFinal(res, 0); return res; } // Base64 encode: byte[] -> string private static string Encode(byte[] b) { return Convert.ToBase64String(b); } // hash: string -> Base64 string public static string Hash(IDigest 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, IDigest 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 Sha256Digest(), TEXT) != "oJM3t4y26uLCLtiLLNP8bhZuZi24znFEdB+QnM2d0w4=") { throw new Exception("Ooops"); } } public static void Main(string[] args) { Test("SHA-2 224 bit", new Sha224Digest()); Test("SHA-2 256 bit", new Sha256Digest()); Test("SHA-2 384 bit", new Sha384Digest()); Test("SHA-2 512 bit", new Sha512Digest()); Test("SHA-3 224 bit", new Sha3Digest(224)); Test("SHA-3 256 bit", new Sha3Digest(256)); Test("SHA-3 384 bit", new Sha3Digest(384)); Test("SHA-3 512 bit", new Sha3Digest(512)); Test("RIPEMD 160 bit", new RipeMD160Digest()); Test2(); } } }