HMAC ExampleHMAC is a message authentication code (MAC) and can be used to verify the integrity and authentication of a message. It involves hashing a message with a secret key. As with any MAC, it can be used with standard hash function, such as MD5 or SHA-1, which results in methods such as HMAC-MD5 or HMAC-SHA-1. As with any hashing function, the strength depends on the quality of the hashing function, and the resulting number of code bits. Along with this the number of bits in the secret key is a factor. [Lecture] [Tutorial]
The results are then:
Try it with a message of "testing123" and a key of "hello", and you should get: AC2C2E614882CE7158F69B7E3B12114465945D01 |
Examples
- Try "The quick brown fox jumps over the lazy dog" and "key" gives 0x80070713463E7749B90C2DC24911E275 (MD5). Try
- Try "The quick brown fox jumps over the lazy dog" and "key" gives 0xDE7C9B85B8B78AA6BC8A7A36F70A90701C9DB4D9 (SHA-1). Try
Sample code
using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Crypto.Paddings; public void checkHMAC(string key, string message) { if (key == null) return; if (message == null) return; System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] keyByte = encoding.GetBytes(key); HMACMD5 hmacmd5 = new HMACMD5(keyByte); HMACSHA1 hmacsha1 = new HMACSHA1(keyByte); HMACSHA256 hmacsha256 = new HMACSHA256(keyByte); HMACSHA384 hmacsha384 = new HMACSHA384(keyByte); HMACSHA512 hmacsha512 = new HMACSHA512(keyByte); byte[] messageBytes = encoding.GetBytes(message); byte[] hashmessage = hmacmd5.ComputeHash(messageBytes); hmac1 = Global.ByteToString(hashmessage); hashmessage = hmacsha1.ComputeHash(messageBytes); hmac2 = Global.ByteToString(hashmessage); hashmessage = hmacsha256.ComputeHash(messageBytes); hmac3 = Global.ByteToString(hashmessage); hashmessage = hmacsha384.ComputeHash(messageBytes); hmac4 = Global.ByteToString(hashmessage); hashmessage = hmacsha512.ComputeHash(messageBytes); hmac5 = Global.ByteToString(hashmessage); }