The deriveKey()
method of the SubtleCrypto
interface can be used to derive a secret key from a master key.
It takes as arguments some initial key material, the derivation algorithm to use, and the desired properties for the key to derive. It returns a Promise
which will be fulfilled with a CryptoKey
object representing the new key.
It's worth noting that the three key derivation algorithms you can use have quite different characteristics and are appropriate in quite different situations. See Supported algorithms for some more detail on this.
deriveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)
A Promise
that fulfills with a CryptoKey
.
The promise is rejected when one of the following exceptions are encountered:
-
InvalidAccessError
DOMException
-
Raised when the master key is not a key for the requested derivation algorithm or if the keyUsages
value of that key doesn't contain deriveKey
.
-
NotSupported
DOMException
-
Raised when trying to use an algorithm that is either unknown or isn't suitable for derivation, or if the algorithm requested for the derived key doesn't define a key length.
-
SyntaxError
DOMException
-
Raised when keyUsages
is empty but the unwrapped key is of type secret
or private
.
The three algorithms supported by deriveKey()
have quite different characteristics and are appropriate in different situations.
ECDH (Elliptic Curve Diffie-Hellman) is a key-agreement algorithm. It enables two people who each have an ECDH public/private key pair to generate a shared secret: that is, a secret that they — and no one else — share. They can then use this shared secret as a symmetric key to secure their communication, or can use the secret as an input to derive such a key (for example, using the HKDF algorithm).
ECDH is specified in RFC 6090.
HKDF is a key derivation function. It's designed to derive key material from some high-entropy input, such as the output of an ECDH key agreement operation.
It's not designed to derive keys from relatively low-entropy inputs such as passwords. For that, use PBKDF2.
HKDF is specified in RFC 5869.
PBKDF2 is also a key derivation function. It's designed to derive key material from some relatively low-entropy input, such as a password. It derives key material by applying a function such as HMAC to the input password along with some salt, and repeating this process many times. The more times the process is repeated, the more computationally expensive key derivation is: this makes it harder for an attacker to use brute-force to discover the key using a dictionary attack.
PBKDF2 is specified in RFC 2898.
In this example Alice and Bob each generate an ECDH key pair, then exchange public keys. They then use deriveKey()
to derive a shared AES key, that they could use to encrypt messages. See the complete code on GitHub.
function deriveSecretKey(privateKey, publicKey) {
return window.crypto.subtle.deriveKey(
{
name: "ECDH",
public: publicKey
},
privateKey,
{
name: "AES-GCM",
length: 256
},
false,
["encrypt", "decrypt"]
);
}
async function agreeSharedSecretKey() {
let alicesKeyPair = await window.crypto.subtle.generateKey(
{
name: "ECDH",
namedCurve: "P-384"
},
false,
["deriveKey"]
);
let bobsKeyPair = await window.crypto.subtle.generateKey(
{
name: "ECDH",
namedCurve: "P-384"
},
false,
["deriveKey"]
);
let alicesSecretKey = await deriveSecretKey(alicesKeyPair.privateKey, bobsKeyPair.publicKey);
let bobsSecretKey = await deriveSecretKey(bobsKeyPair.privateKey, alicesKeyPair.publicKey);
let encryptButton = document.querySelector(".ecdh .encrypt-button");
encryptButton.addEventListener("click", () => {
encrypt(alicesSecretKey);
});
let decryptButton = document.querySelector(".ecdh .decrypt-button");
decryptButton.addEventListener("click", () => {
decrypt(bobsSecretKey);
});
}
In this example we ask the user for a password, then use it to derive an AES key using PBKDF2, then use the AES key to encrypt a message. See the complete code on GitHub.
function getKeyMaterial() {
let password = window.prompt("Enter your password");
let enc = new TextEncoder();
return window.crypto.subtle.importKey(
"raw",
enc.encode(password),
"PBKDF2",
false,
["deriveBits", "deriveKey"]
);
}
async function encrypt(plaintext, salt, iv) {
let keyMaterial = await getKeyMaterial();
let key = await window.crypto.subtle.deriveKey(
{
"name": "PBKDF2",
salt: salt,
"iterations": 100000,
"hash": "SHA-256"
},
keyMaterial,
{ "name": "AES-GCM", "length": 256},
true,
[ "encrypt", "decrypt" ]
);
return window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: iv
},
key,
plaintext
);
}