Although the answer from @Marcelo Uchimura answers the question, I think it does not answer what the code is for, even mentioning that this would be for messages, where it is not point.
HKDF is a KDF using HMAC, there is a definition of it here . Well, a KDF has as input a "not so random" die and another die, which is uniformly random. A good example of use is when a key is agreed via ECDH, since the key is "mathematical response", so it is not indistinguishable from a completely random data, so the use of KDF is necessary. Similarly, you may want to have multiple keys using only one, so HKDF can also be used, * even if the key requires more bytes than the original value.
The HKDF is divided into two parts, one the extractor and the other the expander. This is the puller:
prk = hmac_sha256(salt, ikm)
The idea here is to include salt
and ikm
. It assumes that salt
is distinguishable from a uniformly random data, since ikm
may be, but need not be.
Its result, prk
, is a uniformly random data, assuming hmac_sha256
is a safe PRF, or that at least SHA256 compression is a PRF.
>
After that we have the expander, which consumes prk
, it is in:
for i in range(ceil(length / hash_len)):
t = hmac_sha256(prk, t + info + bytes([1+i]))
Note that prk
is used as the key in this step. That is, the key generated by the extractor is used in the expander. The expander will create n required bytes, so there is range
to repeat the process until it reaches the required number of bytes.
Formally this process is described as:
K(1) = HMAC(PRK, CTXinfo || 0),
K(i + 1) = HMAC(PRK, K(i) || CTXinfo || i), 1 ≤ i < t,
The CTXinfo
is additional information, can be omitted. So basically the input of the HMAC is: the previous result (if i> 1) concatenated with the information added and concatenated with the i,% being a single byte, sequential.
In the case of this implementation, as defined by i
, there will be no difference between the first or last execution.
Finally, t = b""
will only cut the output, since the hash is fixed size (in the case of SHA-256), so if you want non-multiples of 256, for example, you will not be able to get truncated.