HKDF with Node.jsHMAC Key Derivation function (HKDF) is used to derive an encryption key from initial key material (IKM). With HKDF we use a given hashing method to the bases of the function, such as with SHA-512. With this, HKDF creates a pseudorandom key (PRK) using an IKM and a salt value in order to produce an HMAC hash function (such as HMAC-SHA256). This PRK output is used to produce a key of the required length. Next the PRK output is used to produce a key of the required length. If we generate a 16-byte output (32 hex characters), we have a 128-bit key, and a 32-byte output (64 hex characters) will generate a 256-bit key. HKDF is used in TLS 1.3 for generating encryption keys [RFC 5869][article]. In this case we use the IKM as the input keying material and a salt value. From this we compute the pseudo random key (PRK) with HMAC-Hash(salt, IKM) and the OKM (output keying material) with HKDF-Expand(PRK, info, L), and where L is the length, and info is additional information. The PRK is a fixed length hash, whereas the OKM can be used to create any length of a pseudo random value. 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. |
Coding
The code is:
const crypto = require("crypto"); var hash="sha256"; var pass="hello"; var salt="secp256k1"; var size=16; var args = process.argv; if (args.length>2) pass=args[2]; if (args.length>3) hash=args[3]; if (args.length>4) salt=args[4]; if (args.length>5) size=parseInt(args[5]); const Key = crypto.hkdfSync(hash, pass, salt, '', size); console.log("Initial key material: ",pass); console.log("Hash: ",hash); console.log("Salt: ",salt); console.log("Size: ",size); console.log("\nKey: ",Buffer.from(Key).toString('hex')); console.log("Key: ",Buffer.from(Key).toString('Base64'));
A sample run:
Initial key material: Test Hash: blake2s256 Salt: salt1234 Size: 32 Key: 3eae28c470266ab84ddb4cfcd880304cfa67e94b40a9ec94783fd97f21efedf2 Key: Pq4oxHAmarhN20z82IAwTPpn6UtAqeyUeD/ZfyHv7fI=