SubtleCrypto: generateKey() method
Use the generateKey()
method of the SubtleCrypto
interface to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms).
Syntax
generateKey(algorithm, extractable, keyUsages)
Parameters
-
algorithm
-
An object defining the type of key to generate and providing extra algorithm-specific parameters.
-
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 newly generated key. Possible values for array elements 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
.
Return value
A Promise
that fulfills with a CryptoKey
(for symmetric algorithms) or a CryptoKeyPair
(for public-key algorithms).
Exceptions
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.
Examples
RSA key pair generation
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"],
);
Elliptic curve key pair generation
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"],
);
HMAC key generation
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"],
);
AES key generation
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"],
);
Specifications
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
generateKey |
37 |
79
12–79["Not supported: RSA-PSS, ECDSA, ECDH.", "Not supported: AES-CTR."]
|
34 |
11Returns KeyOperation instead of Promise
|
24 |
7 |
37 |
37 |
34 |
24 |
7 |
3.0 |
See also