@types/node
Version:
TypeScript definitions for node
1,195 lines • 168 kB
TypeScript
declare module "node:crypto" {
import { NonSharedBuffer } from "node:buffer";
import { Transform, TransformOptions, Writable, WritableOptions } from "node:stream";
import { PeerCertificate } from "node:tls";
/**
* SPKAC is a Certificate Signing Request mechanism originally implemented by
* Netscape and was specified formally as part of HTML5's `keygen` element.
*
* `<keygen>` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects
* should not use this element anymore.
*
* The `node:crypto` module provides the `Certificate` class for working with SPKAC
* data. The most common usage is handling output generated by the HTML5 `<keygen>` element. Node.js uses [OpenSSL's SPKAC
* implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally.
* @since v0.11.8
*/
class Certificate {
/**
* ```js
* const { Certificate } = await import('node:crypto');
* const spkac = getSpkacSomehow();
* const challenge = Certificate.exportChallenge(spkac);
* console.log(challenge.toString('utf8'));
* // Prints: the challenge as a UTF8 string
* ```
* @since v9.0.0
* @param encoding The `encoding` of the `spkac` string.
* @return The challenge component of the `spkac` data structure, which includes a public key and a challenge.
*/
static exportChallenge(spkac: BinaryLike, encoding?: BufferEncoding): NonSharedBuffer;
/**
* ```js
* const { Certificate } = await import('node:crypto');
* const spkac = getSpkacSomehow();
* const publicKey = Certificate.exportPublicKey(spkac);
* console.log(publicKey);
* // Prints: the public key as <Buffer ...>
* ```
* @since v9.0.0
* @param encoding The `encoding` of the `spkac` string.
* @return The public key component of the `spkac` data structure, which includes a public key and a challenge.
*/
static exportPublicKey(spkac: BinaryLike, encoding?: BufferEncoding): NonSharedBuffer;
/**
* ```js
* import { Buffer } from 'node:buffer';
* const { Certificate } = await import('node:crypto');
*
* const spkac = getSpkacSomehow();
* console.log(Certificate.verifySpkac(Buffer.from(spkac)));
* // Prints: true or false
* ```
* @since v9.0.0
* @param encoding The `encoding` of the `spkac` string.
* @return `true` if the given `spkac` data structure is valid, `false` otherwise.
*/
static verifySpkac(spkac: BinaryLike, encoding?: BufferEncoding): boolean;
/**
* @deprecated
* @param encoding The `encoding` of the `spkac` string.
* @returns The challenge component of the `spkac` data structure,
* which includes a public key and a challenge.
*/
exportChallenge(spkac: BinaryLike, encoding?: BufferEncoding): NonSharedBuffer;
/**
* @deprecated
* @param encoding The encoding of the spkac string.
* @returns The public key component of the `spkac` data structure,
* which includes a public key and a challenge.
*/
exportPublicKey(spkac: BinaryLike, encoding?: BufferEncoding): NonSharedBuffer;
/**
* @deprecated
* @param encoding The `encoding` of the `spkac` string.
* @returns `true` if the given `spkac` data structure is valid,
* `false` otherwise.
*/
verifySpkac(spkac: BinaryLike, encoding?: BufferEncoding): boolean;
}
/** @deprecated This property is deprecated. Please use `crypto.setFips()` and `crypto.getFips()` instead. */
var fips: boolean;
interface HashOptions extends TransformOptions {
outputLength?: number | undefined;
}
/**
* Creates and returns a `Hash` object that can be used to generate hash digests
* using the given `algorithm`. Optional `options` argument controls stream
* behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option
* can be used to specify the desired output length in bytes.
*
* The `algorithm` is dependent on the available algorithms supported by the
* version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
* On recent releases of OpenSSL, `openssl list -digest-algorithms` will
* display the available digest algorithms.
*
* Example: generating the sha256 sum of a file
*
* ```js
* import {
* createReadStream,
* } from 'node:fs';
* import { argv } from 'node:process';
* const {
* createHash,
* } = await import('node:crypto');
*
* const filename = argv[2];
*
* const hash = createHash('sha256');
*
* const input = createReadStream(filename);
* input.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = input.read();
* if (data)
* hash.update(data);
* else {
* console.log(`${hash.digest('hex')} ${filename}`);
* }
* });
* ```
* @since v0.1.92
* @param options `stream.transform` options
*/
function createHash(algorithm: string, options?: HashOptions): Hash;
interface HmacOptions extends TransformOptions {
encoding?: BufferEncoding | undefined;
}
/**
* Creates and returns an `Hmac` object that uses the given `algorithm` and `key`.
* Optional `options` argument controls stream behavior.
*
* The `algorithm` is dependent on the available algorithms supported by the
* version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
* On recent releases of OpenSSL, `openssl list -digest-algorithms` will
* display the available digest algorithms.
*
* The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is
* a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was
* obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not
* exceed the block size of `algorithm` (e.g., 512 bits for SHA-256).
*
* Example: generating the sha256 HMAC of a file
*
* ```js
* import {
* createReadStream,
* } from 'node:fs';
* import { argv } from 'node:process';
* const {
* createHmac,
* } = await import('node:crypto');
*
* const filename = argv[2];
*
* const hmac = createHmac('sha256', 'a secret');
*
* const input = createReadStream(filename);
* input.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = input.read();
* if (data)
* hmac.update(data);
* else {
* console.log(`${hmac.digest('hex')} ${filename}`);
* }
* });
* ```
* @since v0.1.94
* @param options `stream.transform` options
*/
function createHmac(algorithm: string, key: KeyLike, options?: HmacOptions): Hmac;
/**
* The `Hash` class is a utility for creating hash digests of data. It can be
* used in one of two ways:
*
* * As a `stream` that is both readable and writable, where data is written
* to produce a computed hash digest on the readable side, or
* * Using the `hash.update()` and `hash.digest()` methods to produce the
* computed hash.
*
* The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword.
*
* Example: Using `Hash` objects as streams:
*
* ```js
* const {
* createHash,
* } = await import('node:crypto');
*
* const hash = createHash('sha256');
*
* hash.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = hash.read();
* if (data) {
* console.log(data.toString('hex'));
* // Prints:
* // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
* }
* });
*
* hash.write('some data to hash');
* hash.end();
* ```
*
* Example: Using `Hash` and piped streams:
*
* ```js
* import { createReadStream } from 'node:fs';
* import { stdout } from 'node:process';
* const { createHash } = await import('node:crypto');
*
* const hash = createHash('sha256');
*
* const input = createReadStream('test.js');
* input.pipe(hash).setEncoding('hex').pipe(stdout);
* ```
*
* Example: Using the `hash.update()` and `hash.digest()` methods:
*
* ```js
* const {
* createHash,
* } = await import('node:crypto');
*
* const hash = createHash('sha256');
*
* hash.update('some data to hash');
* console.log(hash.digest('hex'));
* // Prints:
* // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
* ```
* @since v0.1.92
*/
class Hash extends Transform {
private constructor();
/**
* Creates a new `Hash` object that contains a deep copy of the internal state
* of the current `Hash` object.
*
* The optional `options` argument controls stream behavior. For XOF hash
* functions such as `'shake256'`, the `outputLength` option can be used to
* specify the desired output length in bytes.
*
* An error is thrown when an attempt is made to copy the `Hash` object after
* its `hash.digest()` method has been called.
*
* ```js
* // Calculate a rolling hash.
* const {
* createHash,
* } = await import('node:crypto');
*
* const hash = createHash('sha256');
*
* hash.update('one');
* console.log(hash.copy().digest('hex'));
*
* hash.update('two');
* console.log(hash.copy().digest('hex'));
*
* hash.update('three');
* console.log(hash.copy().digest('hex'));
*
* // Etc.
* ```
* @since v13.1.0
* @param options `stream.transform` options
*/
copy(options?: HashOptions): Hash;
/**
* Updates the hash content with the given `data`, the encoding of which
* is given in `inputEncoding`.
* If `encoding` is not provided, and the `data` is a string, an
* encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
*
* This can be called many times with new data as it is streamed.
* @since v0.1.92
* @param inputEncoding The `encoding` of the `data` string.
*/
update(data: string | NodeJS.ArrayBufferView, inputEncoding?: BufferEncoding): Hash;
/**
* Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method).
* If `encoding` is provided a string will be returned; otherwise
* a `Buffer` is returned.
*
* The `Hash` object can not be used again after `hash.digest()` method has been
* called. Multiple calls will cause an error to be thrown.
* @since v0.1.92
* @param encoding The `encoding` of the return value.
*/
digest(): NonSharedBuffer;
digest(encoding: BufferEncoding): string;
}
/**
* The `Hmac` class is a utility for creating cryptographic HMAC digests. It can
* be used in one of two ways:
*
* * As a `stream` that is both readable and writable, where data is written
* to produce a computed HMAC digest on the readable side, or
* * Using the `hmac.update()` and `hmac.digest()` methods to produce the
* computed HMAC digest.
*
* The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword.
*
* Example: Using `Hmac` objects as streams:
*
* ```js
* const {
* createHmac,
* } = await import('node:crypto');
*
* const hmac = createHmac('sha256', 'a secret');
*
* hmac.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = hmac.read();
* if (data) {
* console.log(data.toString('hex'));
* // Prints:
* // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
* }
* });
*
* hmac.write('some data to hash');
* hmac.end();
* ```
*
* Example: Using `Hmac` and piped streams:
*
* ```js
* import { createReadStream } from 'node:fs';
* import { stdout } from 'node:process';
* const {
* createHmac,
* } = await import('node:crypto');
*
* const hmac = createHmac('sha256', 'a secret');
*
* const input = createReadStream('test.js');
* input.pipe(hmac).pipe(stdout);
* ```
*
* Example: Using the `hmac.update()` and `hmac.digest()` methods:
*
* ```js
* const {
* createHmac,
* } = await import('node:crypto');
*
* const hmac = createHmac('sha256', 'a secret');
*
* hmac.update('some data to hash');
* console.log(hmac.digest('hex'));
* // Prints:
* // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
* ```
* @since v0.1.94
*/
class Hmac extends Transform {
private constructor();
/**
* Updates the `Hmac` content with the given `data`, the encoding of which
* is given in `inputEncoding`.
* If `encoding` is not provided, and the `data` is a string, an
* encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
*
* This can be called many times with new data as it is streamed.
* @since v0.1.94
* @param inputEncoding The `encoding` of the `data` string.
*/
update(data: string | NodeJS.ArrayBufferView, inputEncoding?: BufferEncoding): Hmac;
/**
* Calculates the HMAC digest of all of the data passed using `hmac.update()`.
* If `encoding` is
* provided a string is returned; otherwise a `Buffer` is returned;
*
* The `Hmac` object can not be used again after `hmac.digest()` has been
* called. Multiple calls to `hmac.digest()` will result in an error being thrown.
* @since v0.1.94
* @param encoding The `encoding` of the return value.
*/
digest(): NonSharedBuffer;
digest(encoding: BufferEncoding): string;
}
type KeyFormat = "pem" | "der" | "jwk" | "raw-public" | "raw-private" | "raw-seed";
type KeyObjectType = "secret" | "public" | "private";
type PublicKeyExportType = "pkcs1" | "spki";
type PrivateKeyExportType = "pkcs1" | "pkcs8" | "sec1";
type KeyExportOptions =
| SymmetricKeyExportOptions
| PublicKeyExportOptions
| PrivateKeyExportOptions
| JwkKeyExportOptions
| RawPublicKeyExportOptions
| RawPrivateKeyExportOptions;
interface SymmetricKeyExportOptions {
format?: "buffer" | undefined;
}
interface PublicKeyExportOptions<T extends PublicKeyExportType = PublicKeyExportType> {
type: T;
format: "pem" | "der";
}
interface PrivateKeyExportOptions<T extends PrivateKeyExportType = PrivateKeyExportType> {
type: T;
format: "pem" | "der";
cipher?: string | undefined;
passphrase?: BinaryLike | undefined;
}
interface JwkKeyExportOptions {
format: "jwk";
}
interface RawPublicKeyExportOptions {
format: "raw-public";
}
interface RawPrivateKeyExportOptions {
format: "raw-private" | "raw-seed";
}
interface KeyPairExportOptions<
TPublic extends PublicKeyExportType = PublicKeyExportType,
TPrivate extends PrivateKeyExportType = PrivateKeyExportType,
> {
publicKeyEncoding?:
| PublicKeyExportOptions<TPublic>
| RawPublicKeyExportOptions
| JwkKeyExportOptions
| undefined;
privateKeyEncoding?:
| PrivateKeyExportOptions<TPrivate>
| RawPrivateKeyExportOptions
| JwkKeyExportOptions
| undefined;
}
type KeyExportResult<T, Default> = T extends { format: infer F extends KeyFormat } ? {
"der": NonSharedBuffer;
"jwk": webcrypto.JsonWebKey;
"pem": string;
"raw-public": NonSharedBuffer;
"raw-private": NonSharedBuffer;
"raw-seed": NonSharedBuffer;
}[F]
: Default;
interface KeyPairExportResult<T extends KeyPairExportOptions> {
publicKey: KeyExportResult<T["publicKeyEncoding"], KeyObject>;
privateKey: KeyExportResult<T["privateKeyEncoding"], KeyObject>;
}
type KeyPairExportCallback<T extends KeyPairExportOptions = {}> = (
err: Error | null,
publicKey: KeyExportResult<T["publicKeyEncoding"], KeyObject>,
privateKey: KeyExportResult<T["privateKeyEncoding"], KeyObject>,
) => void;
type MLDSAKeyType = `ml-dsa-${44 | 65 | 87}`;
type MLKEMKeyType = `ml-kem-${1024 | 512 | 768}`;
type SLHDSAKeyType = `slh-dsa-${"sha2" | "shake"}-${128 | 192 | 256}${"f" | "s"}`;
type AsymmetricKeyType =
| "dh"
| "dsa"
| "ec"
| "ed25519"
| "ed448"
| MLDSAKeyType
| MLKEMKeyType
| "rsa-pss"
| "rsa"
| SLHDSAKeyType
| "x25519"
| "x448";
interface AsymmetricKeyDetails {
modulusLength?: number;
publicExponent?: bigint;
hashAlgorithm?: string;
mgf1HashAlgorithm?: string;
saltLength?: number;
divisorLength?: number;
namedCurve?: string;
}
/**
* Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key,
* and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject`
* objects are not to be created directly using the `new`keyword.
*
* Most applications should consider using the new `KeyObject` API instead of
* passing keys as strings or `Buffer`s due to improved security features.
*
* `KeyObject` instances can be passed to other threads via `postMessage()`.
* The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to
* be listed in the `transferList` argument.
* @since v11.6.0
*/
class KeyObject {
private constructor();
/**
* Returns the underlying `KeyObject` of a `CryptoKey`. The returned `KeyObject`
* does not retain any of the restrictions imposed by the Web Crypto API on the
* original `CryptoKey`, such as the allowed key usages, the algorithm or hash
* algorithm bindings, and the extractability flag. In particular, the underlying
* key material of the returned `KeyObject` can always be exported.
*
* ```js
* const { KeyObject } = await import('node:crypto');
* const { subtle } = globalThis.crypto;
*
* const key = await subtle.generateKey({
* name: 'HMAC',
* hash: 'SHA-256',
* length: 256,
* }, true, ['sign', 'verify']);
*
* const keyObject = KeyObject.from(key);
* console.log(keyObject.symmetricKeySize);
* // Prints: 32 (symmetric key size in bytes)
* ```
* @since v15.0.0
*/
static from(key: webcrypto.CryptoKey): KeyObject;
/**
* For asymmetric keys, this property represents the type of the key. See the
* supported [asymmetric key types](https://nodejs.org/docs/latest-v26.x/api/crypto.html#asymmetric-key-types).
*
* This property is `undefined` for unrecognized `KeyObject` types and symmetric
* keys.
* @since v11.6.0
*/
asymmetricKeyType?: AsymmetricKeyType;
/**
* This property exists only on asymmetric keys. Depending on the type of the key,
* this object contains information about the key. None of the information obtained
* through this property can be used to uniquely identify a key or to compromise
* the security of the key.
*
* For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence,
* the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be
* set.
*
* Other key details might be exposed via this API using additional attributes.
* @since v15.7.0
*/
asymmetricKeyDetails?: AsymmetricKeyDetails;
/**
* The result type depends on the selected encoding format, when PEM the
* result is a string, when DER it will be a buffer containing the data
* encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. Raw formats return a
* `Buffer` containing the raw key material.
*
* Private keys can be encrypted by specifying a `cipher` and `passphrase`.
* The PKCS#8 `type` supports encryption with both PEM and DER `format` for any
* key algorithm. PKCS#1 and SEC1 can only be encrypted when the PEM `format` is
* used. For maximum compatibility, use PKCS#8 for encrypted private keys. Since
* PKCS#8 defines its own encryption mechanism, PEM-level encryption is not
* supported when encrypting a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption
* and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for PKCS#1 and SEC1 encryption.
* @since v11.6.0
*/
export<T extends KeyExportOptions = {}>(options?: T): KeyExportResult<T, NonSharedBuffer>;
/**
* Returns `true` or `false` depending on whether the keys have exactly the same
* type, value, and parameters. This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack).
* @since v17.7.0, v16.15.0
* @param otherKeyObject A `KeyObject` with which to compare `keyObject`.
*/
equals(otherKeyObject: KeyObject): boolean;
/**
* For secret keys, this property represents the size of the key in bytes. This
* property is `undefined` for asymmetric keys.
* @since v11.6.0
*/
symmetricKeySize?: number;
/**
* Converts a `KeyObject` instance to a `CryptoKey`.
* @since 22.10.0
*/
toCryptoKey(
algorithm:
| webcrypto.AlgorithmIdentifier
| webcrypto.RsaHashedImportParams
| webcrypto.EcKeyImportParams
| webcrypto.HmacImportParams,
extractable: boolean,
keyUsages: readonly webcrypto.KeyUsage[],
): webcrypto.CryptoKey;
/**
* Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys
* or `'private'` for private (asymmetric) keys.
* @since v11.6.0
*/
type: KeyObjectType;
}
type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm";
type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm";
type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb";
type CipherChaCha20Poly1305Types = "chacha20-poly1305";
type BinaryLike = string | ArrayBufferLike | NodeJS.ArrayBufferView;
type KeyLike = BinaryLike | KeyObject;
interface CipherCCMOptions extends TransformOptions {
authTagLength: number;
}
interface CipherGCMOptions extends TransformOptions {
authTagLength?: number | undefined;
}
interface CipherOCBOptions extends TransformOptions {
authTagLength: number;
}
interface CipherChaCha20Poly1305Options extends TransformOptions {
authTagLength?: number | undefined;
}
/**
* Creates and returns a `Cipher` object, with the given `algorithm`, `key` and
* initialization vector (`iv`).
*
* The `options` argument controls stream behavior and is optional except when a
* cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the
* authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication
* tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
* For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
*
* The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
* recent OpenSSL releases, `openssl list -cipher-algorithms` will
* display the available cipher algorithms.
*
* The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded
* strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be
* a `KeyObject` of type `secret`. If the cipher does not need
* an initialization vector, `iv` may be `null`.
*
* When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* Initialization vectors should be unpredictable and unique; ideally, they will be
* cryptographically random. They do not have to be secret: IVs are typically just
* added to ciphertext messages unencrypted. It may sound contradictory that
* something has to be unpredictable and unique, but does not have to be secret;
* remember that an attacker must not be able to predict ahead of time what a
* given IV will be.
* @since v0.1.94
* @param options `stream.transform` options
*/
function createCipheriv(
algorithm: CipherCCMTypes,
key: KeyLike,
iv: BinaryLike,
options: CipherCCMOptions,
): CipherCCM;
function createCipheriv(
algorithm: CipherOCBTypes,
key: KeyLike,
iv: BinaryLike,
options: CipherOCBOptions,
): CipherOCB;
function createCipheriv(
algorithm: CipherGCMTypes,
key: KeyLike,
iv: BinaryLike,
options?: CipherGCMOptions,
): CipherGCM;
function createCipheriv(
algorithm: CipherChaCha20Poly1305Types,
key: KeyLike,
iv: BinaryLike,
options?: CipherChaCha20Poly1305Options,
): CipherChaCha20Poly1305;
function createCipheriv(
algorithm: string,
key: KeyLike,
iv: BinaryLike | null,
options?: TransformOptions,
): Cipheriv;
/**
* Instances of the `Cipheriv` class are used to encrypt data. The class can be
* used in one of two ways:
*
* * As a `stream` that is both readable and writable, where plain unencrypted
* data is written to produce encrypted data on the readable side, or
* * Using the `cipher.update()` and `cipher.final()` methods to produce
* the encrypted data.
*
* The {@link createCipheriv} method is
* used to create `Cipheriv` instances. `Cipheriv` objects are not to be created
* directly using the `new` keyword.
*
* Example: Using `Cipheriv` objects as streams:
*
* ```js
* const {
* scrypt,
* randomFill,
* createCipheriv,
* } = await import('node:crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
*
* // First, we'll generate the key. The key length is dependent on the algorithm.
* // In this case for aes192, it is 24 bytes (192 bits).
* scrypt(password, 'salt', 24, (err, key) => {
* if (err) throw err;
* // Then, we'll generate a random initialization vector
* randomFill(new Uint8Array(16), (err, iv) => {
* if (err) throw err;
*
* // Once we have the key and iv, we can create and use the cipher...
* const cipher = createCipheriv(algorithm, key, iv);
*
* let encrypted = '';
* cipher.setEncoding('hex');
*
* cipher.on('data', (chunk) => encrypted += chunk);
* cipher.on('end', () => console.log(encrypted));
*
* cipher.write('some clear text data');
* cipher.end();
* });
* });
* ```
*
* Example: Using `Cipheriv` and piped streams:
*
* ```js
* import {
* createReadStream,
* createWriteStream,
* } from 'node:fs';
*
* import {
* pipeline,
* } from 'node:stream';
*
* const {
* scrypt,
* randomFill,
* createCipheriv,
* } = await import('node:crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
*
* // First, we'll generate the key. The key length is dependent on the algorithm.
* // In this case for aes192, it is 24 bytes (192 bits).
* scrypt(password, 'salt', 24, (err, key) => {
* if (err) throw err;
* // Then, we'll generate a random initialization vector
* randomFill(new Uint8Array(16), (err, iv) => {
* if (err) throw err;
*
* const cipher = createCipheriv(algorithm, key, iv);
*
* const input = createReadStream('test.js');
* const output = createWriteStream('test.enc');
*
* pipeline(input, cipher, output, (err) => {
* if (err) throw err;
* });
* });
* });
* ```
*
* Example: Using the `cipher.update()` and `cipher.final()` methods:
*
* ```js
* const {
* scrypt,
* randomFill,
* createCipheriv,
* } = await import('node:crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
*
* // First, we'll generate the key. The key length is dependent on the algorithm.
* // In this case for aes192, it is 24 bytes (192 bits).
* scrypt(password, 'salt', 24, (err, key) => {
* if (err) throw err;
* // Then, we'll generate a random initialization vector
* randomFill(new Uint8Array(16), (err, iv) => {
* if (err) throw err;
*
* const cipher = createCipheriv(algorithm, key, iv);
*
* let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
* encrypted += cipher.final('hex');
* console.log(encrypted);
* });
* });
* ```
* @since v0.1.94
*/
class Cipheriv extends Transform {
private constructor();
/**
* Updates the cipher with `data`. If the `inputEncoding` argument is given,
* the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or `DataView`. If `data` is a `Buffer`,
* `TypedArray`, or `DataView`, then `inputEncoding` is ignored.
*
* The `outputEncoding` specifies the output format of the enciphered
* data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned.
*
* The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being
* thrown.
* @since v0.1.94
* @param inputEncoding The `encoding` of the data.
* @param outputEncoding The `encoding` of the return value.
*/
update(data: string | NodeJS.ArrayBufferView, inputEncoding?: BufferEncoding): NonSharedBuffer;
update(
data: string | NodeJS.ArrayBufferView,
inputEncoding: BufferEncoding | null | undefined,
outputEncoding: BufferEncoding,
): string;
/**
* Once the `cipher.final()` method has been called, the `Cipheriv` object can no
* longer be used to encrypt data. Attempts to call `cipher.final()` more than
* once will result in an error being thrown.
* @since v0.1.94
* @param outputEncoding The `encoding` of the return value.
* @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned.
*/
final(): NonSharedBuffer;
final(outputEncoding: BufferEncoding): string;
/**
* When using block encryption algorithms, the `Cipheriv` class will automatically
* add padding to the input data to the appropriate block size. To disable the
* default padding call `cipher.setAutoPadding(false)`.
*
* When `autoPadding` is `false`, the length of the entire input data must be a
* multiple of the cipher's block size or `cipher.final()` will throw an error.
* Disabling automatic padding is useful for non-standard padding, for instance
* using `0x0` instead of PKCS padding.
*
* The `cipher.setAutoPadding()` method must be called before `cipher.final()`.
* @since v0.7.1
* @param [autoPadding=true]
* @return for method chaining.
*/
setAutoPadding(autoPadding?: boolean): this;
}
interface CipherAEADMethods {
getAuthTag(): NonSharedBuffer;
setAAD(buffer: BinaryLike, options?: {
plaintextLength?: number | undefined;
encoding?: BufferEncoding | undefined;
}): this;
}
interface CipherCCM extends Cipheriv, CipherAEADMethods {
setAAD(buffer: BinaryLike, options: {
plaintextLength: number;
encoding?: BufferEncoding | undefined;
}): this;
}
interface CipherGCM extends Cipheriv, CipherAEADMethods {}
interface CipherOCB extends Cipheriv, CipherAEADMethods {}
interface CipherChaCha20Poly1305 extends Cipheriv, CipherAEADMethods {}
/**
* Creates and returns a `Decipheriv` object that uses the given `algorithm`, `key` and initialization vector (`iv`).
*
* The `options` argument controls stream behavior and is optional except when a
* cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the
* `authTagLength` option is required and specifies the length of the
* authentication tag in bytes, see [CCM mode](https://nodejs.org/docs/latest-v26.x/api/crypto.html#ccm-mode).
* For AES-GCM and `chacha20-poly1305`, the `authTagLength` option defaults to 16
* bytes and must be set to a different value if a different length is used.
*
* The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
* recent OpenSSL releases, `openssl list -cipher-algorithms` will
* display the available cipher algorithms.
*
* The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded
* strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be
* a `KeyObject` of type `secret`. If the cipher does not need
* an initialization vector, `iv` may be `null`.
*
* When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* Initialization vectors should be unpredictable and unique; ideally, they will be
* cryptographically random. They do not have to be secret: IVs are typically just
* added to ciphertext messages unencrypted. It may sound contradictory that
* something has to be unpredictable and unique, but does not have to be secret;
* remember that an attacker must not be able to predict ahead of time what a given
* IV will be.
* @since v0.1.94
* @param options `stream.transform` options
*/
function createDecipheriv(
algorithm: CipherCCMTypes,
key: KeyLike,
iv: BinaryLike,
options: CipherCCMOptions,
): DecipherCCM;
function createDecipheriv(
algorithm: CipherOCBTypes,
key: KeyLike,
iv: BinaryLike,
options: CipherOCBOptions,
): DecipherOCB;
function createDecipheriv(
algorithm: CipherGCMTypes,
key: KeyLike,
iv: BinaryLike,
options?: CipherGCMOptions,
): DecipherGCM;
function createDecipheriv(
algorithm: CipherChaCha20Poly1305Types,
key: KeyLike,
iv: BinaryLike,
options?: CipherChaCha20Poly1305Options,
): DecipherChaCha20Poly1305;
function createDecipheriv(
algorithm: string,
key: KeyLike,
iv: BinaryLike | null,
options?: TransformOptions,
): Decipheriv;
/**
* Instances of the `Decipheriv` class are used to decrypt data. The class can be
* used in one of two ways:
*
* * As a `stream` that is both readable and writable, where plain encrypted
* data is written to produce unencrypted data on the readable side, or
* * Using the `decipher.update()` and `decipher.final()` methods to
* produce the unencrypted data.
*
* The {@link createDecipheriv} method is
* used to create `Decipheriv` instances. `Decipheriv` objects are not to be created
* directly using the `new` keyword.
*
* Example: Using `Decipheriv` objects as streams:
*
* ```js
* import { Buffer } from 'node:buffer';
* const {
* scryptSync,
* createDecipheriv,
* } = await import('node:crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
* // Key length is dependent on the algorithm. In this case for aes192, it is
* // 24 bytes (192 bits).
* // Use the async `crypto.scrypt()` instead.
* const key = scryptSync(password, 'salt', 24);
* // The IV is usually passed along with the ciphertext.
* const iv = Buffer.alloc(16, 0); // Initialization vector.
*
* const decipher = createDecipheriv(algorithm, key, iv);
*
* let decrypted = '';
* decipher.on('readable', () => {
* let chunk;
* while (null !== (chunk = decipher.read())) {
* decrypted += chunk.toString('utf8');
* }
* });
* decipher.on('end', () => {
* console.log(decrypted);
* // Prints: some clear text data
* });
*
* // Encrypted with same algorithm, key and iv.
* const encrypted =
* 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
* decipher.write(encrypted, 'hex');
* decipher.end();
* ```
*
* Example: Using `Decipheriv` and piped streams:
*
* ```js
* import {
* createReadStream,
* createWriteStream,
* } from 'node:fs';
* import { Buffer } from 'node:buffer';
* const {
* scryptSync,
* createDecipheriv,
* } = await import('node:crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
* // Use the async `crypto.scrypt()` instead.
* const key = scryptSync(password, 'salt', 24);
* // The IV is usually passed along with the ciphertext.
* const iv = Buffer.alloc(16, 0); // Initialization vector.
*
* const decipher = createDecipheriv(algorithm, key, iv);
*
* const input = createReadStream('test.enc');
* const output = createWriteStream('test.js');
*
* input.pipe(decipher).pipe(output);
* ```
*
* Example: Using the `decipher.update()` and `decipher.final()` methods:
*
* ```js
* import { Buffer } from 'node:buffer';
* const {
* scryptSync,
* createDecipheriv,
* } = await import('node:crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
* // Use the async `crypto.scrypt()` instead.
* const key = scryptSync(password, 'salt', 24);
* // The IV is usually passed along with the ciphertext.
* const iv = Buffer.alloc(16, 0); // Initialization vector.
*
* const decipher = createDecipheriv(algorithm, key, iv);
*
* // Encrypted using same algorithm, key and iv.
* const encrypted =
* 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
* let decrypted = decipher.update(encrypted, 'hex', 'utf8');
* decrypted += decipher.final('utf8');
* console.log(decrypted);
* // Prints: some clear text data
* ```
* @since v0.1.94
*/
class Decipheriv extends Transform {
private constructor();
/**
* Updates the decipher with `data`. If the `inputEncoding` argument is given,
* the `data` argument is a string using the specified encoding. If the `inputEncoding` argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is
* ignored.
*
* The `outputEncoding` specifies the output format of the enciphered
* data. If the `outputEncoding` is specified, a string using the specified encoding is returned. If no `outputEncoding` is provided, a `Buffer` is returned.
*
* The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error
* being thrown.
* @since v0.1.94
* @param inputEncoding The `encoding` of the `data` string.
* @param outputEncoding The `encoding` of the return value.
*/
update(data: string | NodeJS.ArrayBufferView, inputEncoding?: BufferEncoding): NonSharedBuffer;
update(
data: string | NodeJS.ArrayBufferView,
inputEncoding: BufferEncoding | null | undefined,
outputEncoding: BufferEncoding,
): string;
/**
* Once the `decipher.final()` method has been called, the `Decipheriv` object can
* no longer be used to decrypt data. Attempts to call `decipher.final()` more
* than once will result in an error being thrown.
* @since v0.1.94
* @param outputEncoding The `encoding` of the return value.
* @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned.
*/
final(): NonSharedBuffer;
final(outputEncoding: BufferEncoding): string;
/**
* When data has been encrypted without standard block padding, calling `decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and
* removing padding.
*
* Turning auto padding off will only work if the input data's length is a
* multiple of the ciphers block size.
*
* The `decipher.setAutoPadding()` method must be called before `decipher.final()`.
* @since v0.7.1
* @param [autoPadding=true]
* @return for method chaining.
*/
setAutoPadding(auto_padding?: boolean): this;
}
interface DecipherAEADMethods {
setAAD(
buffer: BinaryLike,
options?: {
plaintextLength?: number | undefined;
encoding?: BufferEncoding | undefined;
},
): this;
setAuthTag(buffer: BinaryLike, encoding?: BufferEncoding): this;
}
interface DecipherCCM extends Decipheriv, DecipherAEADMethods {
setAAD(
buffer: BinaryLike,
options: {
plaintextLength: number;
encoding?: BufferEncoding | undefined;
},
): this;
}
interface DecipherGCM extends Decipheriv, DecipherAEADMethods {}
interface DecipherOCB extends Decipheriv, DecipherAEADMethods {}
interface DecipherChaCha20Poly1305 extends Decipheriv, DecipherAEADMethods {}
interface PrivateKeyInput {
key: BinaryLike;
format?: "pem" | "der" | undefined;
type?: PrivateKeyExportType | undefined;
passphrase?: BinaryLike | undefined;
encoding?: BufferEncoding | undefined;
}
interface PublicKeyInput {
key: BinaryLike;
format?: "pem" | "der" | undefined;
type?: PublicKeyExportType | undefined;
encoding?: BufferEncoding | undefined;
}
interface RawPrivateKeyInput {
key: ArrayBufferLike | NodeJS.ArrayBufferView;
format: "raw-private" | "raw-seed";
asymmetricKeyType: AsymmetricKeyType;
namedCurve?: string | undefined;
}
interface RawPublicKeyInput {
key: ArrayBufferLike | NodeJS.ArrayBufferView;
format: "raw-public";
asymmetricKeyType: AsymmetricKeyType;
namedCurve?: string | undefined;
}
interface JsonWebKeyInput {
key: webcrypto.JsonWebKey;
format: "jwk";
}
interface SecretKeyOptions {
length: number;
}
/**
* Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`.
*
* ```js
* const {
* generateKey,
* } = await import('node:crypto');
*
* generateKey('hmac', { length: 512 }, (err, key) => {
* if (err) throw err;
* console.log(key.export().toString('hex')); // 46e..........620
* });
* ```
*
* The size of a generated HMAC key should not exceed the block size of the
* underlying hash function. See {@link createHmac} for more information.
* @since v15.0.0
* @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`.
*/
function generateKey(
type: "hmac" | "aes",
options: SecretKeyOptions,
callback: (err: Error | null, key: KeyObject) => void,
): void;
/**
* Synchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`.
*
* ```js
* const {
* generateKeySync,
* } = await import('node:crypto');
*
* const key = generateKeySync('hmac', { length: 512 });
* console.log(key.export().toString('hex')); // e89..........41e
* ```
*
* The size of a generated HMAC key should not exceed the block size of the
* underlying hash function. See {@link createHmac} for more information.
* @since v15.0.0
* @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`.
*/
function generateKeySync(type: "hmac" | "aes", options: SecretKeyOptions): KeyObject;
/**
* Creates and returns a new key object containing a private key. If `key` is a
* string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key` must be an object with the properties described above.
*
* If the private key is encrypted, a `passphrase` must be specified. The length
* of the passphrase is limited to 1024 bytes.
* @since v11.6.0
*/
function createPrivateKey(key: PrivateKeyInput | RawPrivateKeyInput | JsonWebKeyInput | BinaryLike): KeyObject;
/**
* Creates and returns a new key object containing a public key. If `key` is a
* string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` with type `'private'`, the public key is derived from the given private key;
* otherwise, `key` must be an object with the properties described above.
*
* If the format is `'pem'`, the `'key'` may also be an X.509 certificate.
*
* Because public keys can be derived from private keys, a private key may be
* passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the
* returned `KeyObject` will be `'public'` and that the private key cannot be
* extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type `'private'` is given, a new `KeyObject` with type `'public'` will be returned
* and it will be impossible to extract the private key from the returned object.
* @since v11.6.0
*/
function createPublicKey(key: PublicKeyInput | RawPublicKeyInput | JsonWebKeyInput | BinaryLike): KeyObject;
/**
* Creates and returns a new key object containing a secret key for symmetric
* encryption or `Hmac`.
* @since v11.6.0
* @param encoding The string encoding when `key` is a string.
*/
function createSecretKey(key: BinaryLike, encoding?: BufferEncoding): Ke