The hashing method of MD5 should not be used these days, as it is possible to create a hash collision for a relatively low cost. Improved methods are SHA-1 (160 bits), SHA-256 (256 bits) and SHA-512 (512 bits). This page provides a Federal Information Processing Standard (FIPS) approved code for hashing methods and which integrates into the Bouncy Castle FIPS (FIPS) C# API. This needs the bc-fips-1.0.2.dll assembly and which integrates into the System.Security.Cryptography provider.
FIPS Hashing in C# |
Coding
The full code is:
namespace PB { using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Fips; using Org.BouncyCastle.Crypto.Utilities; using Org.BouncyCastle.Security; class Program { static void Main(string[] args) { var hash="sha256"; var msg="Qwerty123"; if (args.Length >0) msg=args[0]; if (args.Length >1) hash=args[1]; try { var hashmethod=FipsShs.Sha256; if (hash=="SHA1") hashmethod=FipsShs.Sha1; if (hash=="SHA224") hashmethod=FipsShs.Sha224; if (hash=="SHA256") hashmethod=FipsShs.Sha256; if (hash=="SHA384") hashmethod=FipsShs.Sha384; if (hash=="SHA512") hashmethod=FipsShs.Sha512; if (hash=="SHA3_224") hashmethod=FipsShs.Sha3_224; if (hash=="SHA3_256") hashmethod=FipsShs.Sha3_256; if (hash=="SHA3_384") hashmethod=FipsShs.Sha3_384; if (hash=="SHA3_512") hashmethod=FipsShs.Sha3_512; IDigestFactory<FipsShs.Parameters> factory = CryptoServicesRegistrar.CreateService(hashmethod); IStreamCalculator<IBlockResult> calculator = factory.CreateCalculator(); Stream digestStream = calculator.Stream; digestStream.Write(System.Text.Encoding.UTF8.GetBytes(msg), 0,System.Text.Encoding.UTF8.GetBytes(msg).Length); digestStream.Close(); byte[] digest = calculator.GetResult().Collect(); Console.WriteLine("Message: {0}",msg); Console.WriteLine("Hash method: {0}",hash); Console.WriteLine("Hash: {0}",Convert.ToHexString(digest)); Console.WriteLine("Hash: {0}",Convert.ToBase64String(digest)); } catch (Exception e) { Console.WriteLine("Error: {0}",e.Message); } } } }
and a sample test is:
Message: Qwerty Hash method: SHA1 Hash: 36810ED90AA5DE17CBC1B471B999EC6B53B7C602 Hash: NoEO2Qql3hfLwbRxuZnsa1O3xgI=