Hash Algorithm in .NET Framework and Data Protection
.NET Framework includes keyed and non-keyed algorithms and each is derived from System.Security.Cryptography.HashAlgorithm class which is based on System.Security.Cryptography.
Non-keyed Algorithms
Abstract Class | Description |
---|---|
MD5 | Message Digest algorithm |
RIPEMD160 | MD160 hash algorithm |
SHA1 | Hash Algorithm 1 |
SHA256 | Hash Algorithm 256 |
SHA384 | Hash Algorithm 384 |
SHA512 | Hash Algorithm 512 |
Keyed Algorithms
Class | Description |
---|---|
HMACSHA1 | Hash-based Message Authentication Code using SHA1 |
MACTripleDES | Message Authentication Code using TripleDES |
Computing non-keyed hash is simple
MD5 myHash = new MD5CryptoServiceProvider();
FileStream file = new FileStream(args[0], FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(file);
myHash.ComputeHash(reader.ReadBytes((int)file.Length));
Console.WriteLine(Convert.ToBase64String(myHash.Hash));
And keyed hash
byte[] saltValueBytes = Encoding.ASCII.GetBytes("This is my sa1t");
Rfc2898DeriveBytes passwordKey = new Rfc2898DeriveBytes(args[0], saltValueBytes);
byte[] secretKey = passwordKey.GetBytes(16);
HMACSHA1 myHash = new HMACSHA1(secretKey);
FileStream file = new FileStream(args[1], FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(file);
myHash.ComputeHash(reader.ReadBytes((int)file.Length));
Console.WriteLine(Convert.ToBase64String(myHash.Hash));