hash_hkdf
hash_hkdf(string $algo, string $key, int $length = 32, string $info = "", string $salt = ""): string
HKDF key derivation (RFC 5869: extract to a pseudorandom key, then expand to length) — pairs with hash_pbkdf2: slow PBKDF2 for passwords, fast HKDF for keys.
C C23
#include <stdio.h>
#include <string.h>
#include "sha256.h" // vendored SHA-256 (Brad Conte, public domain)
// HMAC-SHA256 (RFC 2104)
static void hmac_sha256(const BYTE *key, size_t klen, const BYTE *msg, size_t mlen, BYTE out[32]) {
BYTE k[64] = {0}, ipad[64], opad[64], inner[32];
if (klen > 64) {
SHA256_CTX c;
sha256_init(&c);
sha256_update(&c, key, klen);
sha256_final(&c, k);
} else {
memcpy(k, key, klen);
}
for (int i = 0; i < 64; i++) {
ipad[i] = (BYTE)(k[i] ^ 0x36);
opad[i] = (BYTE)(k[i] ^ 0x5c);
}
SHA256_CTX c;
sha256_init(&c);
sha256_update(&c, ipad, 64);
sha256_update(&c, msg, mlen);
sha256_final(&c, inner);
sha256_init(&c);
sha256_update(&c, opad, 64);
sha256_update(&c, inner, 32);
sha256_final(&c, out);
}
// HKDF (RFC 5869): extract then expand
static void hkdf(const BYTE *ikm, size_t ikmlen,
const BYTE *salt, size_t saltlen,
const BYTE *info, size_t infolen,
BYTE *okm, size_t okmlen) {
BYTE prk[32];
hmac_sha256(salt, saltlen, ikm, ikmlen, prk); // extract: PRK = HMAC(salt, IKM)
BYTE t[32];
size_t tlen = 0, done = 0;
for (int i = 1; done < okmlen; i++) {
BYTE inner[32 + 64];
size_t innerlen = 0;
memcpy(inner, t, tlen); // T(i-1), empty for the first block
innerlen += tlen;
memcpy(inner + innerlen, info, infolen); // info
innerlen += infolen;
inner[innerlen++] = (BYTE)i; // block counter starts at 1
hmac_sha256(prk, 32, inner, innerlen, t);
tlen = 32;
size_t n = okmlen - done < 32 ? okmlen - done : 32;
memcpy(okm + done, t, n);
done += n;
}
}
static void print_hex(const BYTE *p, size_t n) {
for (size_t i = 0; i < n; i++) printf("%02x", p[i]);
printf("\n");
}
int main(void) {
BYTE ikm[22];
memset(ikm, 0x0b, sizeof ikm);
const BYTE salt[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
const BYTE info[] = "context-v1";
BYTE okm[64];
hkdf(ikm, sizeof ikm, salt, sizeof salt, info, sizeof info - 1, okm, 32);
printf("hkdf-32: ");
print_hex(okm, 32);
hkdf(ikm, sizeof ikm, salt, sizeof salt, info, sizeof info - 1, okm, 64);
printf("hkdf-64: ");
print_hex(okm, 64);
BYTE zeros[32] = {0};
hkdf(ikm, sizeof ikm, zeros, 32, (const BYTE *)"", 0, okm, 32);
printf("nosaltinfo-32: ");
print_hex(okm, 32);
return 0;
}
hkdf-32: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715e hkdf-64: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715ee5f5ff2dfc85a4ef267b9ebcde34425d774c3e753ecb85ed3068d15df0f38b6f nosaltinfo-32: 8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d
C++ C++26
#include <cstdio>
#include <cstring>
#include "sha256.h" // vendored SHA-256 (Brad Conte, public domain)
// HMAC-SHA256 (RFC 2104)
static void hmac_sha256(const BYTE *key, size_t klen, const BYTE *msg, size_t mlen, BYTE out[32]) {
BYTE k[64] = {0}, ipad[64], opad[64], inner[32];
if (klen > 64) {
SHA256_CTX c;
sha256_init(&c);
sha256_update(&c, key, klen);
sha256_final(&c, k);
} else {
memcpy(k, key, klen);
}
for (int i = 0; i < 64; i++) {
ipad[i] = (BYTE)(k[i] ^ 0x36);
opad[i] = (BYTE)(k[i] ^ 0x5c);
}
SHA256_CTX c;
sha256_init(&c);
sha256_update(&c, ipad, 64);
sha256_update(&c, msg, mlen);
sha256_final(&c, inner);
sha256_init(&c);
sha256_update(&c, opad, 64);
sha256_update(&c, inner, 32);
sha256_final(&c, out);
}
// HKDF (RFC 5869): extract then expand
static void hkdf(const BYTE *ikm, size_t ikmlen,
const BYTE *salt, size_t saltlen,
const BYTE *info, size_t infolen,
BYTE *okm, size_t okmlen) {
BYTE prk[32];
hmac_sha256(salt, saltlen, ikm, ikmlen, prk); // extract: PRK = HMAC(salt, IKM)
BYTE t[32];
size_t tlen = 0, done = 0;
for (int i = 1; done < okmlen; i++) {
BYTE inner[32 + 64];
size_t innerlen = 0;
memcpy(inner, t, tlen); // T(i-1), empty for the first block
innerlen += tlen;
memcpy(inner + innerlen, info, infolen); // info
innerlen += infolen;
inner[innerlen++] = (BYTE)i; // block counter starts at 1
hmac_sha256(prk, 32, inner, innerlen, t);
tlen = 32;
size_t n = okmlen - done < 32 ? okmlen - done : 32;
memcpy(okm + done, t, n);
done += n;
}
}
static void print_hex(const BYTE *p, size_t n) {
for (size_t i = 0; i < n; i++) printf("%02x", p[i]);
printf("\n");
}
int main() {
BYTE ikm[22];
memset(ikm, 0x0b, sizeof ikm);
const BYTE salt[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
const BYTE info[] = "context-v1";
BYTE okm[64];
hkdf(ikm, sizeof ikm, salt, sizeof salt, info, sizeof info - 1, okm, 32);
printf("hkdf-32: ");
print_hex(okm, 32);
hkdf(ikm, sizeof ikm, salt, sizeof salt, info, sizeof info - 1, okm, 64);
printf("hkdf-64: ");
print_hex(okm, 64);
BYTE zeros[32] = {0};
hkdf(ikm, sizeof ikm, zeros, 32, (const BYTE *)"", 0, okm, 32);
printf("nosaltinfo-32: ");
print_hex(okm, 32);
return 0;
}
hkdf-32: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715e hkdf-64: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715ee5f5ff2dfc85a4ef267b9ebcde34425d774c3e753ecb85ed3068d15df0f38b6f nosaltinfo-32: 8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d
C# v11.0.100
using System;
using System.Linq;
using System.Security.Cryptography;
byte[] ikm = Enumerable.Repeat((byte)0x0b, 22).ToArray();
byte[] salt = Enumerable.Range(0, 13).Select(i => (byte)i).ToArray();
byte[] info = System.Text.Encoding.ASCII.GetBytes("context-v1");
// HKDF is native since .NET 5 — no hand-rolled HMAC needed
byte[] okm32 = HKDF.DeriveKey(HashAlgorithmName.SHA256, ikm, 32, salt, info);
Console.WriteLine($"hkdf-32: {Convert.ToHexString(okm32).ToLower()}");
byte[] okm64 = HKDF.DeriveKey(HashAlgorithmName.SHA256, ikm, 64, salt, info);
Console.WriteLine($"hkdf-64: {Convert.ToHexString(okm64).ToLower()}");
// no salt / no info
byte[] okmPlain = HKDF.DeriveKey(HashAlgorithmName.SHA256, ikm, 32);
Console.WriteLine($"nosaltinfo-32: {Convert.ToHexString(okmPlain).ToLower()}");
hkdf-32: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715e hkdf-64: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715ee5f5ff2dfc85a4ef267b9ebcde34425d774c3e753ecb85ed3068d15df0f38b6f nosaltinfo-32: 8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d
Go v1.27.4
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"golang.org/x/crypto/hkdf"
)
func main() {
ikm := bytes.Repeat([]byte{0x0b}, 22)
salt, _ := hex.DecodeString("000102030405060708090a0b0c")
info := []byte("context-v1")
out := make([]byte, 32)
io.ReadFull(hkdf.New(sha256.New, ikm, salt, info), out) // extract + expand in one reader
fmt.Println("hkdf-32:", hex.EncodeToString(out))
out64 := make([]byte, 64)
io.ReadFull(hkdf.New(sha256.New, ikm, salt, info), out64)
fmt.Println("hkdf-64:", hex.EncodeToString(out64))
// no salt / no info: pass nil for both, equivalent to HashLen zero bytes of salt
plain := make([]byte, 32)
io.ReadFull(hkdf.New(sha256.New, ikm, nil, nil), plain)
fmt.Println("nosaltinfo-32:", hex.EncodeToString(plain))
}
hkdf-32: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715e hkdf-64: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715ee5f5ff2dfc85a4ef267b9ebcde34425d774c3e753ecb85ed3068d15df0f38b6f nosaltinfo-32: 8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d
Java v27.0.1
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class Main {
static byte[] hmacSha256(byte[] key, byte[] msg) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return mac.doFinal(msg);
}
// HKDF (RFC 5869): extract then expand, built from HMAC-SHA256
static byte[] hkdf(byte[] ikm, byte[] salt, byte[] info, int length) throws Exception {
byte[] prk = hmacSha256(salt, ikm); // extract: PRK = HMAC(salt, IKM)
byte[] okm = new byte[length];
byte[] t = new byte[0];
int done = 0;
for (int i = 1; done < length; i++) {
byte[] msg = new byte[t.length + info.length + 1];
System.arraycopy(t, 0, msg, 0, t.length);
System.arraycopy(info, 0, msg, t.length, info.length);
msg[msg.length - 1] = (byte) i;
t = hmacSha256(prk, msg);
int n = Math.min(32, length - done);
System.arraycopy(t, 0, okm, done, n);
done += n;
}
return okm;
}
public static void main(String[] args) throws Exception {
byte[] ikm = new byte[22];
java.util.Arrays.fill(ikm, (byte) 0x0b);
byte[] salt = HexFormat.of().parseHex("000102030405060708090a0b0c");
byte[] info = "context-v1".getBytes(StandardCharsets.UTF_8);
System.out.println("hkdf-32: " + HexFormat.of().formatHex(hkdf(ikm, salt, info, 32)));
System.out.println("hkdf-64: " + HexFormat.of().formatHex(hkdf(ikm, salt, info, 64)));
// no salt: RFC 5869 says a not-provided salt means HashLen zero bytes
byte[] zeros = new byte[32];
System.out.println("nosaltinfo-32: " + HexFormat.of().formatHex(hkdf(ikm, zeros, new byte[0], 32)));
}
}
hkdf-32: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715e hkdf-64: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715ee5f5ff2dfc85a4ef267b9ebcde34425d774c3e753ecb85ed3068d15df0f38b6f nosaltinfo-32: 8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d
JavaScript v26.13.1
// crypto.hkdfSync: HKDF built into the standard library
const crypto = require("node:crypto");
const ikm = Buffer.from("0b".repeat(22), "hex");
const salt = Buffer.from("000102030405060708090a0b0c", "hex");
const info = Buffer.from("context-v1");
console.log("hkdf-32:", Buffer.from(crypto.hkdfSync("sha256", ikm, salt, info, 32)).toString("hex"));
console.log("hkdf-64:", Buffer.from(crypto.hkdfSync("sha256", ikm, salt, info, 64)).toString("hex"));
// no salt / no info: both default to empty, equivalent to a zero salt of HashLen
console.log("nosaltinfo-32:", Buffer.from(crypto.hkdfSync("sha256", ikm, Buffer.alloc(0), Buffer.alloc(0), 32)).toString("hex"));
hkdf-32: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715e hkdf-64: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715ee5f5ff2dfc85a4ef267b9ebcde34425d774c3e753ecb85ed3068d15df0f38b6f nosaltinfo-32: 8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d
PHP v8.6.0
// hash_hkdf: RFC 5869 key derivation (extract + expand) on HMAC-SHA256.
// Fixed ikm/salt/info make the output deterministic for comparison across languages.
$ikm = str_repeat("\x0b", 22); // input keying material (demo vector style)
$salt = hex2bin("000102030405060708090a0b0c");
$info = "context-v1"; // binds the derived key to a purpose (protocol / version)
// note the parameter order: algo, ikm, length, info, salt — info comes BEFORE salt
echo "hkdf-32: ", bin2hex(hash_hkdf("sha256", $ikm, 32, $info, $salt)), "\n";
// expand loops into a second HMAC block once the output passes 32 bytes
echo "hkdf-64: ", bin2hex(hash_hkdf("sha256", $ikm, 64, $info, $salt)), "\n";
// no salt/info: the salt defaults to a string of HashLen zeros (RFC 5869)
echo "nosaltinfo-32: ", bin2hex(hash_hkdf("sha256", $ikm, 32)), "\n";
hkdf-32: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715e hkdf-64: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715ee5f5ff2dfc85a4ef267b9ebcde34425d774c3e753ecb85ed3068d15df0f38b6f nosaltinfo-32: 8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d
Python v3.15.2
import hashlib
import hmac
# HKDF (RFC 5869) on the standard library: extract then expand
ikm = b"\x0b" * 22
salt = bytes(range(13))
info = b"context-v1"
def hkdf(ikm, salt, info, length):
# extract: PRK = HMAC-SHA256(salt, IKM); no salt means HashLen zero bytes
prk = hmac.new(salt if salt else b"\x00" * 32, ikm, hashlib.sha256).digest()
# expand: T(i) = HMAC(PRK, T(i-1) || info || i)
okm, t, i = b"", b"", 1
while len(okm) < length:
t = hmac.new(prk, t + info + bytes([i]), hashlib.sha256).digest()
okm += t
i += 1
return okm[:length]
print("hkdf-32:", hkdf(ikm, salt, info, 32).hex())
print("hkdf-64:", hkdf(ikm, salt, info, 64).hex())
print("nosaltinfo-32:", hkdf(ikm, b"", b"", 32).hex())
hkdf-32: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715e hkdf-64: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715ee5f5ff2dfc85a4ef267b9ebcde34425d774c3e753ecb85ed3068d15df0f38b6f nosaltinfo-32: 8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d
Rust v1.99.1
use sha2::{Digest, Sha256};
// HKDF-SHA256 (RFC 5869): hand-rolled HMAC on the sha2 crate, like the PBKDF2 entry
fn hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{:02x}", x)).collect()
}
fn hmac_sha256(key: &[u8], msg: &[u8]) -> [u8; 32] {
let mut k = [0u8; 64];
if key.len() > 64 {
k[..32].copy_from_slice(&Sha256::digest(key));
} else {
k[..key.len()].copy_from_slice(key);
}
let mut inner = Sha256::new();
for b in k.iter() {
inner.update([b ^ 0x36]);
}
inner.update(msg);
let ih = inner.finalize();
let mut outer = Sha256::new();
for b in k.iter() {
outer.update([b ^ 0x5c]);
}
outer.update(ih);
outer.finalize().into()
}
fn hkdf(ikm: &[u8], salt: &[u8], info: &[u8], len: usize) -> Vec<u8> {
let prk = hmac_sha256(salt, ikm); // extract: PRK = HMAC(salt, IKM)
let mut okm = Vec::new();
let mut t: Vec<u8> = Vec::new();
let mut i = 1u8;
while okm.len() < len {
// expand: T(i) = HMAC(PRK, T(i-1) || info || i)
let mut msg = t.clone();
msg.extend_from_slice(info);
msg.push(i);
t = hmac_sha256(&prk, &msg).to_vec();
okm.extend_from_slice(&t);
i += 1;
}
okm.truncate(len);
okm
}
fn main() {
let ikm = [0x0bu8; 22];
let salt = [0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let info = b"context-v1";
println!("hkdf-32: {}", hex(&hkdf(&ikm, &salt, info, 32)));
println!("hkdf-64: {}", hex(&hkdf(&ikm, &salt, info, 64)));
// no salt / no info: HashLen zero bytes of salt per RFC 5869
println!("nosaltinfo-32: {}", hex(&hkdf(&ikm, &[0u8; 32], b"", 32)));
}
hkdf-32: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715e hkdf-64: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715ee5f5ff2dfc85a4ef267b9ebcde34425d774c3e753ecb85ed3068d15df0f38b6f nosaltinfo-32: 8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d
TypeScript v26.13.1
// crypto.hkdfSync: HKDF built into the standard library
import { hkdfSync } from "node:crypto";
const ikm = Buffer.from("0b".repeat(22), "hex");
const salt = Buffer.from("000102030405060708090a0b0c", "hex");
const info = Buffer.from("context-v1");
console.log("hkdf-32:", Buffer.from(hkdfSync("sha256", ikm, salt, info, 32)).toString("hex"));
console.log("hkdf-64:", Buffer.from(hkdfSync("sha256", ikm, salt, info, 64)).toString("hex"));
// no salt / no info: both default to empty, equivalent to a zero salt of HashLen
console.log("nosaltinfo-32:", Buffer.from(hkdfSync("sha256", ikm, Buffer.alloc(0), Buffer.alloc(0), 32)).toString("hex"));
hkdf-32: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715e hkdf-64: 5d7ce091457d5c55a679222e7fa9b8a52b343603ee788e7d78bcf5c383b1715ee5f5ff2dfc85a4ef267b9ebcde34425d774c3e753ecb85ed3068d15df0f38b6f nosaltinfo-32: 8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d
Language differences
Batch special: the hash extension runs at full strength on CI — real-function demo with deterministic preset output (same inputs always derive the same key).
C: no KDF in the standard library — the example hand-writes HMAC+HKDF over the bundled vendor sha256; real code uses OpenSSL PKCS5_PBKDF2_HMAC or libsodium crypto_kdf.
C++: same hand-rolled approach as C; real work uses OpenSSL EVP_PKEY-HKDF or libsodium.
C#: HKDF.DeriveKey (native since .NET 5) — one of the first mainstream platforms with a built-in HKDF.
Go: golang.org/x/crypto/hkdf — hkdf.New(hash, ikm, salt, info) returns an io.Reader; io.ReadFull pulls the requested length.
Java: no native HKDF in the JDK — the example hand-writes it with Mac HmacSHA256; production options include BouncyCastle HKDFBytesGenerator.
JavaScript: crypto.hkdfSync(digest, ikm, salt, info, keylen) (Node 15+); WebCrypto has no HKDF, hand-roll or pull a library.
PHP: the parameter order is (algo, ikm, length, info, salt) — info comes BEFORE salt, against intuition; with no salt, RFC-mandated HashLen zeros apply. The derived output is binary, compare after hex/bin2hex.
Python: hmac + hashlib from the standard library write the extract/expand stages directly; the cryptography package also ships HKDF.
Rust: no KDF in the standard library — the example hand-writes HMAC over the sha2 crate (same approach as the PBKDF2 entry).
TypeScript: same as JavaScript. The usage split (core teaching point): PBKDF2 (see the hash_pbkdf2 entry) is a SLOW hash that stretches low-entropy passwords against brute force; HKDF is a FAST hash that expands already-entropic key material into more keys (e.g. TLS session keys after the handshake) — use HKDF when the input is a key, PBKDF2 when the input is a password.