Skip to content

HMAC

HMAC

  • Similar to Symmetric Encryption as in both sides need the secret key to verify the integrity of the message
  • Not vulnerable to Length Extension attacks because it uses the output the hash function as input to another and should be unique on each input

Note

If the hmac key is not the same length of the block size then it is prehashed. This might open up problems.

Implementation

import hashlib

def fixedlen_xor(input1, input2):
	assert(len(input1) == len(input2))
	return bytes([input1[i] ^ input2[i] for i in range(len(input1))])


def hmac(key, message, hash_function):
	#Get hash_function block_size
	block_size = getattr(hash_function(), 'block_size')

	# Check if key is longer than block size.
	if len(key) > block_size:
		# IF it is then hash the key. This makes the keysize the same as the output of the hashfunction
		key = hash_function(key).digest()

	# IF key is shorter
	if len(key) < block_size:
		# Pad the key to blocksize
		key = key + b"\x00" * (block_size - len(key))

	#print(key, len(key), block_size)

	# Create Keys
	o_key = fixedlen_xor(key, b"\x5c" * block_size)
	i_key = fixedlen_xor(key, b"\x36" * block_size)

	#Hash i_key and message
	tmp = hash_function(i_key + message)

	#Hash the o_key and the hashed output of above
	return hash_function(o_key + tmp.digest()).digest()

print(test.hexdigest())
#32885b49c8a1009e6d66662f8462e7dd5df769a7b725d1d546574e6d5d6e76ad

Security

https://mathiasbynens.be/notes/pbkdf2-hmac