Use the generateKey()
method of the SubtleCrypto
interface to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms).
generateKey(algorithm, extractable, keyUsages)
A Promise
that fulfills with a CryptoKey
(for symmetric algorithms) or a CryptoKeyPair
(for public-key algorithms).
The promise is rejected when the following exception is encountered:
-
SyntaxError
DOMException
-
Raised when the result is a CryptoKey
of type secret
or private
but keyUsages
is empty.
-
SyntaxError
DOMException
-
Raised when the result is a CryptoKeyPair
and its privateKey.usages
attribute is empty.
This code generates an RSA-OAEP encryption key pair. See the complete code on GitHub.
let keyPair = await window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 4096,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256",
},
true,
["encrypt", "decrypt"],
);
This code generates an ECDSA signing key pair. See the complete code on GitHub.
let keyPair = await window.crypto.subtle.generateKey(
{
name: "ECDSA",
namedCurve: "P-384",
},
true,
["sign", "verify"],
);
This code generates an HMAC signing key. See the complete code on GitHub.
let key = await window.crypto.subtle.generateKey(
{
name: "HMAC",
hash: { name: "SHA-512" },
},
true,
["sign", "verify"],
);
This code generates an AES-GCM encryption key. See the complete code on GitHub.
let key = await window.crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256,
},
true,
["encrypt", "decrypt"],
);