Baseline Widely available *
Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
Note: This feature is available in Web Workers.
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 supported key derivation algorithms have quite different characteristics and are appropriate in quite different situations. See Supported algorithms for some more detail on this.
SyntaxderiveKey(algorithm, baseKey, derivedKeyAlgorithm, extractable, keyUsages)
Parameters
algorithm
An object defining the derivation algorithm to use.
EcdhKeyDeriveParams
object, specifying the string ECDH
as the name
property.HkdfParams
object.Pbkdf2Params
object.EcdhKeyDeriveParams
object, specifying the string X25519
as the name
property.baseKey
A CryptoKey
representing the input to the derivation algorithm. If algorithm
is ECDH or X25519, then this will be the ECDH or X25519 private key. Otherwise it will be the initial key material for the derivation function: for example, for PBKDF2 it might be a password, imported as a CryptoKey
using SubtleCrypto.importKey()
.
derivedKeyAlgorithm
An object defining the algorithm the derived key will be used for:
HmacKeyGenParams
object.AesKeyGenParams
object.HkdfParams
object.Pbkdf2Params
object.A boolean value indicating whether it will be possible to export the key using SubtleCrypto.exportKey()
or SubtleCrypto.wrapKey()
.
keyUsages
An Array
indicating what can be done with the derived key. Note that the key usages must be allowed by the algorithm set in derivedKeyAlgorithm
. Possible values of the array are:
encrypt
: The key may be used to encrypt messages.decrypt
: The key may be used to decrypt messages.sign
: The key may be used to sign messages.verify
: The key may be used to verify signatures.deriveKey
: The key may be used in deriving a new key.deriveBits
: The key may be used in deriving bits.wrapKey
: The key may be used to wrap a key.unwrapKey
: The key may be used to unwrap a key.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 algorithms supported by deriveKey()
have quite different characteristics and are appropriate in different situations.
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.
PBKDF2PBKDF2 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.
Key agreement algorithms ECDHECDH (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.
X25519X25519 is a key agreement algorithm like ECDH, but built on the Curve25519 elliptic curve, which is part of the Edwards-Curve Digital Signature Algorithm (EdDSA) family of algorithms defined in RFC 8032.
The Curve25519 algorithms are widely used in cryptography, and are considered to be some of the most efficient/fast available. By comparison with the NIST (National Institute of Standards and Technology) curve key exchange algorithms used with ECDH, Curve25519 is simpler to implement, and its non-governmental origin means that the decisions behind its design choices are transparent and open.
X25519 is specified in RFC 7748.
ExamplesNote: You can try the working examples on GitHub.
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.
/*
Derive an AES key, given:
- our ECDH private key
- their ECDH public key
*/
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() {
// Generate 2 ECDH key pairs: one for Alice and one for Bob
// In more normal usage, they would generate their key pairs
// separately and exchange public keys securely
let aliceKeyPair = await window.crypto.subtle.generateKey(
{
name: "ECDH",
namedCurve: "P-384",
},
false,
["deriveKey"],
);
let bobKeyPair = await window.crypto.subtle.generateKey(
{
name: "ECDH",
namedCurve: "P-384",
},
false,
["deriveKey"],
);
// Alice then generates a secret key using her private key and Bob's public key.
let aliceSecretKey = await deriveSecretKey(
aliceKeyPair.privateKey,
bobKeyPair.publicKey,
);
// Bob generates the same secret key using his private key and Alice's public key.
let bobSecretKey = await deriveSecretKey(
bobKeyPair.privateKey,
aliceKeyPair.publicKey,
);
// Alice can then use her copy of the secret key to encrypt a message to Bob.
let encryptButton = document.querySelector(".ecdh .encrypt-button");
encryptButton.addEventListener("click", () => {
encrypt(aliceSecretKey);
});
// Bob can use his copy to decrypt the message.
let decryptButton = document.querySelector(".ecdh .decrypt-button");
decryptButton.addEventListener("click", () => {
decrypt(bobSecretKey);
});
}
In this example Alice and Bob each generate an X25519 key pair, then exchange public keys. They then each use deriveKey()
to derive a shared AES key from their own private key and each other's public key. They can use this shared key to encrypt and decrypt messages they exchange.
First we define an HTML <input>
that you will use to enter the plaintext message that "Alice" will send, and a button that you can click to start the encryption process.
This is followed by another two elements for displaying the ciphertext after Alice has encrypted the plaintext with her copy of the secret key, and for displaying the text after Bob has decrypted it with his copy of the secret key.
JavaScriptThe code below shows how we use deriveKey()
. We pass in the remote party's X25519 public key, the local party's X25519 private key, and specify that the derived key should be an AES-GCM key. We also set the derived key to be non-extractable, and suitable for encryption and decryption.
We use this function further down in the code to create shared keys for Bob and Alice.
Next we define the functions that Alice will use to UTF-8 encode and then encrypt her plaintext message, and that Bob will use to decrypt and then decode the message. They both take as arguments the shared AES key, an initialization vector, and the text to be encrypted or decrypted.
The same initialization vector must be used for encryption and decryption, but it does not need to be secret, so usually it is sent alongside the encrypted message. In this case, though, since we're not actually sending a message, we just make it directly available.
The agreeSharedSecretKey()
function below is called on loading to generate pairs and shared keys for Alice and Bob. It also adds a click handler for the "Encrypt" button that will trigger encryption and then decryption of the text defined in the first <input>
. Note that all the code is inside a try...catch
handler, to ensure that we can log the case where key generation fails because the X25519 algorithm is not supported.
Press the Encrypt button to encrypt the text in the top <input>
element, displaying the encrypted ciphertext and decrypted ciphertext in the following two elements. The log area at the bottom provides information about the keys that are generated by the code.
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.
/*
Get some key material to use as input to the deriveKey method.
The key material is a password supplied by the user.
*/
function getKeyMaterial() {
const password = window.prompt("Enter your password");
const enc = new TextEncoder();
return window.crypto.subtle.importKey(
"raw",
enc.encode(password),
"PBKDF2",
false,
["deriveBits", "deriveKey"],
);
}
async function encrypt(plaintext, salt, iv) {
const keyMaterial = await getKeyMaterial();
const key = await window.crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt,
iterations: 100000,
hash: "SHA-256",
},
keyMaterial,
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"],
);
return window.crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, plaintext);
}
In this example, we encrypt a message plainText
given a shared secret secret
, which might itself have been derived using an algorithm such as ECDH. Instead of using the shared secret directly, we use it as key material for the HKDF function, to derive an AES-GCM encryption key, which we then use to encrypt the message. See the complete code on GitHub.
/*
Given some key material and some random salt,
derive an AES-GCM key using HKDF.
*/
function getKey(keyMaterial, salt) {
return window.crypto.subtle.deriveKey(
{
name: "HKDF",
salt,
info: new TextEncoder().encode("Encryption example"),
hash: "SHA-256",
},
keyMaterial,
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"],
);
}
async function encrypt(secret, plainText) {
const message = {
salt: window.crypto.getRandomValues(new Uint8Array(16)),
iv: window.crypto.getRandomValues(new Uint8Array(12)),
};
const key = await getKey(secret, message.salt);
message.ciphertext = await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: message.iv,
},
key,
plainText,
);
return message;
}
Specifications Browser compatibility See also
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4