Web Crypto: deriveKey

This page shows how to use the deriveKey() function of the Web Crypto API. It contains three separate examples: one for PBKDF2, one for ECDH, and one for HKDF.

Although alll three algorithms are defined in the API as key derivation functions, they have very different use cases and characteristics.


PBKDF2 example

The PBKDF2 algorithm is used here to derive a secret key from a password.

When you click "Encrypt" the example prompts you for a password and then derives an AES key from the password using PBKDF2. It then uses that key to encrypt the message, and writes a representation of the ciphertext into the "Ciphertext" output.

When you click "Decrypt" the example prompts you for the password and derives an AES key from the password using PBKDF2. It then uses that key to decrypt the ciphertext, and writes a representation of the decrypted message into the "Decrypted" output.

If the "Decrypt" password doesn't match the original, decryption will fail and an error is shown.


ECDH example

The ECDH algorithm is more commonly called a "key agreement" algorithm. It enables two parties (conventionally called "Alice" and "Bob"), each of whom has a public/private key pair, to establish a shared secret key.

With this example we've created two key pairs, one for Alice and one for Bob. Alice derives an AES key using her private key and Bob's public key. Bob independently derives the same key using his private key and Alice's public key.

When you click "Encrypt" the example uses Alice's copy of the key to encrypt a message for Bob.

When you click "Decrypt" the example uses Bob's copy of the key to decrypt the message.


HKDF example

The HKDF algorithm is used to derive a key from some relatively high-entropy input, such as a secret agreed using ECDH. So for example, it could be used to derive multiple encryption keys from a single ECDH secret.

When the page loads, we use ECDH to derive a shared secret.

When you click "Encrypt" the example uses HKDF to derive an AES encryption key from the shared secret, and uses it to encrypt the message.

When you click "Decrypt" the example uses HKDF to derive the same AES encryption key from the shared secret, and uses it to decrypt the message.

PBKDF2

Ciphertext:
Decrypted:

ECDH

Ciphertext:
Decrypted:

HKDF

Ciphertext:
Decrypted: