How is hmac sha256 different from sha256?

591    Asked by AntonyBence in Cyber Security , Asked on Sep 23, 2022

Is there anything different about how secure these two hashing algorithms are? Does HMAC "fuse" the data and the key in a special way that's more security-aware?

Answered by Ankit Chauhan

Yes, HMAC sha256 is more complex than simple concatenation.


As a simplistic example, if you were to simply concatenate key + data, then "key1"+"data" yields identical results to "key"+"1 data", which is suboptimal. HMAC will yield different results for each. There are other flaws with simple concatenation in many cases, as well; see cpast's answer for one.

The specification for HMAC is called RFC2104, which you should read if you have this level of interest.

In summary, to implement HMAC, you should first:

Create "ipad", which is 0x36 repeated BLOCKSIZE times. Create "opad", which is 0x5c repeated BLOCKSIZE times.

Note that BLOCKSIZE is 64 bytes for MD5, SHA-1, SHA-224, SHA-256, and 128 bytes for SHA-384 and SHA-512, per RFC2104 and RFC4868.

Then HMAC is defined as:HASH(Key XOR opad, HASH(Key XOR ipad, text))or, in detail from the RFC,

(Pretext: The definition of HMAC requires a cryptographic hash function, which we denote by H, and a secret key K. We assume H to be a cryptographic hash function where data is hashed by iterating a basic compression function on blocks of data. We denote by B the byte-length of such blocks.)

(1) append zeros to the end of K to create a B byte string (e.g., if K is of length 20 bytes and B=64, then K will be appended with 44 zero bytes 0x00)

(2) XOR (bitwise exclusive-OR) the B byte string computed in step (1) with ipad

(3) append the stream of data 'text' to the B byte string resulting from step (2)

(4) apply H to the stream generated in step (3)

(5) XOR (bitwise exclusive-OR) the B byte string computed in step (1) with opad

(6) append the H result from step (4) to the B byte string resulting from step (5)

(7) apply H to the stream generated in step (6) and output the result



Your Answer

Interviews

Parent Categories