Node.js provides an implementation of the standard Web Crypto API.
Use require('node:crypto').webcrypto to access this module.
require('node:crypto').webcrypto
const { subtle } = require('node:crypto').webcrypto;\n\n(async function() {\n\n const key = await subtle.generateKey({\n name: 'HMAC',\n hash: 'SHA-256',\n length: 256\n }, true, ['sign', 'verify']);\n\n const enc = new TextEncoder();\n const message = enc.encode('I love cupcakes');\n\n const digest = await subtle.sign({\n name: 'HMAC'\n }, key, message);\n\n})();\n
The <SubtleCrypto> class can be used to generate symmetric (secret) keys\nor asymmetric key pairs (public key and private key).
const { subtle } = require('node:crypto').webcrypto;\n\nasync function generateAesKey(length = 256) {\n const key = await subtle.generateKey({\n name: 'AES-CBC',\n length\n }, true, ['encrypt', 'decrypt']);\n\n return key;\n}\n
const { subtle } = require('node:crypto').webcrypto;\n\nasync function generateEcKey(namedCurve = 'P-521') {\n const {\n publicKey,\n privateKey\n } = await subtle.generateKey({\n name: 'ECDSA',\n namedCurve,\n }, true, ['sign', 'verify']);\n\n return { publicKey, privateKey };\n}\n
const { subtle } = require('node:crypto').webcrypto;\n\nasync function generateEd25519Key() {\n return subtle.generateKey({\n name: 'Ed25519',\n }, true, ['sign', 'verify']);\n}\n\nasync function generateX25519Key() {\n return subtle.generateKey({\n name: 'X25519',\n }, true, ['deriveKey']);\n}\n
const { subtle } = require('node:crypto').webcrypto;\n\nasync function generateHmacKey(hash = 'SHA-256') {\n const key = await subtle.generateKey({\n name: 'HMAC',\n hash\n }, true, ['sign', 'verify']);\n\n return key;\n}\n
const { subtle } = require('node:crypto').webcrypto;\nconst publicExponent = new Uint8Array([1, 0, 1]);\n\nasync function generateRsaKey(modulusLength = 2048, hash = 'SHA-256') {\n const {\n publicKey,\n privateKey\n } = await subtle.generateKey({\n name: 'RSASSA-PKCS1-v1_5',\n modulusLength,\n publicExponent,\n hash,\n }, true, ['sign', 'verify']);\n\n return { publicKey, privateKey };\n}\n
const crypto = require('node:crypto').webcrypto;\n\nasync function aesEncrypt(plaintext) {\n const ec = new TextEncoder();\n const key = await generateAesKey();\n const iv = crypto.getRandomValues(new Uint8Array(16));\n\n const ciphertext = await crypto.subtle.encrypt({\n name: 'AES-CBC',\n iv,\n }, key, ec.encode(plaintext));\n\n return {\n key,\n iv,\n ciphertext\n };\n}\n\nasync function aesDecrypt(ciphertext, key, iv) {\n const dec = new TextDecoder();\n const plaintext = await crypto.subtle.decrypt({\n name: 'AES-CBC',\n iv,\n }, key, ciphertext);\n\n return dec.decode(plaintext);\n}\n
const { subtle } = require('node:crypto').webcrypto;\n\nasync function generateAndExportHmacKey(format = 'jwk', hash = 'SHA-512') {\n const key = await subtle.generateKey({\n name: 'HMAC',\n hash\n }, true, ['sign', 'verify']);\n\n return subtle.exportKey(format, key);\n}\n\nasync function importHmacKey(keyData, format = 'jwk', hash = 'SHA-512') {\n const key = await subtle.importKey(format, keyData, {\n name: 'HMAC',\n hash\n }, true, ['sign', 'verify']);\n\n return key;\n}\n
const { subtle } = require('node:crypto').webcrypto;\n\nasync function generateAndWrapHmacKey(format = 'jwk', hash = 'SHA-512') {\n const [\n key,\n wrappingKey,\n ] = await Promise.all([\n subtle.generateKey({\n name: 'HMAC', hash\n }, true, ['sign', 'verify']),\n subtle.generateKey({\n name: 'AES-KW',\n length: 256\n }, true, ['wrapKey', 'unwrapKey']),\n ]);\n\n const wrappedKey = await subtle.wrapKey(format, key, wrappingKey, 'AES-KW');\n\n return { wrappedKey, wrappingKey };\n}\n\nasync function unwrapHmacKey(\n wrappedKey,\n wrappingKey,\n format = 'jwk',\n hash = 'SHA-512') {\n\n const key = await subtle.unwrapKey(\n format,\n wrappedKey,\n wrappingKey,\n 'AES-KW',\n { name: 'HMAC', hash },\n true,\n ['sign', 'verify']);\n\n return key;\n}\n
const { subtle } = require('node:crypto').webcrypto;\n\nasync function sign(key, data) {\n const ec = new TextEncoder();\n const signature =\n await subtle.sign('RSASSA-PKCS1-v1_5', key, ec.encode(data));\n return signature;\n}\n\nasync function verify(key, signature, data) {\n const ec = new TextEncoder();\n const verified =\n await subtle.verify(\n 'RSASSA-PKCS1-v1_5',\n key,\n signature,\n ec.encode(data));\n return verified;\n}\n
const { subtle } = require('node:crypto').webcrypto;\n\nasync function pbkdf2(pass, salt, iterations = 1000, length = 256) {\n const ec = new TextEncoder();\n const key = await subtle.importKey(\n 'raw',\n ec.encode(pass),\n 'PBKDF2',\n false,\n ['deriveBits']);\n const bits = await subtle.deriveBits({\n name: 'PBKDF2',\n hash: 'SHA-512',\n salt: ec.encode(salt),\n iterations\n }, key, length);\n return bits;\n}\n\nasync function pbkdf2Key(pass, salt, iterations = 1000, length = 256) {\n const ec = new TextEncoder();\n const keyMaterial = await subtle.importKey(\n 'raw',\n ec.encode(pass),\n 'PBKDF2',\n false,\n ['deriveKey']);\n const key = await subtle.deriveKey({\n name: 'PBKDF2',\n hash: 'SHA-512',\n salt: ec.encode(salt),\n iterations\n }, keyMaterial, {\n name: 'AES-GCM',\n length: 256\n }, true, ['encrypt', 'decrypt']);\n return key;\n}\n
const { subtle } = require('node:crypto').webcrypto;\n\nasync function digest(data, algorithm = 'SHA-512') {\n const ec = new TextEncoder();\n const digest = await subtle.digest(algorithm, ec.encode(data));\n return digest;\n}\n
The table details the algorithms supported by the Node.js Web Crypto API\nimplementation and the APIs supported for each:
generateKey
exportKey
importKey
encrypt
decrypt
wrapKey
unwrapKey
deriveBits
deriveKey
sign
verify
digest
'RSASSA-PKCS1-v1_5'
'RSA-PSS'
'RSA-OAEP'
'ECDSA'
'Ed25519'
'Ed448'
'ECDH'
'X25519'
'X448'
'AES-CTR'
'AES-CBC'
'AES-GCM'
'AES-KW'
'HMAC'
'HKDF'
'PBKDF2'
'SHA-1'
'SHA-256'
'SHA-384'
'SHA-512'
The algorithm parameter objects define the methods and parameters used by\nthe various <SubtleCrypto> methods. While described here as \"classes\", they\nare simple JavaScript dictionary objects.
Provides the initialization vector. It must be exactly 16-bytes in length\nand should be unpredictable and cryptographically random.
The initial value of the counter block. This must be exactly 16 bytes long.
The AES-CTR method uses the rightmost length bits of the block as the\ncounter and the remaining bits as the nonce.
AES-CTR
length
With the AES-GCM method, the additionalData is extra input that is not\nencrypted but is included in the authentication of the data. The use of\nadditionalData is optional.
additionalData
The initialization vector must be unique for every encryption operation using a\ngiven key.
Ideally, this is a deterministic 12-byte value that is computed in such a way\nthat it is guaranteed to be unique across all invocations that use the same key.\nAlternatively, the initialization vector may consist of at least 12\ncryptographically random bytes. For more information on constructing\ninitialization vectors for AES-GCM, refer to Section 8 of NIST SP 800-38D.
The length of the AES key to be generated. This must be either 128, 192,\nor 256.
128
192
256
ECDH key derivation operates by taking as input one parties private key and\nanother parties public key -- using both to generate a common shared secret.\nThe ecdhKeyDeriveParams.public property is set to the other parties public\nkey.
ecdhKeyDeriveParams.public
If represented as a <string>, the value must be one of:
If represented as an <Object>, the object must have a name property\nwhose value is one of the above listed values.
name
The context member represents the optional context data to associate with\nthe message.\nThe Node.js Web Crypto API implementation only supports zero-length context\nwhich is equivalent to not providing context at all.
context
Provides application-specific contextual input to the HKDF algorithm.\nThis can be zero-length but must be provided.
The salt value significantly improves the strength of the HKDF algorithm.\nIt should be random or pseudorandom and should be the same length as the\noutput of the digest function (for instance, if using 'SHA-256' as the\ndigest, the salt should be 256-bits of random data).
The optional number of bits in the HMAC key. This is optional and should\nbe omitted for most cases.
The number of bits to generate for the HMAC key. If omitted,\nthe length will be determined by the hash algorithm used.\nThis is optional and should be omitted for most cases.
The number of iterations the PBKDF2 algorithm should make when deriving bits.
Should be at least 16 random or pseudorandom bytes.
The length in bits of the RSA modulus. As a best practice, this should be\nat least 2048.
2048
The RSA public exponent. This must be a <Uint8Array> containing a big-endian,\nunsigned integer that must fit within 32-bits. The <Uint8Array> may contain an\narbitrary number of leading zero-bits. The value must be a prime number. Unless\nthere is reason to use a different value, use new Uint8Array([1, 0, 1])\n(65537) as the public exponent.
new Uint8Array([1, 0, 1])
An additional collection of bytes that will not be encrypted, but will be bound\nto the generated ciphertext.
The rsaOaepParams.label parameter is optional.
rsaOaepParams.label
The length (in bytes) of the random salt to use.
Calling require('node:crypto').webcrypto returns an instance of the Crypto\nclass. Crypto is a singleton that provides access to the remainder of the\ncrypto API.
Crypto
Provides access to the SubtleCrypto API.
SubtleCrypto
Generates cryptographically strong random values. The given typedArray is\nfilled with random values, and a reference to typedArray is returned.
typedArray
The given typedArray must be an integer-based instance of <TypedArray>,\ni.e. Float32Array and Float64Array are not accepted.
Float32Array
Float64Array
An error will be thrown if the given typedArray is larger than 65,536 bytes.
Generates a random RFC 4122 version 4 UUID. The UUID is generated using a\ncryptographic pseudorandom number generator.
An object detailing the algorithm for which the key can be used along with\nadditional algorithm-specific parameters.
Read-only.
When true, the <CryptoKey> can be extracted using either\nsubtleCrypto.exportKey() or subtleCrypto.wrapKey().
true
subtleCrypto.exportKey()
subtleCrypto.wrapKey()
A string identifying whether the key is a symmetric ('secret') or\nasymmetric ('private' or 'public') key.
'secret'
'private'
'public'
An array of strings identifying the operations for which the\nkey may be used.
The possible usages are:
'encrypt'
'decrypt'
'sign'
'verify'
'deriveKey'
'deriveBits'
'wrapKey'
'unwrapKey'
Valid key usages depend on the key algorithm (identified by\ncryptokey.algorithm.name).
cryptokey.algorithm.name
'HDKF'
The CryptoKeyPair is a simple dictionary object with publicKey and\nprivateKey properties, representing an asymmetric key pair.
CryptoKeyPair
publicKey
privateKey
Using the method and parameters specified in algorithm and the keying\nmaterial provided by key, subtle.decrypt() attempts to decipher the\nprovided data. If successful, the returned promise will be resolved with\nan <ArrayBuffer> containing the plaintext result.
algorithm
key
subtle.decrypt()
data
The algorithms currently supported include:
'AES-GCM
baseKey
Using the method and parameters specified in algorithm and the keying\nmaterial provided by baseKey, subtle.deriveBits() attempts to generate\nlength bits. The Node.js implementation requires that length is a\nmultiple of 8. If successful, the returned promise will be resolved with\nan <ArrayBuffer> containing the generated data.
subtle.deriveBits()
8
derivedKeyAlgorithm
extractable
keyUsages
Using the method and parameters specified in algorithm, and the keying\nmaterial provided by baseKey, subtle.deriveKey() attempts to generate\na new <CryptoKey> based on the method and parameters in derivedKeyAlgorithm.
subtle.deriveKey()
Calling subtle.deriveKey() is equivalent to calling subtle.deriveBits() to\ngenerate raw keying material, then passing the result into the\nsubtle.importKey() method using the deriveKeyAlgorithm, extractable, and\nkeyUsages parameters as input.
subtle.importKey()
deriveKeyAlgorithm
Using the method identified by algorithm, subtle.digest() attempts to\ngenerate a digest of data. If successful, the returned promise is resolved\nwith an <ArrayBuffer> containing the computed digest.
subtle.digest()
If algorithm is provided as a <string>, it must be one of:
If algorithm is provided as an <Object>, it must have a name property\nwhose value is one of the above.
Using the method and parameters specified by algorithm and the keying\nmaterial provided by key, subtle.encrypt() attempts to encipher data.\nIf successful, the returned promise is resolved with an <ArrayBuffer>\ncontaining the encrypted result.
subtle.encrypt()
Exports the given key into the specified format, if supported.
If the <CryptoKey> is not extractable, the returned promise will reject.
When format is either 'pkcs8' or 'spki' and the export is successful,\nthe returned promise will be resolved with an <ArrayBuffer> containing the\nexported key data.
format
'pkcs8'
'spki'
When format is 'jwk' and the export is successful, the returned promise\nwill be resolved with a JavaScript object conforming to the JSON Web Key\nspecification.
'jwk'
'raw'
Using the method and parameters provided in algorithm, subtle.generateKey()\nattempts to generate new keying material. Depending the method used, the method\nmay generate either a single <CryptoKey> or a <CryptoKeyPair>.
subtle.generateKey()
The <CryptoKeyPair> (public and private key) generating algorithms supported\ninclude:
The <CryptoKey> (secret key) generating algorithms supported include:
The subtle.importKey() method attempts to interpret the provided keyData\nas the given format to create a <CryptoKey> instance using the provided\nalgorithm, extractable, and keyUsages arguments. If the import is\nsuccessful, the returned promise will be resolved with the created <CryptoKey>.
keyData
If importing a 'PBKDF2' key, extractable must be false.
false
Using the method and parameters given by algorithm and the keying material\nprovided by key, subtle.sign() attempts to generate a cryptographic\nsignature of data. If successful, the returned promise is resolved with\nan <ArrayBuffer> containing the generated signature.
subtle.sign()
unwrapAlgo
unwrappedKeyAlgo
In cryptography, \"wrapping a key\" refers to exporting and then encrypting the\nkeying material. The subtle.unwrapKey() method attempts to decrypt a wrapped\nkey and create a <CryptoKey> instance. It is equivalent to calling\nsubtle.decrypt() first on the encrypted key data (using the wrappedKey,\nunwrapAlgo, and unwrappingKey arguments as input) then passing the results\nin to the subtle.importKey() method using the unwrappedKeyAlgo,\nextractable, and keyUsages arguments as inputs. If successful, the returned\npromise is resolved with a <CryptoKey> object.
subtle.unwrapKey()
wrappedKey
unwrappingKey
The wrapping algorithms currently supported include:
The unwrapped key algorithms supported include:
signature
Using the method and parameters given in algorithm and the keying material\nprovided by key, subtle.verify() attempts to verify that signature is\na valid cryptographic signature of data. The returned promise is resolved\nwith either true or false.
subtle.verify()
wrappingKey
wrapAlgo
In cryptography, \"wrapping a key\" refers to exporting and then encrypting the\nkeying material. The subtle.wrapKey() method exports the keying material into\nthe format identified by format, then encrypts it using the method and\nparameters specified by wrapAlgo and the keying material provided by\nwrappingKey. It is the equivalent to calling subtle.exportKey() using\nformat and key as the arguments, then passing the result to the\nsubtle.encrypt() method using wrappingKey and wrapAlgo as inputs. If\nsuccessful, the returned promise will be resolved with an <ArrayBuffer>\ncontaining the encrypted key data.
subtle.wrapKey()
subtle.exportKey()