In this article I will try to unravel the HMAC algo, how it’s used, and how it can be attacked.
Mechanics
These constants were chosen because they have particular properties when used with XOR operation. The
0x36
value inverts half the bits when XORed with the key, and0x5c
inverts all but one of the other half. This helps to ensure a good distribution of the resulting values, making the algorithm more secure.
Code
import hashlib
def xor_bytes(a, b):
return bytes(x ^ y for x, y in zip(a, b))
def hmac(key, message):
# If key is longer than block size, hash it
if len(key) > 64:
key = hashlib.sha256(key).digest()
# If key is shorter than block size, pad it with zeros on the right
if len(key) < 64:
key = key + b'\x00' * (64 - len(key))
# Compute inner hash
o_key_pad = xor_bytes(key, b'\x5c' * 64)
i_key_pad = xor_bytes(key, b'\x36' * 64)
inner_hash = hashlib.sha256(i_key_pad + message).digest()
# Compute outer hash
hmac_result = hashlib.sha256(o_key_pad + inner_hash)
return hmac_result.hexdigest()
key = b'secret_key'
message = b'This is a test message'
print(hmac(key, message))