Getting to know HKDF

March 18, 2021

HKDF is one of the algorithms used within the Cryptography Specification of the Exposure Notification system created by Google and Apple that lies at the heart of the Covid-19 contact tracing applications NearForm and others have produced to help slow the spread of the virus. You can also find HKDF buried in the internals of the new QUIC protocol TLS 1.3 handshake, at the heart of the new Hybrid Public Key Encryption (HPKE) scheme, as a component of several evolving distributed identity frameworks and in many other systems... Read more:

import { webcrypto } from 'crypto';
const { subtle, getRandomValues } = webcrypto;

// First set up our initial key
const key = await subtle.importKey(
  Buffer.from('initial key'),
  { name: 'HKDF' },
  ['deriveKey', 'deriveBits']);

// Then, perform the HKDF Extract and Expand
const out = await subtle.deriveBits(
    name: 'HKDF',
    info: 'the info',
    salt: getRandomValues(new Uint8Array(16)),
    hash: 'SHA-256'
  128);  // 16 bytes
const { hkdf, hkdfSync } = require('crypto');

hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
  if (err) throw err;
  console.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'

const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
console.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'