Photo by Everyday basics on Unsplash

HMAC-SHA256 and Rust

--

So how do we create an encryption key from a password? Well, the wrong answer is to hash a password, as this is insecure. The correct way is to use a Key Derivation Function (KDF) and one of the most popular is HMAC Key Derivation function (HKDF). With this we derive our random key from a given hashing method such as SHA-1, SHA-256 and SHA-512. Into this we add a salt value and some extra information. In practice, though, we use HMAC-SHA256 not for password hashing, but for generating encryption keys based on a shared secret, such as within a Diffie-Hellman key exchange.

Initially, HKDF creates a pseudorandom key (PRK) using initial key material (IKM) and a salt value in order to produce an HMAC hash function (such as HMAC-SHA256). Next, the PRK output is used to produce a key of a required length — this is output is known as the OKM (output keying material). If we generate a 16-byte output (32 hex characters), we will have a 128-bit encryption key, and a 32-byte output (64 hex characters) gives us a 256-bit encryption key. HKDF has many applications such as in TLS 1.3 for generating encryption keys [RFC 5869][article].

Implementing with Rust

In this case we use the IKM as the input keying material and a salt value. From this, we will compute the PRK from the HMAC-Hash(salt, IKM) function and the OKM from the HKDF-Expand(PRK, info, L)

--

--

Prof Bill Buchanan OBE FRSE
ASecuritySite: When Bob Met Alice

Professor of Cryptography. Serial innovator. Believer in fairness, justice & freedom. Based in Edinburgh. Old World Breaker. New World Creator. Building trust.