// PBKDF2 - Password-based key derivation
const password = new TextEncoder().encode("my-password");
const salt = crypto.getRandomValues(new Uint8Array(16));
const baseKey = await crypto.subtle.importKey(
"raw",
password,
"PBKDF2",
false,
["deriveBits", "deriveKey"]
);
const derivedKey = await crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt,
iterations: 100000,
hash: "SHA-256",
},
baseKey,
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
// HKDF - HMAC-based key derivation
const hkdfKey = await crypto.subtle.importKey(
"raw",
crypto.getRandomValues(new Uint8Array(32)),
"HKDF",
false,
["deriveKey"]
);
const derived = await crypto.subtle.deriveKey(
{
name: "HKDF",
salt: crypto.getRandomValues(new Uint8Array(16)),
info: new Uint8Array([1, 2, 3]),
hash: "SHA-256",
},
hkdfKey,
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
// ECDH - Elliptic Curve Diffie-Hellman
const aliceKeyPair = await crypto.subtle.generateKey(
{ name: "ECDH", namedCurve: "P-256" },
true,
["deriveBits"]
);
const bobKeyPair = await crypto.subtle.generateKey(
{ name: "ECDH", namedCurve: "P-256" },
true,
["deriveBits"]
);
const sharedSecret = await crypto.subtle.deriveBits(
{ name: "ECDH", public: bobKeyPair.publicKey },
aliceKeyPair.privateKey,
256
);