HKDF Key Derivation With Web Crypto
Derive AES-GCM keys or raw bytes from a shared secret with HKDF-SHA-256, an explicit salt and context-specific info strings.
Code
function assertSecret(secret: string): void {
if (typeof secret !== "string" || secret.length === 0) {
throw new TypeError("secret must be a non-empty string");
}
}
export async function deriveAesKey(
secret: string,
salt: Uint8Array,
info: string,
): Promise<CryptoKey> {
assertSecret(secret);
if (!(salt instanceof Uint8Array)) throw new TypeError("salt must be a Uint8Array");
if (typeof info !== "string") throw new TypeError("info must be a string");
const material = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(secret),
"HKDF",
false,
["deriveKey"],
);
return crypto.subtle.deriveKey(
{ name: "HKDF", hash: "SHA-256", salt, info: new TextEncoder().encode(info) },
material,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"],
);
}
export async function deriveBytes(
secret: string,
salt: Uint8Array,
info: string,
length = 32,
): Promise<Uint8Array> {
assertSecret(secret);
if (!(salt instanceof Uint8Array)) throw new TypeError("salt must be a Uint8Array");
if (typeof info !== "string") throw new TypeError("info must be a string");
if (!Number.isInteger(length) || length < 1 || length > 255) {
throw new RangeError("length must be an integer between 1 and 255");
}
const material = await crypto.subtle.importKey(
"raw",
new TextEncoder().encode(secret),
"HKDF",
false,
["deriveBits"],
);
const bits = await crypto.subtle.deriveBits(
{ name: "HKDF", hash: "SHA-256", salt, info: new TextEncoder().encode(info) },
material,
length * 8,
);
return new Uint8Array(bits);
}How the snippet works
Everything happens inside the functions assertSecret, deriveAesKey and deriveBytes.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. A guard precedes the TypeError and RangeError: bad state stops the flow there instead of continuing.
The result is a fresh construction, so callers can keep their originals.
Caveats
- The snippet leans on
crypto— browser-only surfaces a bare Node process cannot provide. - The guard
typeof secret !== "string" || secret.length === 0short-circuits the flow with an earlythrowwhen its condition holds.
Using it
Entry signature: export async function deriveAesKey( secret: string, salt: Uint8Array, info: string, )
Import deriveAesKey from the file and call it — the rest of the code is implementation detail.
Key statements
if (!(salt instanceof Uint8Array)) throw new TypeError("salt must be a Uint8Array");
if (typeof info !== "string") throw new TypeError("info must be a string");
throw new RangeError("length must be an integer between 1 and 255");
Interactive Tools for This Topic
FAQ
- Does `deriveAesKey` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- How does the snippet fail?
- Validation comes first — `TypeError` and `RangeError` marks the failure at `typeof secret !== "string" || secret.length === 0`, before any partial work happens.
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. The file defines `assertSecret`, `deriveAesKey`, `deriveBytes` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.