In cryptography, HMAC (Hash-based Message Authentication Code) is a specific construction for calculating a message authentication code (MAC) involving a cryptographic hash function in combination with a secret key.
In cryptography, HMAC (Hash-based Message Authentication Code) is a specific construction for calculating a message authentication code (MAC) involving a cryptographic hash function in combination with a secret key. As with any MAC, it may be used to simultaneously verify both the data integrity and the authenticity of a message. Any cryptographic hash function, such as MD5 or SHA-1, may be used in the calculation of an HMAC; the resulting MAC algorithm is termed HMAC-MD5 or HMAC-SHA1 accordingly. The cryptographic strength of the HMAC depends upon the cryptographic strength of the underlying hash function, the size of its hash output length in bits and on the size and quality of the cryptographic key.
An iterative hash function breaks up a message into blocks of a fixed size and iterates over them with a compression function. For example, MD5 and SHA-1 operate on 512-bit blocks. The size of the output of HMAC is the same as that of the underlying hash function (128 or 160 bits in the case of MD5 or SHA-1, respectively), although it can be truncated if desired.
The definition and analysis of the HMAC construction was first published in 1996 by Mihir Bellare, Ran Canetti, and Hugo Krawczyk, who also wrote RFC 2104. This paper also defined a variant called NMAC that is rarely if ever used. FIPS PUB 198 generalizes and standardizes the use of HMACs. HMAC-SHA-1 and HMAC-MD5 are used within the IPsec and TLS protocols.
Source: Wikipedia
An example of calculating a HMAC-SHA256 in Java:
byte[] expectedResult = { /* Expected HMAC result from a prior run */
96, 21, 116, 11, 4, -51, -115, -20, 104, 18, 117, -75, 3, -100, 126,
-89, -22, 120, -120, 30, 102, 104, -125, -120, -62, 111, -75,
24, 14, 62, 48, -65 };
byte[] secret = "your eyes only".getBytes();
String algorithm = "HmacSha256";
SecretKeySpec signingKey = new SecretKeySpec(secret, algorithm);
// Init HMAC usign secret
Mac hmac = Mac.getInstance(algorithm);
hmac.init(signingKey);
// Run message through HMAC and calculate result
byte[] message = "Don't tamper with me".getBytes();
byte[] macOutput = hmac.doFinal(message);
// Compare HMAC output to expected result
// A message that has been altered will not be equal
assertTrue(Arrays.equals(macOutput, expectedResult));