Skip to content

HKDF

HKDF

  • Key derivation using the HMAC algorithm

Implementation

#!/usr/bin/env python3
import hashlib
import hmac, os
from math import ceil

def hmac_hash(hash_object, key, data):
	return hmac.new(key, data, hash_object).digest()

def hkdf(hash_object, output_size, input_key, salt=b"", data=b""):
	"""Key derivation function"""
	hash_len = hash_object().digest_size
	temp = b""
	output = b""

	if len(salt) == 0:
		salt = bytes([0] * hash_len)
	key_output = hmac_hash(hash_object, salt, input_key)
	for i in range(ceil(output_size / hash_len)):
		temp = hmac_hash(hash_object, key_output, temp + data + bytes([1 + i]))
		output += temp
	return output[:output_size]

if __name__ == '__main__':
	test = hkdf(hashlib.sha512, 24, os.urandom(16))
	print(test.hex())