Hash is used to verify that data was not tempered during transmission. Hash is a checksum value generated and assigned to a file. Hash generation is only happen once; we cannot get a value out of hash. In some instances, we don’t even store a password but its hash value. We authenticate password by simply converting it into hash value and than comparing hash value and stored hash value in the database. If both match we’ll authenticate.
.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));