- 断言测试
- 异步上下文跟踪
- 异步钩子
- 缓冲(Buffer)
- C++ 插件
- 使用 Node-API 的 C/C++ 插件
- C++ 嵌入 Node环境
- 子进程(Child processes)
- 集群(Cluster)
- 命令行选项
- 控制台(Console)
- 核心包(Corepack)
- 加密(Crypto)
- 调试器(Debugger)
- 已弃用的 API
- 诊断通道(Diagnostics Channel)
- 域名系统(DNS)
- 域(Domain)
- 错误(Errors)
- 事件(Events)
- 文件系统(File system)
- 全局变量(Globals)
- HTTP
- HTTP/2
- HTTPS
- 检查器(Inspector)
- 国际化
- 模块:CommonJS 模块
- 模块:ECMAScript 模块
- 模块:
node:moduleAPI - 模块:packages 模块
- 网络(Net)
- 系统(OS)
- 路径(Path)
- 性能挂钩(Performance hooks)
- 性能挂钩(Permissions)
- 进程(Process)
- Punycode 国际化域名编码
- 查询字符串(Query strings)
- 命令行库(Readline)
- REPL 交互式编程环境
- 诊断报告
- 单个可执行应用程序
- Stream 流
- 字符串解码器
- 单元测试
- 定时器(Timers)
- 传输层安全/SSL
- 跟踪事件
- TTY
- UDP/数据报
- URL
- 实用程序
- V8
- 虚拟机
- WebAssembly
- Web加密 API(Web Crypto API)
- 网络流 API(Web Streams API)
- 工作线程(Worker threads)
- zlib
Node.js v18.18.2 文档
- Node.js v18.18.2
-
►
目录
- 加密
- 确定加密支持是否不可用
- 类:
Certificate - 类:
Cipher - 类:
Decipher - 类:
DiffieHellmandiffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])diffieHellman.generateKeys([encoding])diffieHellman.getGenerator([encoding])diffieHellman.getPrime([encoding])diffieHellman.getPrivateKey([encoding])diffieHellman.getPublicKey([encoding])diffieHellman.setPrivateKey(privateKey[, encoding])diffieHellman.setPublicKey(publicKey[, encoding])diffieHellman.verifyError
- 类:
DiffieHellmanGroup - 类:
ECDH- 静态方法:
ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]]) ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])ecdh.generateKeys([encoding[, format]])ecdh.getPrivateKey([encoding])ecdh.getPublicKey([encoding][, format])ecdh.setPrivateKey(privateKey[, encoding])ecdh.setPublicKey(publicKey[, encoding])
- 静态方法:
- 类:
Hash - 类:
Hmac - 类:
KeyObject - 类:
Sign - 类:
Verify - 类:
X509Certificatenew X509Certificate(buffer)x509.cax509.checkEmail(email[, options])x509.checkHost(name[, options])x509.checkIP(ip)x509.checkIssued(otherCert)x509.checkPrivateKey(privateKey)x509.fingerprintx509.fingerprint256x509.fingerprint512x509.infoAccessx509.issuerx509.issuerCertificatex509.keyUsagex509.publicKeyx509.rawx509.serialNumberx509.subjectx509.subjectAltNamex509.toJSON()x509.toLegacyObject()x509.toString()x509.validFromx509.validTox509.verify(publicKey)
node:cryptomodule methods and propertiescrypto.constantscrypto.DEFAULT_ENCODINGcrypto.fipscrypto.checkPrime(candidate[, options], callback)crypto.checkPrimeSync(candidate[, options])crypto.createCipher(algorithm, password[, options])crypto.createCipheriv(algorithm, key, iv[, options])crypto.createDecipher(algorithm, password[, options])crypto.createDecipheriv(algorithm, key, iv[, options])crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])crypto.createDiffieHellman(primeLength[, generator])crypto.createDiffieHellmanGroup(name)crypto.createECDH(curveName)crypto.createHash(algorithm[, options])crypto.createHmac(algorithm, key[, options])crypto.createPrivateKey(key)crypto.createPublicKey(key)crypto.createSecretKey(key[, encoding])crypto.createSign(algorithm[, options])crypto.createVerify(algorithm[, options])crypto.diffieHellman(options)crypto.generateKey(type, options, callback)crypto.generateKeyPair(type, options, callback)crypto.generateKeyPairSync(type, options)crypto.generateKeySync(type, options)crypto.generatePrime(size[, options[, callback]])crypto.generatePrimeSync(size[, options])crypto.getCipherInfo(nameOrNid[, options])crypto.getCiphers()crypto.getCurves()crypto.getDiffieHellman(groupName)crypto.getFips()crypto.getHashes()crypto.getRandomValues(typedArray)crypto.hkdf(digest, ikm, salt, info, keylen, callback)crypto.hkdfSync(digest, ikm, salt, info, keylen)crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)crypto.privateDecrypt(privateKey, buffer)crypto.privateEncrypt(privateKey, buffer)crypto.publicDecrypt(key, buffer)crypto.publicEncrypt(key, buffer)crypto.randomBytes(size[, callback])crypto.randomFillSync(buffer[, offset][, size])crypto.randomFill(buffer[, offset][, size], callback)crypto.randomInt([min, ]max[, callback])crypto.randomUUID([options])crypto.scrypt(password, salt, keylen[, options], callback)crypto.scryptSync(password, salt, keylen[, options])crypto.secureHeapUsed()crypto.setEngine(engine[, flags])crypto.setFips(bool)crypto.sign(algorithm, data, key[, callback])crypto.subtlecrypto.timingSafeEqual(a, b)crypto.verify(algorithm, data, key, signature[, callback])crypto.webcrypto
- Notes
- Crypto constants
- 加密
-
►
索引
- Assertion testing
- Asynchronous context tracking
- Async hooks
- Buffer
- C++ addons
- C/C++ addons with Node-API
- C++ embedder API
- Child processes
- Cluster
- Command-line options
- Console
- Corepack
- Crypto
- Debugger
- Deprecated APIs
- Diagnostics Channel
- DNS
- Domain
- Errors
- Events
- File system
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- Internationalization
- Modules: CommonJS modules
- Modules: ECMAScript modules
- Modules:
node:moduleAPI - Modules: Packages
- Net
- 系统(OS)
- 路径(Path)
- Performance hooks
- Permissions
- 进程(Process)
- Punycode
- Query strings
- 命令行库(Readline)
- REPL 交互式编程环境
- Report
- Single executable applications
- Stream
- String decoder
- Test runner
- Timers
- TLS/SSL
- Trace events
- TTY
- UDP/datagram
- URL
- Utilities
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- Worker threads
- Zlib
- ► 其他版本
- ► 选项
目录
- 加密
- 确定加密支持是否不可用
- 类:
Certificate - 类:
Cipher - 类:
Decipher - 类:
DiffieHellmandiffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])diffieHellman.generateKeys([encoding])diffieHellman.getGenerator([encoding])diffieHellman.getPrime([encoding])diffieHellman.getPrivateKey([encoding])diffieHellman.getPublicKey([encoding])diffieHellman.setPrivateKey(privateKey[, encoding])diffieHellman.setPublicKey(publicKey[, encoding])diffieHellman.verifyError
- 类:
DiffieHellmanGroup - 类:
ECDH- 静态方法:
ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]]) ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])ecdh.generateKeys([encoding[, format]])ecdh.getPrivateKey([encoding])ecdh.getPublicKey([encoding][, format])ecdh.setPrivateKey(privateKey[, encoding])ecdh.setPublicKey(publicKey[, encoding])
- 静态方法:
- 类:
Hash - 类:
Hmac - 类:
KeyObject - 类:
Sign - 类:
Verify - 类:
X509Certificatenew X509Certificate(buffer)x509.cax509.checkEmail(email[, options])x509.checkHost(name[, options])x509.checkIP(ip)x509.checkIssued(otherCert)x509.checkPrivateKey(privateKey)x509.fingerprintx509.fingerprint256x509.fingerprint512x509.infoAccessx509.issuerx509.issuerCertificatex509.keyUsagex509.publicKeyx509.rawx509.serialNumberx509.subjectx509.subjectAltNamex509.toJSON()x509.toLegacyObject()x509.toString()x509.validFromx509.validTox509.verify(publicKey)
node:crypto模块方法和属性crypto.constantscrypto.DEFAULT_ENCODINGcrypto.fipscrypto.checkPrime(candidate[, options], callback)crypto.checkPrimeSync(candidate[, options])crypto.createCipher(algorithm, password[, options])crypto.createCipheriv(algorithm, key, iv[, options])crypto.createDecipher(algorithm, password[, options])crypto.createDecipheriv(algorithm, key, iv[, options])crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])crypto.createDiffieHellman(primeLength[, generator])crypto.createDiffieHellmanGroup(name)crypto.createECDH(curveName)crypto.createHash(algorithm[, options])crypto.createHmac(algorithm, key[, options])crypto.createPrivateKey(key)crypto.createPublicKey(key)crypto.createSecretKey(key[, encoding])crypto.createSign(algorithm[, options])crypto.createVerify(algorithm[, options])crypto.diffieHellman(options)crypto.generateKey(type, options, callback)crypto.generateKeyPair(type, options, callback)crypto.generateKeyPairSync(type, options)crypto.generateKeySync(type, options)crypto.generatePrime(size[, options[, callback]])crypto.generatePrimeSync(size[, options])crypto.getCipherInfo(nameOrNid[, options])crypto.getCiphers()crypto.getCurves()crypto.getDiffieHellman(groupName)crypto.getFips()crypto.getHashes()crypto.getRandomValues(typedArray)crypto.hkdf(digest, ikm, salt, info, keylen, callback)crypto.hkdfSync(digest, ikm, salt, info, keylen)crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)crypto.privateDecrypt(privateKey, buffer)crypto.privateEncrypt(privateKey, buffer)crypto.publicDecrypt(key, buffer)crypto.publicEncrypt(key, buffer)crypto.randomBytes(size[, callback])crypto.randomFillSync(buffer[, offset][, size])crypto.randomFill(buffer[, offset][, size], callback)crypto.randomInt([min, ]max[, callback])crypto.randomUUID([options])crypto.scrypt(password, salt, keylen[, options], callback)crypto.scryptSync(password, salt, keylen[, options])crypto.secureHeapUsed()crypto.setEngine(engine[, flags])crypto.setFips(bool)crypto.sign(algorithm, data, key[, callback])crypto.subtlecrypto.timingSafeEqual(a, b)crypto.verify(algorithm, data, key, signature[, callback])crypto.webcrypto
- 注意
- 加密常量
加密#
源代码: lib/crypto.js
node:crypto模块提供加密功能,其中包括一组 OpenSSL 哈希、HMAC、密码、解密、签名和验证函数的包装器。
const { createHmac } = await import('node:crypto');
const secret = 'abcdefg';
const hash = createHmac('sha256', secret)
.update('I love cupcakes')
.digest('hex');
console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658econst { createHmac } = require('node:crypto');
const secret = 'abcdefg';
const hash = createHmac('sha256', secret)
.update('I love cupcakes')
.digest('hex');
console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
确定加密支持是否不可用#
Node.js 可以在不包含对
node:crypto模块的支持的情况下构建。在这种情况下,尝试从crypto执行import或调用require('node:crypto')将导致抛出错误。
使用 CommonJS 时,可以使用 try/catch 捕获抛出的错误:
let crypto;
try {
crypto = require('node:crypto');
} catch (err) {
console.error('crypto support is disabled!');
}
当使用词法 ESM import关键字时,只有在尝试加载模块之前注册了
process.on('uncaughtException') 的处理程序(例如,使用预加载),才能捕获错误模块)。
使用 ESM 时,如果代码有可能在未启用加密支持的 Node.js 版本上运行,请考虑使用 import() 函数
而不是词法import关键字:
let crypto;
try {
crypto = await import('node:crypto');
} catch (err) {
console.error('crypto support is disabled!');
}
类:Certificate#
SPKAC 是一种证书签名请求机制,最初由 Netscape 实现,并被正式指定为 HTML5 的keygen元素的一部分。
自HTML 5.2起, <keygen>已被弃用,新项目不应再使用此元素。
node:crypto模块提供了用于处理 SPKAC 数据的Certificate类。最常见的用法是处理 HTML5
<keygen>元素生成的输出。Node.js 在内部使用OpenSSL 的 SPKAC 实现。
静态方法:Certificate.exportChallenge(spkac[, encoding])#
spkac<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>encoding<string>spkac字符串的编码。- 返回:<Buffer>
spkac数据结构的质询组件,其中包括公钥和质询。
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 stringconst { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
const challenge = Certificate.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 string
静态方法:Certificate.exportPublicKey(spkac[, encoding])#
spkac<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>encoding<string>spkac字符串的编码。- 返回:<Buffer>
spkac数据结构的公钥组成部分,其中包括公钥和质询。
const { Certificate } = await import('node:crypto');
const spkac = getSpkacSomehow();
const publicKey = Certificate.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as <Buffer ...>const { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
const publicKey = Certificate.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as <Buffer ...>
静态方法:Certificate.verifySpkac(spkac[, encoding])#
spkac<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>encoding<string>spkac字符串的编码。- 返回:<boolean>
true如果给定的spkac数据结构有效, 则false否则。
import { Buffer } from 'node:buffer';
const { Certificate } = await import('node:crypto');
const spkac = getSpkacSomehow();
console.log(Certificate.verifySpkac(Buffer.from(spkac)));
// Prints: true or falseconst { Buffer } = require('node:buffer');
const { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
console.log(Certificate.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
旧版 API#
作为旧接口,可以创建crypto.Certificate类的新实例,如下例所示。
new crypto.Certificate()#
可以使用 new 关键字或通过将 crypto.Certificate() 作为函数调用来创建 Certificate类的实例:
const { Certificate } = await import('node:crypto');
const cert1 = new Certificate();
const cert2 = Certificate();const { Certificate } = require('node:crypto');
const cert1 = new Certificate();
const cert2 = Certificate();
certificate.exportChallenge(spkac[, encoding])#
spkac<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>encoding<string>spkac字符串的编码。- 返回:<Buffer>
spkac数据结构的质询组件,其中包括公钥和质询。
const { Certificate } = await import('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
const challenge = cert.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 stringconst { Certificate } = require('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
const challenge = cert.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 string
certificate.exportPublicKey(spkac[, encoding])#
spkac<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>encoding<string>spkac字符串的编码。- 返回:<Buffer>
spkac数据结构的公钥组成部分,其中包括公钥和质询。
const { Certificate } = await import('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
const publicKey = cert.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as <Buffer ...>const { Certificate } = require('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
const publicKey = cert.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as <Buffer ...>
certificate.verifySpkac(spkac[, encoding])#
spkac<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>encoding<string>spkac字符串的编码。- 返回:如果给定的
spkac数据结构有效, 则返回<boolean>true,否则返回false。
import { Buffer } from 'node:buffer';
const { Certificate } = await import('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
console.log(cert.verifySpkac(Buffer.from(spkac)));
// Prints: true or falseconst { Buffer } = require('node:buffer');
const { Certificate } = require('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
console.log(cert.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
类:Cipher#
Cipher类的实例用于加密数据。该类可以通过以下两种方式之一使用:
- 作为可读可写的流,写入纯未加密数据以在可读端生成加密数据,或者
- 使用
cipher.update()和cipher.final()方法生成加密数据。
crypto.createCipher()或crypto.createCipheriv()方法用于创建Cipher实例。不应使用new 关键字直接创建 Cipher对象。
示例:使用Cipher对象作为流:
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();
});
});const {
scrypt,
randomFill,
createCipheriv,
} = require('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();
});
});
示例:使用Cipher和管道流:
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;
});
});
});const {
createReadStream,
createWriteStream,
} = require('node:fs');
const {
pipeline,
} = require('node:stream');
const {
scrypt,
randomFill,
createCipheriv,
} = require('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;
});
});
});
示例:使用cipher.update()和cipher.final()方法:
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);
});
});const {
scrypt,
randomFill,
createCipheriv,
} = require('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);
});
});
cipher.final([outputEncoding])#
outputEncoding<string>返回值的编码。- 返回:<缓冲区> | <string>任何剩余的加密内容。如果指定了
outputEncoding,则返回一个字符串。如果未提供outputEncoding,则返回Buffer。
一旦调用了cipher.final()方法, Cipher对象就不能再用于加密数据。尝试多次调用cipher.final()将导致抛出错误。
cipher.getAuthTag()#
- 返回:<Buffer>当使用经过身份验证的加密模式(当前支持
GCM、CCM、OCB和chacha20-poly1305)时,cipher.getAuthTag()方法返回一个Buffer,其中包含根据给定数据计算出的身份验证标记。
仅应在使用cipher.final()方法完成加密后调用cipher.getAuthTag()方法。
如果在创建cipher实例期间设置了authTagLength选项,则此函数将恰好返回authTagLength字节。
cipher.setAAD(buffer[, options])#
buffer<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>options<对象>stream.transform选项- 返回:<Cipher>用于方法链接。
当使用经过身份验证的加密模式(当前支持GCM、CCM、OCB和
chacha20-poly1305 )时, cipher.setAAD()方法设置用于附加身份验证数据(AAD) 输入参数的值
。
对于GCM和OCB , plaintextLength选项是可选的。使用CCM时,必须指定plaintextLength选项,并且其值必须与明文长度(以字节为单位)匹配。请参阅CCM 模式。
必须在cipher.update()之前调用cipher.setAAD()方法。
cipher.setAutoPadding([autoPadding])#
使用块加密算法时,Cipher类会自动向输入数据添加填充,以达到适当的块大小。要禁用默认填充,请调用cipher.setAutoPadding(false)。
当autoPadding为false时,整个输入数据的长度必须是密码块大小的倍数,否则cipher.final()将引发错误。禁用自动填充对于非标准填充非常有用,例如使用0x0而不是 PKCS 填充。
必须在cipher.final()之前调用
cipher.setAutoPadding()方法。
cipher.update(data[, inputEncoding][, outputEncoding])#
data<字符串> | <缓冲区> | <类型化数组> | <数据视图>-
inputEncoding<string>数据的编码。 outputEncoding<string>返回值的编码。- 返回:<缓冲区> | <字符串>
使用data更新密码。如果给出了inputEncoding参数,则 data
参数是使用指定编码的字符串。如果
未给出inputEncoding参数,则data必须是Buffer、TypedArray或
DataView。如果data是Buffer、TypedArray或DataView,则
inputEncoding会被忽略。
outputEncoding指定加密数据的输出格式。如果指定了outputEncoding
,则返回使用指定编码的字符串。如果未
提供outputEncoding ,则返回Buffer 。
可以使用新数据多次调用
cipher.update()方法,直到调用cipher.final()为止。在cipher.final()之后
调用cipher.update()将导致抛出错误。
类:Decipher#
Decipher类的实例用于解密数据。该类可以通过以下两种方式之一使用:
- 作为可读可写的流,其中写入明文加密数据以在可读端生成未加密数据,或者
- 使用
decipher.update()和decipher.final()方法生成未加密的数据。
crypto.createDecipher()或crypto.createDecipheriv()方法用于创建Decipher实例。Decipher对象不能直接使用new关键字创建。
示例:使用Decipher对象作为流:
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();const {
scryptSync,
createDecipheriv,
} = require('node:crypto');
const { Buffer } = require('node:buffer');
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();
示例:使用Decipher和管道流:
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);const {
createReadStream,
createWriteStream,
} = require('node:fs');
const {
scryptSync,
createDecipheriv,
} = require('node:crypto');
const { Buffer } = require('node:buffer');
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);
示例:使用decipher.update()和decipher.final()方法:
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 dataconst {
scryptSync,
createDecipheriv,
} = require('node:crypto');
const { Buffer } = require('node:buffer');
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
decipher.final([outputEncoding])#
outputEncoding<string>返回值的编码。- 返回:<缓冲区> | <string>任何剩余的解密内容。如果指定了
outputEncoding,则返回一个字符串。如果未提供outputEncoding,则返回Buffer。
一旦调用了decipher.final()方法, Decipher对象就不能再用于解密数据。尝试多次调用decipher.final()将导致抛出错误。
decipher.setAAD(buffer[, options])#
buffer<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>options<对象>stream.transform选项- 返回:<Decipher>用于方法链接。
当使用经过身份验证的加密模式(当前支持GCM、CCM、OCB和
chacha20-poly1305 )时, decipher.setAAD()方法设置用于附加身份验证数据(AAD) 输入参数的值
。
对于GCM来说, options参数是可选的。使用CCM时,
必须指定plaintextLength选项,并且其值必须与密文长度(以字节为单位)匹配。请参阅CCM 模式。
必须在decipher.update()之前调用decipher.setAAD()方法。
将字符串作为buffer传递时,请考虑
使用字符串作为加密 API 的输入时的注意事项。
decipher.setAuthTag(buffer[, encoding])#
buffer<字符串> | <缓冲区> | <数组缓冲区> | <类型化数组> | <数据视图>encoding<string>当buffer是字符串时使用的字符串编码。- 返回:<Decipher>用于方法链接。
当使用经过身份验证的加密模式(当前支持GCM、CCM、OCB和
chacha20-poly1305 )时, decipher.setAuthTag()方法用于传入接收到的认证标签。如果没有提供标签,或者密文被篡改,则会抛出decipher.final(),表示由于认证失败,密文应被丢弃。如果标签长度根据NIST SP 800-38D无效或与authTagLength选项的值不匹配
,则decipher.setAuthTag()将引发错误。
对于CCM模式,必须在decipher.update()之前调用decipher.setAuthTag()方法;对于GCM和OCB模式和
chacha20-poly1305。
decipher.setAuthTag()只能调用一次。
当传递字符串作为身份验证标签时,请考虑 使用字符串作为加密 API 的输入时的注意事项。
decipher.setAutoPadding([autoPadding])#
autoPadding<布尔值> 默认值:true- 返回:<Decipher>用于方法链接。
当数据在没有标准块填充的情况下进行加密时,调用
decipher.setAutoPadding(false)将禁用自动填充,以防止
decipher.final()检查和删除填充。
仅当输入数据的长度是密码块大小的倍数时,关闭自动填充才有效。
必须在decipher.final()之前调用
decipher.setAutoPadding()方法。
decipher.update(data[, inputEncoding][, outputEncoding])#
data<字符串> | <缓冲区> | <类型化数组> | <数据视图>inputEncoding<string>data字符串的编码。outputEncoding<string>返回值的编码。- 返回:<缓冲区> | <字符串>
使用data更新解密。如果给出了inputEncoding参数,则 data
参数是使用指定编码的字符串。如果
未给出inputEncoding参数,则 data必须是Buffer。如果data是
Buffer,则inputEncoding将被忽略。
outputEncoding指定加密数据的输出格式。如果指定了outputEncoding
,则返回使用指定编码的字符串。如果未
提供outputEncoding ,则返回Buffer 。
可以使用新数据多次调用
decipher.update()方法,直到调用decipher.final()为止。在decipher.final()之后
调用decipher.update()将导致抛出错误。
类:DiffieHellman#
DiffieHellman类是用于创建 Diffie-Hellman 密钥交换的实用程序。
可以使用
crypto.createDiffieHellman()函数创建DiffieHellman类的实例。
import assert from 'node:assert';
const {
createDiffieHellman,
} = await import('node:crypto');
// Generate Alice's keys...
const alice = createDiffieHellman(2048);
const aliceKey = alice.generateKeys();
// Generate Bob's keys...
const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());
const bobKey = bob.generateKeys();
// Exchange and generate the secret...
const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);
// OK
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));const assert = require('node:assert');
const {
createDiffieHellman,
} = require('node:crypto');
// Generate Alice's keys...
const alice = createDiffieHellman(2048);
const aliceKey = alice.generateKeys();
// Generate Bob's keys...
const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());
const bobKey = bob.generateKeys();
// Exchange and generate the secret...
const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);
// OK
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])#
otherPublicKey<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>inputEncoding<string>otherPublicKey字符串的编码。outputEncoding<string>返回值的编码。- 返回:<缓冲区> | <字符串>
使用otherPublicKey作为另一方的公钥计算共享密钥,并返回计算出的共享密钥。提供的密钥使用指定的inputEncoding进行解释,秘密使用指定的outputEncoding进行编码。如果未提供inputEncoding ,则otherPublicKey预计为Buffer、
TypedArray或DataView。
如果给定outputEncoding则返回一个字符串;否则,
返回Buffer 。
diffieHellman.generateKeys([encoding])#
生成私有和公共 Diffie-Hellman 密钥值(除非它们已生成或计算),并返回指定的encoding中的公钥。这个密钥应该转移给对方。如果提供了encoding,则返回一个字符串;否则
返回Buffer 。
此函数是DH_generate_key()的薄包装。特别是,一旦生成或设置了私钥,调用此函数只会更新公钥,但不会生成新的私钥。
diffieHellman.getGenerator([encoding])#
返回指定的encoding中的 Diffie-Hellman 生成器。如果提供了encoding,则返回一个字符串;否则返回Buffer 。
diffieHellman.getPrime([encoding])#
返回指定encoding中的 Diffie-Hellman 素数。如果提供了encoding,则返回一个字符串;否则返回Buffer 。
diffieHellman.getPrivateKey([encoding])#
返回指定的encoding中的 Diffie-Hellman 私钥。如果提供了encoding,则返回一个字符串;否则返回Buffer 。
diffieHellman.getPublicKey([encoding])#
返回指定encoding中的 Diffie-Hellman 公钥。如果提供了encoding,则返回一个字符串;否则返回Buffer 。
diffieHellman.setPrivateKey(privateKey[, encoding])#
设置 Diffie-Hellman 私钥。如果提供了
encoding参数,则privateKey应该是一个字符串。如果未提供encoding ,则privateKey预计为Buffer、TypedArray或DataView。
此函数不会自动计算关联的公钥。可以
使用diffieHellman.setPublicKey()或diffieHellman.generateKeys()手动提供公钥或自动导出公钥。
diffieHellman.setPublicKey(publicKey[, encoding])#
设置 Diffie-Hellman 公钥。如果提供了
encoding参数,则publicKey应该是一个字符串。如果未提供encoding ,则publicKey预计为Buffer、TypedArray或DataView。
diffieHellman.verifyError#
包含在DiffieHellman对象初始化期间执行的检查所产生的任何警告和/或错误的位字段。
以下值对此属性有效(如node:constants模块中所定义):
DH_CHECK_P_NOT_SAFE_PRIMEDH_CHECK_P_NOT_PRIMEDH_UNABLE_TO_CHECK_GENERATORDH_NOT_SUITABLE_GENERATOR
类:DiffieHellmanGroup#
DiffieHellmanGroup类采用众所周知的 modp 组作为其参数。它的工作原理与DiffieHellman相同,只是它不允许在创建后更改其键。换句话说,它不实现setPublicKey()
或setPrivateKey()方法。
const { createDiffieHellmanGroup } = await import('node:crypto');
const dh = createDiffieHellmanGroup('modp16');const { createDiffieHellmanGroup } = require('node:crypto');
const dh = createDiffieHellmanGroup('modp16');
支持以下组:
'modp14'(2048 位,RFC 3526第 3 节)'modp15'(3072 位,RFC 3526第 4 节)'modp16'(4096 位,RFC 3526第 5 节)'modp17'(6144 位,RFC 3526第 6 节)'modp18'(8192 位,RFC 3526第 7 节)
以下组仍然受支持但已弃用(请参阅注意事项):
这些已弃用的组可能会在 Node.js 的未来版本中删除。
类:ECDH#
ECDH类是用于创建椭圆曲线 Diffie-Hellman (ECDH) 密钥交换的实用程序。
可以使用
crypto.createECDH()函数创建ECDH 类的实例。
import assert from 'node:assert';
const {
createECDH,
} = await import('node:crypto');
// Generate Alice's keys...
const alice = createECDH('secp521r1');
const aliceKey = alice.generateKeys();
// Generate Bob's keys...
const bob = createECDH('secp521r1');
const bobKey = bob.generateKeys();
// Exchange and generate the secret...
const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
// OKconst assert = require('node:assert');
const {
createECDH,
} = require('node:crypto');
// Generate Alice's keys...
const alice = createECDH('secp521r1');
const aliceKey = alice.generateKeys();
// Generate Bob's keys...
const bob = createECDH('secp521r1');
const bobKey = bob.generateKeys();
// Exchange and generate the secret...
const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);
assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
// OK
静态方法:ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])#
key<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>curve<字符串>inputEncoding<string>key字符串的编码。outputEncoding<string>返回值的编码。format<字符串> 默认:'uncompressed'- 返回:<缓冲区> | <字符串>
将key和curve指定的 EC Diffie-Hellman 公钥转换为format指定的格式。format参数指定点编码,可以是'compressed'、'uncompressed'或'hybrid'。提供的密钥使用指定的inputEncoding进行解释,返回的密钥使用指定的outputEncoding进行编码。
使用crypto.getCurves()获取可用曲线名称的列表。在最近的 OpenSSL 版本中,openssl ecparam -list_curves还将显示每个可用椭圆曲线的名称和描述。
如果未指定format,则点将以'uncompressed'
格式返回。
如果未提供inputEncoding ,则key预计为Buffer、
TypedArray或DataView。
示例(解压缩密钥):
const {
createECDH,
ECDH,
} = await import('node:crypto');
const ecdh = createECDH('secp256k1');
ecdh.generateKeys();
const compressedKey = ecdh.getPublicKey('hex', 'compressed');
const uncompressedKey = ECDH.convertKey(compressedKey,
'secp256k1',
'hex',
'hex',
'uncompressed');
// The converted key and the uncompressed public key should be the same
console.log(uncompressedKey === ecdh.getPublicKey('hex'));const {
createECDH,
ECDH,
} = require('node:crypto');
const ecdh = createECDH('secp256k1');
ecdh.generateKeys();
const compressedKey = ecdh.getPublicKey('hex', 'compressed');
const uncompressedKey = ECDH.convertKey(compressedKey,
'secp256k1',
'hex',
'hex',
'uncompressed');
// The converted key and the uncompressed public key should be the same
console.log(uncompressedKey === ecdh.getPublicKey('hex'));
ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])#
otherPublicKey<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>inputEncoding<string>otherPublicKey字符串的编码。outputEncoding<string>返回值的编码。- 返回:<缓冲区> | <字符串>
使用otherPublicKey作为另一方的公钥计算共享密钥,并返回计算出的共享密钥。提供的密钥使用指定的inputEncoding进行解释,返回的密钥使用指定的outputEncoding进行编码。如果未提供inputEncoding ,则otherPublicKey预计为Buffer、TypedArray或
DataView。
如果给出outputEncoding将返回一个字符串;否则
返回Buffer 。
当otherPublicKey
位于椭圆曲线之外时, ecdh.computeSecret将抛出
ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY错误。由于otherPublicKey通常是由远程用户通过不安全的网络提供的,因此请务必相应地处理此异常。
ecdh.generateKeys([encoding[, format]])#
生成私有和公共 EC Diffie-Hellman 密钥值,并返回指定的format和encoding中的公钥。这个密钥应该转移给对方。
format参数指定点编码,可以是'compressed'或
'uncompressed'。如果未指定format,则该点将以
'uncompressed'格式返回。
如果提供了encoding,则返回一个字符串;否则
返回Buffer 。
ecdh.getPrivateKey([encoding])#
如果指定了encoding,则返回一个字符串;否则返回Buffer 。
ecdh.getPublicKey([encoding][, format])#
encoding<string>返回值的编码。format<字符串> 默认值:'uncompressed'- 返回:<缓冲区> | <string>指定的
encoding和format中的 EC Diffie-Hellman 公钥 。
format参数指定点编码,可以是'compressed'或
'uncompressed'。如果未指定format ,则点将以
'uncompressed'格式返回。
如果指定了encoding,则返回一个字符串;否则返回Buffer 。
ecdh.setPrivateKey(privateKey[, encoding])#
设置 EC Diffie-Hellman 私钥。如果提供了encoding ,则privateKey应该是一个字符串;否则privateKey预计为Buffer、
TypedArray或DataView。
如果privateKey对于创建ECDH对象时指定的曲线无效,则会引发错误。设置私钥后,还会生成关联的公共点(密钥)并将其设置在ECDH对象中。
ecdh.setPublicKey(publicKey[, encoding])#
设置 EC Diffie-Hellman 公钥。如果提供了encoding,则publicKey应该是一个字符串;否则应为Buffer、TypedArray或DataView 。
通常没有理由调用此方法,因为ECDH
仅需要私钥和另一方的公钥来计算共享秘密。通常会调用ecdh.generateKeys()或
ecdh.setPrivateKey() 。ecdh.setPrivateKey()方法尝试生成与所设置的私钥关联的公共点/密钥。
示例(获取共享秘密):
const {
createECDH,
createHash,
} = await import('node:crypto');
const alice = createECDH('secp256k1');
const bob = createECDH('secp256k1');
// This is a shortcut way of specifying one of Alice's previous private
// keys. It would be unwise to use such a predictable private key in a real
// application.
alice.setPrivateKey(
createHash('sha256').update('alice', 'utf8').digest(),
);
// Bob uses a newly generated cryptographically strong
// pseudorandom key pair
bob.generateKeys();
const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
// aliceSecret and bobSecret should be the same shared secret value
console.log(aliceSecret === bobSecret);const {
createECDH,
createHash,
} = require('node:crypto');
const alice = createECDH('secp256k1');
const bob = createECDH('secp256k1');
// This is a shortcut way of specifying one of Alice's previous private
// keys. It would be unwise to use such a predictable private key in a real
// application.
alice.setPrivateKey(
createHash('sha256').update('alice', 'utf8').digest(),
);
// Bob uses a newly generated cryptographically strong
// pseudorandom key pair
bob.generateKeys();
const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
// aliceSecret and bobSecret should be the same shared secret value
console.log(aliceSecret === bobSecret);
类:Hash#
Hash类是用于创建数据哈希摘要的实用程序。它可以通过以下两种方式之一使用:
- 作为可读可写的流,其中写入数据以在可读端生成计算的哈希摘要,或者
- 使用
hash.update()和hash.digest()方法生成计算的哈希值。
crypto.createHash()方法用于创建Hash实例。
不应使用new关键字直接创建 Hash 对象。
示例:使用Hash对象作为流:
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();const {
createHash,
} = require('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();
示例:使用Hash和管道流:
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);const { createReadStream } = require('node:fs');
const { createHash } = require('node:crypto');
const { stdout } = require('node:process');
const hash = createHash('sha256');
const input = createReadStream('test.js');
input.pipe(hash).setEncoding('hex').pipe(stdout);
示例:使用hash.update()和hash.digest()方法:
const {
createHash,
} = await import('node:crypto');
const hash = createHash('sha256');
hash.update('some data to hash');
console.log(hash.digest('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50const {
createHash,
} = require('node:crypto');
const hash = createHash('sha256');
hash.update('some data to hash');
console.log(hash.digest('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
hash.copy([options])#
options<对象>stream.transform选项- 返回:<哈希值>
创建一个新的Hash对象,其中包含当前Hash对象的内部状态的深层副本。
可选的options参数控制流行为。对于 XOF 哈希函数(例如'shake256' ),可以使用outputLength选项指定所需的输出长度(以字节为单位)。
在调用hash.digest()方法后尝试复制Hash对象时,会引发错误。
// 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.// Calculate a rolling hash.
const {
createHash,
} = require('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.
hash.digest([encoding])#
计算要进行哈希处理的所有数据的摘要(使用
hash.update()方法)。如果提供了encoding将返回一个字符串;否则返回Buffer 。
调用hash.digest()方法后,无法再次使用Hash对象。多次调用将导致抛出错误。
hash.update(data[, inputEncoding])#
使用给定的data更新哈希内容,其编码在inputEncoding中给出。如果未提供encoding ,并且data是字符串,则强制执行'utf8'编码。如果data是Buffer、TypedArray或
DataView,则inputEncoding会被忽略。
当新数据流式传输时,可以多次调用此方法。
类:Hmac#
Hmac类是用于创建加密 HMAC 摘要的实用程序。它可以通过以下两种方式之一使用:
- 作为可读可写的流,写入数据以在可读端生成计算出的 HMAC 摘要,或者
- 使用
hmac.update()和hmac.digest()方法生成计算的 HMAC 摘要。
crypto.createHmac()方法用于创建Hmac实例。Hmac
对象不能直接使用new关键字创建。
示例:使用Hmac对象作为流:
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();const {
createHmac,
} = require('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();
示例:使用Hmac和管道流:
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);const {
createReadStream,
} = require('node:fs');
const {
createHmac,
} = require('node:crypto');
const { stdout } = require('node:process');
const hmac = createHmac('sha256', 'a secret');
const input = createReadStream('test.js');
input.pipe(hmac).pipe(stdout);
示例:使用hmac.update()和hmac.digest()方法:
const {
createHmac,
} = await import('node:crypto');
const hmac = createHmac('sha256', 'a secret');
hmac.update('some data to hash');
console.log(hmac.digest('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77econst {
createHmac,
} = require('node:crypto');
const hmac = createHmac('sha256', 'a secret');
hmac.update('some data to hash');
console.log(hmac.digest('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
hmac.digest([encoding])#
计算使用hmac.update()传递的所有数据的 HMAC 摘要。如果提供了encoding,则返回一个字符串;否则返回Buffer ;
调用hmac.digest()后,不能再次使用Hmac对象。多次调用hmac.digest()将导致抛出错误。
hmac.update(data[, inputEncoding])#
使用给定的data更新Hmac内容,其编码在inputEncoding中给出。如果未提供encoding ,并且data是字符串,则强制执行'utf8'编码。如果data是Buffer、TypedArray或
DataView,则inputEncoding会被忽略。
当新数据流式传输时,可以多次调用此方法。
类:KeyObject#
Node.js 使用KeyObject类来表示对称或非对称密钥,每种密钥公开不同的函数。
crypto.createSecretKey()、crypto.createPublicKey()和
crypto.createPrivateKey()方法用于创建KeyObject
实例。不应使用new 关键字直接创建 KeyObject对象
。
由于改进的安全功能,大多数应用程序应考虑使用新的KeyObject API,而不是将密钥作为字符串或Buffer传递。
KeyObject实例可以通过postMessage()传递给其他线程。接收方获得克隆的KeyObject,并且KeyObject不需要在transferList参数中列出。
静态方法:KeyObject.from(key)#
key<加密密钥>- 返回:<KeyObject>
示例:将CryptoKey实例转换为KeyObject:
const { webcrypto, KeyObject } = await import('node:crypto');
const { subtle } = webcrypto;
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)const {
webcrypto: {
subtle,
},
KeyObject,
} = require('node:crypto');
(async function() {
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)
})();
keyObject.asymmetricKeyDetails#
此属性仅存在于非对称密钥上。根据密钥的类型,该对象包含有关密钥的信息。通过此属性获得的任何信息都不能用于唯一标识密钥或损害密钥的安全性。
对于 RSA-PSS 密钥,如果密钥材料包含RSASSA-PSS-params序列,则将设置 hashAlgorithm、mgf1HashAlgorithm和saltLength属性。
其他关键细节可能会通过此 API 使用附加属性公开。
keyObject.asymmetricKeyType#
对于非对称密钥,此属性表示密钥的类型。支持的密钥类型有:
'rsa'(OID 1.2.840.113549.1.1.1)'rsa-pss'(OID 1.2.840.113549.1.1.10)'dsa'(OID 1.2.840.10040.4.1)'ec'(OID 1.2.840.10045.2.1)'x25519'(OID 1.3.101.110)'x448'(OID 1.3.101.111)'ed25519'(OID 1.3.101.112)'ed448'(OID 1.3.101.113)'dh'(OID 1.2.840.113549.1.3.1)
对于无法识别的KeyObject类型和对称密钥,此属性为undefined 。
keyObject.export([options])#
对于对称密钥,可以使用以下编码选项:
format:<string>必须为'buffer'(默认)或'jwk'。
对于公钥,可以使用以下编码选项:
type:<string>必须是'pkcs1'(仅限 RSA)或'spki'之一。format:<string>必须是'pem'、'der'或'jwk'。
对于私钥,可以使用以下编码选项:
type:<string>必须是'pkcs1'(仅限 RSA)、'pkcs8'或'sec1'(仅限 EC)之一。format:<string>必须是'pem'、'der'或'jwk'。cipher:<string>如果指定,则将使用基于 PKCS#5 v2.0 密码的加密,使用给定的cipher和passphrase来加密私钥。passphrase: <字符串> | <Buffer>用于加密的密码,请参阅cipher。
结果类型取决于所选的编码格式,当 PEM 时结果是字符串,当 DER 时结果将是包含编码为 DER 的数据的缓冲区,当JWK时结果将是对象。
可以使用cipher和format选项的组合来加密 PKCS#1、SEC1 和 PKCS#8 类型密钥。PKCS#8 type可以与任何format一起使用
,通过指定cipher来加密任何密钥算法(RSA、EC 或 DH)
。当使用
PEM format时,只能通过指定cipher来加密 PKCS#1 和 SEC1 。为了获得最大兼容性,请使用 PKCS#8 作为加密私钥。由于 PKCS#8 定义了自己的加密机制,因此在加密 PKCS#8 密钥时不支持 PEM 级加密。有关 PKCS#8 加密的信息,请参阅RFC 5208 ;有关 PKCS#1 和 SEC1 加密的信息,请参阅RFC 1421。
keyObject.equals(otherKeyObject)#
otherKeyObject:<KeyObject>与KeyObject进行比较的keyObject。- 返回:<布尔值>
根据键是否具有完全相同的类型、值和参数,返回true或false 。此方法不是
常数时间。
keyObject.symmetricKeySize#
对于秘密密钥,此属性表示密钥的大小(以字节为单位)。对于非对称密钥,此属性为undefined。
keyObject.type#
根据此KeyObject的类型,此属性
对于秘密(对称)密钥为'secret' ,对于公共(非对称)密钥为'public'或'private'用于私钥(非对称)。
类:Sign#
Sign类是用于生成签名的实用程序。它可以通过以下两种方式之一使用:
- 作为可写流,写入要签名的数据,并
使用
sign.sign()方法生成并返回签名,或者 - 使用
sign.update()和sign.sign()方法生成签名。
crypto.createSign()方法用于创建Sign实例。参数是要使用的哈希函数的字符串名称。Sign对象不能直接使用new关键字创建。
示例:使用Sign和Verify对象作为流:
const {
generateKeyPairSync,
createSign,
createVerify,
} = await import('node:crypto');
const { privateKey, publicKey } = generateKeyPairSync('ec', {
namedCurve: 'sect239k1',
});
const sign = createSign('SHA256');
sign.write('some data to sign');
sign.end();
const signature = sign.sign(privateKey, 'hex');
const verify = createVerify('SHA256');
verify.write('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature, 'hex'));
// Prints: trueconst {
generateKeyPairSync,
createSign,
createVerify,
} = require('node:crypto');
const { privateKey, publicKey } = generateKeyPairSync('ec', {
namedCurve: 'sect239k1',
});
const sign = createSign('SHA256');
sign.write('some data to sign');
sign.end();
const signature = sign.sign(privateKey, 'hex');
const verify = createVerify('SHA256');
verify.write('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature, 'hex'));
// Prints: true
示例:使用sign.update()和verify.update()方法:
const {
generateKeyPairSync,
createSign,
createVerify,
} = await import('node:crypto');
const { privateKey, publicKey } = generateKeyPairSync('rsa', {
modulusLength: 2048,
});
const sign = createSign('SHA256');
sign.update('some data to sign');
sign.end();
const signature = sign.sign(privateKey);
const verify = createVerify('SHA256');
verify.update('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature));
// Prints: trueconst {
generateKeyPairSync,
createSign,
createVerify,
} = require('node:crypto');
const { privateKey, publicKey } = generateKeyPairSync('rsa', {
modulusLength: 2048,
});
const sign = createSign('SHA256');
sign.update('some data to sign');
sign.end();
const signature = sign.sign(privateKey);
const verify = createVerify('SHA256');
verify.update('some data to sign');
verify.end();
console.log(verify.verify(publicKey, signature));
// Prints: true
sign.sign(privateKey[, outputEncoding])#
privateKey<对象> | <字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <关键对象> | <加密密钥>outputEncoding<string>返回值的编码。- 返回:<缓冲区> | <字符串>
使用sign.update()或sign.write()计算传递的所有数据的签名
。
如果privateKey不是KeyObject,则此函数的行为就像
privateKey已传递给crypto.createPrivateKey()。如果它是一个对象,可以传递以下附加属性:
-
dsaEncoding<string>对于 DSA 和 ECDSA,此选项指定生成的签名的格式。它可以是以下之一:'der'(默认):DER 编码的 ASN.1 签名结构编码(r, s)。'ieee-p1363': IEEE-P1363 中建议的签名格式r || s。
-
padding<integer> RSA 的可选填充值,以下之一:crypto.constants.RSA_PKCS1_PADDING(默认)crypto.constants.RSA_PKCS1_PSS_PADDING
RSA_PKCS1_PSS_PADDING将使用 MGF1,其哈希函数与用于对RFC 4055第 3.1 节中指定的消息进行签名的哈希函数相同,除非已按照RFC 4055第 3.3 节的规定将 MGF1 哈希函数指定为密钥的一部分。 -
saltLength<integer>当填充为RSA_PKCS1_PSS_PADDING时的盐长度。特殊值crypto.constants.RSA_PSS_SALTLEN_DIGEST将盐长度设置为摘要大小,crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN(默认)将其设置为最大允许值。
如果提供了outputEncoding,则返回一个字符串;否则
返回Buffer 。
调用 sign.sign() 方法后,不能再次使用Sign对象。多次调用sign.sign()将导致抛出错误。
sign.update(data[, inputEncoding])#
使用给定的data更新Sign内容,其编码在inputEncoding中给出。如果未提供encoding ,并且data是字符串,则强制执行'utf8'编码。如果data是Buffer、TypedArray或
DataView,则inputEncoding会被忽略。
当新数据流式传输时,可以多次调用此方法。
类:Verify#
Verify类是用于验证签名的实用程序。它可以通过以下两种方式之一使用:
- 作为可写流,其中写入的数据用于根据提供的签名进行验证,或者
- 使用
verify.update()和verify.verify()方法来验证签名。
crypto.createVerify()方法用于创建Verify实例。
Verify对象不能直接使用new关键字创建。
有关示例,请参阅Sign。
verify.update(data[, inputEncoding])#
使用给定的data更新Verify内容,其编码在inputEncoding中给出。如果未提供inputEncoding ,并且data是字符串,则强制执行'utf8'编码。如果data是Buffer、TypedArray或
DataView,则inputEncoding会被忽略。
当新数据流式传输时,可以多次调用此方法。
verify.verify(object, signature[, signatureEncoding])#
object<对象> | <字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <关键对象> | <加密密钥>signature<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>signatureEncoding<string>signature字符串的编码。- 返回:<boolean>
true或false,具体取决于数据和公钥签名的有效性。
使用给定的object和signature验证提供的数据。
如果object不是KeyObject,则此函数的行为就像
object已传递给crypto.createPublicKey()。如果它是一个对象,可以传递以下附加属性:
-
dsaEncoding<string>对于 DSA 和 ECDSA,此选项指定签名的格式。它可以是以下之一:'der'(默认):DER 编码的 ASN.1 签名结构编码(r, s)。'ieee-p1363': IEEE-P1363 中建议的签名格式r || s。
-
padding<integer> RSA 的可选填充值,以下之一:crypto.constants.RSA_PKCS1_PADDING(默认)crypto.constants.RSA_PKCS1_PSS_PADDING
RSA_PKCS1_PSS_PADDING将使用 MGF1,其哈希函数与RFC 4055第 3.1 节中指定的用于验证消息的哈希函数相同,除非已按照RFC 4055第 3.3 节的规定将 MGF1 哈希函数指定为密钥的一部分。 -
saltLength<integer>当填充为RSA_PKCS1_PSS_PADDING时的盐长度。特殊值crypto.constants.RSA_PSS_SALTLEN_DIGEST将盐长度设置为摘要大小,crypto.constants.RSA_PSS_SALTLEN_AUTO(默认)会自动确定它。
signature参数是先前计算的数据签名,位于signatureEncoding中。如果指定了signatureEncoding ,则signature应该是一个字符串;否则signature预计为Buffer、
TypedArray或DataView。
调用verify.verify()后,无法再次使用verify对象。多次调用verify.verify()将导致抛出错误。
由于公钥可以从私钥导出,因此可以传递私钥而不是公钥。
类:X509Certificate#
封装 X509 证书并提供对其信息的只读访问。
const { X509Certificate } = await import('node:crypto');
const x509 = new X509Certificate('{... pem encoded cert ...}');
console.log(x509.subject);const { X509Certificate } = require('node:crypto');
const x509 = new X509Certificate('{... pem encoded cert ...}');
console.log(x509.subject);
new X509Certificate(buffer)#
buffer<字符串> | <类型化数组> | <缓冲区> | <DataView> PEM 或 DER 编码的 X509 证书。
x509.ca#
- 类型:<boolean>如果这是证书颁发机构 (CA) 证书,则将为
true。
x509.checkEmail(email[, options])#
email<字符串>options<对象>subject<字符串>'default'、'always'或'never'。 默认值:'default'。
- 返回:<字符串> | <undefined>如果证书匹配,则
返回
email,如果不匹配,则返回undefined。
检查证书是否与给定的电子邮件地址匹配。
如果'subject'选项未定义或设置为'default',则仅当主题备用名称扩展不存在或不包含任何电子邮件地址时才考虑证书主题。
如果'subject'选项设置为'always',并且主题备用名称扩展不存在或不包含匹配的电子邮件地址,则将考虑证书主题。
如果'subject'选项设置为'never',则永远不会考虑证书主题,即使证书不包含主题备用名称。
x509.checkHost(name[, options])#
name<字符串>options<对象>- 返回:<字符串> | <undefined>返回与
name匹配的主题名称,如果没有主题名称与name匹配,则返回undefined。
检查证书是否与给定的主机名匹配。
如果证书与给定的主机名匹配,则返回匹配的主题名称。返回的名称可能是完全匹配的(例如,foo.example.com),也可能包含通配符(例如,*.example.com)。由于主机名比较不区分大小写,因此返回的使用者名称的大小写也可能与给定的name不同。
如果'subject'选项未定义或设置为'default',则仅当主题备用名称扩展不存在或不包含任何 DNS 名称时才考虑证书主题。此行为与RFC 2818 (“HTTP Over TLS”)一致
。
如果'subject'选项设置为'always',并且使用者备用名称扩展不存在或不包含匹配的 DNS 名称,则将考虑证书使用者。
如果'subject'选项设置为'never',则永远不会考虑证书主题,即使证书不包含主题备用名称。
x509.checkIP(ip)#
ip<字符串>- 返回:<字符串> | <undefined>如果证书匹配,则
返回
ip,如果不匹配,则返回undefined。
检查证书是否与给定的 IP 地址(IPv4 或 IPv6)匹配。
仅考虑RFC 5280 iPAddress主题备用名称,并且它们必须与给定的ip地址完全匹配。其他主题备用名称以及证书的主题字段将被忽略。
x509.checkIssued(otherCert)#
检查此证书是否由给定的otherCert颁发。
x509.checkPrivateKey(privateKey)#
privateKey<KeyObject>私钥。- 返回:<布尔值>
检查此证书的公钥与给定的私钥是否一致。
x509.fingerprint#
- 类型:<字符串>
该证书的 SHA-1 指纹。
由于 SHA-1 在加密上已被破坏,并且 SHA-1 的安全性明显比常用的证书签名算法差,因此请考虑改用x509.fingerprint256。
x509.fingerprint256#
- 类型:<字符串>
该证书的 SHA-256 指纹。
x509.fingerprint512#
- 类型:<字符串>
该证书的 SHA-512 指纹。
由于计算 SHA-256 指纹通常速度更快,而且其大小仅为 SHA-512 指纹的一半,因此x509.fingerprint256可能是更好的选择。虽然 SHA-512 通常可以提供更高级别的安全性,但 SHA-256 的安全性与大多数常用于签署证书的算法的安全性相匹配。
x509.infoAccess#
- 类型:<字符串>
证书的权限信息访问扩展的文本表示。
这是一个换行分隔的访问描述列表。每行以访问方法和访问位置的类型开头,后跟冒号和与访问位置关联的值。
在表示访问方法和访问位置类型的前缀之后,每行的其余部分可能会用引号引起来,以指示该值是 JSON 字符串文字。为了向后兼容,Node.js 仅在必要时在此属性中使用 JSON 字符串文字以避免歧义。第三方代码应准备好处理两种可能的条目格式。
x509.issuer#
- 类型:<字符串>
该证书中包含颁发者标识。
x509.issuerCertificate#
- 类型:<X509证书>
颁发者证书或undefined(如果颁发者证书不可用)。
x509.keyUsage#
- 类型:<字符串[]>
详细说明此证书的密钥用法的数组。
x509.publicKey#
- 类型:<关键对象>
此证书的公钥<KeyObject> 。
x509.raw#
- 类型:<缓冲区>
包含此证书的 DER 编码的Buffer 。
x509.serialNumber#
- 类型:<字符串>
该证书的序列号。
序列号由证书颁发机构分配,并不唯一标识证书。考虑使用x509.fingerprint256作为唯一标识符。
x509.subject#
- 类型:<字符串>
本证书的完整主题。
x509.subjectAltName#
- 类型:<字符串>
为此证书指定的使用者备用名称。
这是一个以逗号分隔的主题备用名称列表。每个条目都以一个字符串开头,该字符串标识主题备用名称的类型,后跟冒号和与该条目关联的值。
早期版本的 Node.js 错误地认为以两个字符序列', '分割此属性是安全的(请参阅CVE-2021-44532)。但是,恶意证书和合法证书都可能包含主题备用名称,这些备用名称在表示为字符串时包含此序列。
在表示条目类型的前缀之后,每个条目的其余部分可能会用引号引起来,以指示该值是 JSON 字符串文字。为了向后兼容,Node.js 仅在必要时在此属性中使用 JSON 字符串文字以避免歧义。第三方代码应准备好处理两种可能的条目格式。
x509.toJSON()#
- 类型:<字符串>
X509 证书没有标准的 JSON 编码。toJSON()方法
返回包含 PEM 编码证书的字符串。
x509.toLegacyObject()#
- 类型:<对象>
使用旧 证书对象编码返回有关此证书的信息。
x509.toString()#
- 类型:<字符串>
返回 PEM 编码的证书。
x509.validFrom#
- 类型:<字符串>
该证书被视为有效的日期/时间。
x509.validTo#
- 类型:<字符串>
该证书被视为有效的日期/时间。
x509.verify(publicKey)#
publicKey<KeyObject>公钥。- 返回:<布尔值>
验证此证书是否由给定的公钥签名。不对证书执行任何其他验证检查。
node:crypto模块方法和属性#
crypto.constants#
包含用于加密和安全相关操作的常用常量的对象。当前定义的具体常量在加密常量中描述 。
crypto.DEFAULT_ENCODING#
用于可以采用字符串或缓冲区的函数的默认编码。默认值为'buffer',这使得方法默认为Buffer对象。
提供crypto.DEFAULT_ENCODING机制是为了向后兼容那些期望'latin1'作为默认编码的旧程序。
新应用程序的默认值应为'buffer'。
该属性已被弃用。
crypto.fips#
用于检查和控制当前是否正在使用符合 FIPS 的加密提供程序的属性。设置为 true 需要 Node.js 的 FIPS 构建。
该属性已被弃用。请改用crypto.setFips()和
crypto.getFips()。
crypto.checkPrime(candidate[, options], callback)#
candidate<ArrayBuffer> | <共享数组缓冲区> | <类型化数组> | <缓冲区> | <数据视图> | <bigint> 可能的素数,编码为任意长度的大端字节序序列。options<对象>checks<number>要执行的 Miller-Rabin 概率素性迭代的次数。当值为0(零)时,将使用多次检查,对于随机输入产生最多 2 -64的误报率。选择多种支票时必须小心。 有关更多详细信息,请参阅 OpenSSL 文档中的BN_is_prime_ex函数nchecks选项。默认值:0
callback<函数>err<Error>如果检查期间发生错误,则设置为<Error>对象。result<boolean>true如果候选者是错误概率小于0.25 ** options.checks的素数。
检查candidate的素数。
crypto.checkPrimeSync(candidate[, options])#
candidate<ArrayBuffer> | <共享数组缓冲区> | <类型化数组> | <缓冲区> | <数据视图> | <bigint> 可能的素数,编码为任意长度的大端字节序序列。options<对象>checks<number>要执行的 Miller-Rabin 概率素性迭代的次数。当值为0(零)时,将使用多次检查,对于随机输入产生最多 2 -64的误报率。选择多种支票时必须小心。 有关更多详细信息,请参阅 OpenSSL 文档中的BN_is_prime_ex函数nchecks选项。默认值:0
- 返回:<boolean>
true如果候选者是错误概率小于0.25 ** options.checks的素数。
检查candidate的素数。
crypto.createCipher(algorithm, password[, options])#
crypto.createCipheriv()代替。algorithm<字符串>password<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>options<对象>stream.transform选项- 返回:<密码>
创建并返回一个使用给定algorithm和password 的 Cipher对象。
options参数控制流行为,并且是可选的,除非使用CCM 或 OCB 模式下的密码(例如'aes-128-ccm' )。在这种情况下,
需要authTagLength选项,并指定身份验证标记的长度(以字节为单位),请参阅CCM 模式。在 GCM 模式下,
不需要authTagLength选项,但可用于设置getAuthTag()返回的身份验证标记的长度,默认为 16 字节。对于chacha20-poly1305,authTagLength选项默认为 16 个字节。
algorithm依赖于 OpenSSL,例如'aes192'等。在最近的 OpenSSL 版本中,openssl list -cipher-algorithms将显示可用的密码算法。
password用于导出密钥和初始化向量 (IV)。该值必须是'latin1'编码字符串、Buffer、 TypedArray或DataView。
此函数在语义上对于所有受支持的密码来说都是不安全的,并且对于计数器模式(例如 CTR、GCM 或 CCM)下的密码来说存在致命缺陷。
crypto.createCipher()的实现使用 OpenSSL 函数EVP_BytesToKey派生密钥,摘要算法设置为 MD5,一次迭代,无盐。缺少盐允许字典攻击,因为相同的密码总是创建相同的密钥。低迭代次数和非加密安全散列算法允许非常快速地测试密码。
根据 OpenSSL 使用更现代的算法而不是
EVP_BytesToKey的建议,建议开发人员使用crypto.scrypt()自行派生密钥和 IV ,并使用crypto.createCipheriv()
创建Cipher对象。用户不应在crypto.createCipher()中使用具有计数器模式的密码(例如 CTR、GCM 或 CCM) 。使用它们时会发出警告,以避免 IV 重用导致漏洞的风险。对于 GCM 中重用 IV 的情况,请参阅Nonce-Disrespecting Adversaries了解详细信息。
crypto.createCipheriv(algorithm, key, iv[, options])#
algorithm<字符串>key<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <关键对象> | <加密密钥>iv<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <空>options<对象>stream.transform选项- 返回:<密码>
使用给定的algorithm、key和初始化向量 ( iv )创建并返回一个Cipher对象。
options参数控制流行为,并且是可选的,除非使用CCM 或 OCB 模式下的密码(例如'aes-128-ccm' )。在这种情况下,
需要authTagLength选项,并指定身份验证标记的长度(以字节为单位),请参阅CCM 模式。在 GCM 模式下,
不需要authTagLength选项,但可用于设置getAuthTag()返回的身份验证标记的长度,默认为 16 字节。对于chacha20-poly1305,authTagLength选项默认为 16 个字节。
algorithm依赖于 OpenSSL,例如'aes192'等。在最近的 OpenSSL 版本中,openssl list -cipher-algorithms将显示可用的密码算法。
key是algorithm使用的原始密钥,而iv是
初始化向量。两个参数都必须是'utf8'编码的字符串、
Buffers、TypedArray或DataView。key可以选择是类型为secret的KeyObject。如果密码不需要初始化向量,则iv可以是null。
传递key或iv的字符串时,请考虑
使用字符串作为加密 API 的输入时的注意事项。
初始化向量应该是不可预测的且唯一的;理想情况下,它们在加密上是随机的。它们不必是秘密的:IV 通常只是添加到未加密的密文消息中。有些东西必须是不可预测的和独特的,但不一定是秘密的,这听起来可能很矛盾。请记住,攻击者不能提前预测给定的 IV 是什么。
crypto.createDecipher(algorithm, password[, options])#
crypto.createDecipheriv()代替。algorithm<字符串>password<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>options<对象>stream.transform选项- 返回:<解密>
创建并返回一个使用给定algorithm和
password(键)的Decipher对象。
options参数控制流行为,并且是可选的,除非使用CCM 或 OCB 模式下的密码(例如'aes-128-ccm' )。在这种情况下,
需要authTagLength选项,并指定身份验证标记的长度(以字节为单位),请参阅CCM 模式。对于chacha20-poly1305,authTagLength选项默认为 16 个字节。
此函数在语义上对于所有受支持的密码来说都是不安全的,并且对于计数器模式(例如 CTR、GCM 或 CCM)下的密码来说存在致命缺陷。
crypto.createDecipher()的实现使用 OpenSSL 函数EVP_BytesToKey派生密钥,摘要算法设置为 MD5,一次迭代,无盐。缺少盐允许字典攻击,因为相同的密码总是创建相同的密钥。低迭代次数和非加密安全散列算法允许非常快速地测试密码。
根据 OpenSSL 使用更现代的算法而不是
EVP_BytesToKey的建议,建议开发人员使用crypto.scrypt()自行派生密钥和 IV ,并使用crypto.createDecipheriv()
创建Decipher对象。
crypto.createDecipheriv(algorithm, key, iv[, options])#
algorithm<字符串>key<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <关键对象> | <加密密钥>iv<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <空>options<对象>stream.transform选项- 返回:<解密>
创建并返回一个使用给定的 algorithm 、 key 和初始化向量 ( iv ) 的Decipher对象。
options参数控制流行为,并且是可选的,除非使用CCM 或 OCB 模式下的密码(例如'aes-128-ccm' )。在这种情况下,
需要authTagLength选项,并指定身份验证标记的长度(以字节为单位),请参阅CCM 模式。在 GCM 模式下,
不需要authTagLength选项,但可用于将接受的身份验证标记限制为具有指定长度的标记。对于chacha20-poly1305,authTagLength选项默认为 16 个字节。
algorithm依赖于 OpenSSL,例如'aes192'等。在最近的 OpenSSL 版本中,openssl list -cipher-algorithms将显示可用的密码算法。
key是algorithm使用的原始密钥,而iv是
初始化向量。两个参数都必须是'utf8'编码的字符串、
Buffers、TypedArray或DataView。key可以选择是类型为secret的KeyObject。如果密码不需要初始化向量,则iv可以是null。
传递key或iv的字符串时,请考虑
使用字符串作为加密 API 的输入时的注意事项。
初始化向量应该是不可预测的且唯一的;理想情况下,它们在加密上是随机的。它们不必是秘密的:IV 通常只是添加到未加密的密文消息中。有些东西必须是不可预测的和独特的,但不一定是秘密的,这听起来可能很矛盾。请记住,攻击者不能提前预测给定的 IV 是什么。
crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])#
prime<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>primeEncoding<string>prime字符串的编码。generator<数字> | <字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> 默认:2generatorEncoding<string>generator字符串的编码。- 返回:<迪菲赫尔曼>
使用提供的prime和可选的特定generator创建一个DiffieHellman密钥交换对象。
generator参数可以是数字、字符串或Buffer。如果
未指定generator ,则使用值2 。
如果指定了primeEncoding ,则prime应该是一个字符串;否则需要Buffer、TypedArray或DataView 。
如果指定了generatorEncoding ,则generator应该是一个字符串;否则应为数字Buffer、TypedArray或DataView 。
crypto.createDiffieHellman(primeLength[, generator])#
创建一个DiffieHellman密钥交换对象,并使用可选的特定数字generator生成 primeLength 位的质
数。如果未指定generator ,则使用值2 。
crypto.createDiffieHellmanGroup(name)#
name<字符串>- 返回:<DiffieHellmanGroup>
crypto.createECDH(curveName)#
使用由 curveName 字符串指定的预定义曲线创建椭圆曲线 Diffie-Hellman ( ECDH ) 密钥交换对象。使用
crypto.getCurves()获取可用曲线名称的列表。在最近的 OpenSSL 版本中,openssl ecparam -list_curves还将显示每个可用椭圆曲线的名称和描述。
crypto.createHash(algorithm[, options])#
algorithm<字符串>options<对象>stream.transform选项- 返回:<哈希值>
创建并返回一个Hash对象,该对象可用于使用给定的algorithm生成哈希摘要。可选的options参数控制流行为。对于 XOF 哈希函数(例如'shake256' ),可以使用outputLength选项指定所需的输出长度(以字节为单位)。
algorithm取决于平台上 OpenSSL 版本支持的可用算法。例如'sha256'、'sha512'等。在 OpenSSL 的最新版本中,openssl list -digest-algorithms将显示可用的摘要算法。
示例:生成文件的 sha256 和
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}`);
}
});const {
createReadStream,
} = require('node:fs');
const {
createHash,
} = require('node:crypto');
const { argv } = require('node:process');
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}`);
}
});
crypto.createHmac(algorithm, key[, options])#
algorithm<字符串>key<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <关键对象> | <加密密钥>options<对象>stream.transform选项encoding<string>当key是字符串时使用的字符串编码。
- 返回:<Hmac>
创建并返回一个使用给定algorithm和key 的 Hmac对象。可选的options参数控制流行为。
algorithm取决于平台上 OpenSSL 版本支持的可用算法。例如'sha256'、'sha512'等。在 OpenSSL 的最新版本中,openssl list -digest-algorithms将显示可用的摘要算法。
key是用于生成加密 HMAC 哈希的 HMAC 密钥。如果它是KeyObject,则其类型必须是secret。如果它是字符串,请
在使用字符串作为加密 API 的输入时考虑注意事项。如果它是从加密安全的熵源获取的,例如
crypto.randomBytes()或crypto.generateKey(),则其长度不应超过algorithm的块大小(例如 512 SHA-256 位)。
示例:生成文件的 sha256 HMAC
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}`);
}
});const {
createReadStream,
} = require('node:fs');
const {
createHmac,
} = require('node:crypto');
const { argv } = require('node:process');
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}`);
}
});
crypto.createPrivateKey(key)#
创建并返回包含私钥的新密钥对象。如果key是字符串或Buffer,则format被假定为'pem';否则,key
必须是具有上述属性的对象。
如果私钥已加密,则必须指定passphrase 。密码短语的长度限制为 1024 字节。
crypto.createPublicKey(key)#
创建并返回包含公钥的新密钥对象。如果key是字符串或Buffer,则format被假定为'pem';如果key是
类型为'private'的KeyObject,则公钥源自给定的私钥;否则,key必须是具有上述属性的对象。
如果格式为'pem',则'key'也可能是 X.509 证书。
由于公钥可以从私钥导出,因此可以传递私钥而不是公钥。在这种情况下,该函数的行为就像
调用了crypto.createPrivateKey() ,只不过返回的KeyObject的类型将为'public'并且私钥不能被调用。从返回的KeyObject中提取。同样,如果给出类型为
'private'的 KeyObject,则将返回类型为'public' 的新 KeyObject,并且不可能从返回的对象中提取私钥。
crypto.createSecretKey(key[, encoding])#
创建并返回一个新的密钥对象,其中包含用于对称加密或Hmac的密钥。
crypto.createSign(algorithm[, options])#
algorithm<字符串>options<对象>stream.Writable选项- 返回:<标志>
创建并返回一个使用给定algorithm的 Sign对象。使用
crypto.getHashes()获取可用摘要算法的名称。可选的options参数控制stream.Writable行为。
在某些情况下,可以使用签名算法的名称(例如'RSA-SHA256' )而不是摘要算法来创建Sign实例。这将使用相应的摘要算法。这并不适用于所有签名算法,例如'ecdsa-with-SHA256',因此最好始终使用摘要算法名称。
crypto.createVerify(algorithm[, options])#
algorithm<字符串>options<对象>stream.Writable选项- 返回:<验证>
创建并返回使用给定算法的Verify对象。使用crypto.getHashes()获取可用签名算法的名称数组。可选的options参数控制
stream.Writable行为。
在某些情况下,可以使用签名算法的名称(例如'RSA-SHA256' )而不是摘要算法来创建Verify实例。这将使用相应的摘要算法。这并不适用于所有签名算法,例如'ecdsa-with-SHA256',因此最好始终使用摘要算法名称。
crypto.diffieHellman(options)#
options:<对象>privateKey: <KeyObject>publicKey: <KeyObject>
- 返回:<缓冲区>
基于privateKey和publicKey计算 Diffie-Hellman 密钥。两个密钥必须具有相同的asymmetricKeyType,它必须是'dh'
(对于 Diffie-Hellman)、'ec'(对于 ECDH)、'x448'或'x25519'(对于 ECDH-ES)。
crypto.generateKey(type, options, callback)#
type:<string>生成的密钥的预期用途。目前接受的值为'hmac'和'aes'。options:<对象>length:<number>要生成的密钥的位长度。该值必须是大于 0 的值。- 如果
type为'hmac',则最小值为 8,最大长度为 2 31 -1。如果该值不是 8 的倍数,则生成的密钥将被截断为Math.floor(length / 8)。 - 如果
type为'aes',则长度必须为128、192或256之一。
- 如果
callback: <函数>err:<错误>key:<KeyObject>
异步生成给定length的新随机密钥。type将确定将在length上执行哪些验证。
const {
generateKey,
} = await import('node:crypto');
generateKey('hmac', { length: 512 }, (err, key) => {
if (err) throw err;
console.log(key.export().toString('hex')); // 46e..........620
});const {
generateKey,
} = require('node:crypto');
generateKey('hmac', { length: 512 }, (err, key) => {
if (err) throw err;
console.log(key.export().toString('hex')); // 46e..........620
});
生成的 HMAC 密钥的大小不应超过底层哈希函数的块大小。请参阅crypto.createHmac()了解更多信息。
crypto.generateKeyPair(type, options, callback)#
type:<string>必须为'rsa'、'rsa-pss'、'dsa'、'ec'、'ed25519'、'ed448'、'x25519'、'x448'或'dh'。options:<对象>modulusLength:<number>密钥大小(以位为单位)(RSA、DSA)。publicExponent:<number>公共索引 (RSA)。默认值:0x10001。hashAlgorithm:<string>消息摘要的名称 (RSA-PSS)。mgf1HashAlgorithm:<string> MGF1 (RSA-PSS) 使用的消息摘要的名称。saltLength:<number>最小盐长度(以字节为单位)(RSA-PSS)。divisorLength:<number>q的大小(以位 (DSA) 为单位)。namedCurve: <string>要使用的曲线名称 (EC)。prime:<Buffer>主要参数 (DH)。primeLength:<number>素数长度(以位 (DH) 为单位)。generator:<number>自定义生成器 (DH)。默认值:2。groupName:<字符串> Diffie-Hellman 组名称 (DH)。请参阅crypto.getDiffieHellman()。paramEncoding:<string>必须为'named'或'explicit'(EC)。 默认值:'named'。publicKeyEncoding:<对象>请参阅keyObject.export()。privateKeyEncoding:<对象>请参阅keyObject.export()。
callback: <函数>
生成给定type的新非对称密钥对。目前支持 RSA、RSA-PSS、DSA、EC、Ed25519、Ed448、X25519、X448 和 DH。
如果指定了publicKeyEncoding或privateKeyEncoding,则此函数的行为就好像已对其结果调用了keyObject.export() 。否则,键的相应部分将作为KeyObject返回。
建议将公钥编码为'spki',私钥编码为
'pkcs8',并进行加密以便长期存储:
const {
generateKeyPair,
} = await import('node:crypto');
generateKeyPair('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: 'top secret',
},
}, (err, publicKey, privateKey) => {
// Handle errors and use the generated key pair.
});const {
generateKeyPair,
} = require('node:crypto');
generateKeyPair('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: 'top secret',
},
}, (err, publicKey, privateKey) => {
// Handle errors and use the generated key pair.
});
完成后,将调用callback ,并将err设置为undefined和
publicKey / privateKey表示生成的密钥一对。
如果此方法作为其util.promisify() ed 版本调用,它将返回一个Promise,其中包含publicKey和privateKey特性。
crypto.generateKeyPairSync(type, options)#
type:<string>必须为'rsa'、'rsa-pss'、'dsa'、'ec'、'ed25519'、'ed448'、'x25519'、'x448'或'dh'。options:<对象>modulusLength:<number>密钥大小(以位为单位)(RSA、DSA)。publicExponent:<number>公共索引 (RSA)。默认值:0x10001。hashAlgorithm:<string>消息摘要的名称 (RSA-PSS)。mgf1HashAlgorithm:<string> MGF1 (RSA-PSS) 使用的消息摘要的名称。saltLength:<number>最小盐长度(以字节为单位)(RSA-PSS)。divisorLength:<number>q的大小(以位 (DSA) 为单位)。namedCurve: <string>要使用的曲线名称 (EC)。prime: <Buffer>主参数 (DH)。primeLength:<number>素数长度(以位 (DH) 为单位)。generator:<number>自定义生成器 (DH)。默认值:2。groupName:<字符串> Diffie-Hellman 组名称 (DH)。请参阅crypto.getDiffieHellman()。paramEncoding:<string>必须为'named'或'explicit'(EC)。 默认值:'named'。publicKeyEncoding:<对象>请参阅keyObject.export()。privateKeyEncoding:<对象>请参阅keyObject.export()。
- 返回:<对象>
生成给定type的新非对称密钥对。目前支持 RSA、RSA-PSS、DSA、EC、Ed25519、Ed448、X25519、X448 和 DH。
如果指定了publicKeyEncoding或privateKeyEncoding,则此函数的行为就好像已对其结果调用了keyObject.export() 。否则,键的相应部分将作为KeyObject返回。
对公钥进行编码时,建议使用'spki'。对私钥进行编码时,建议使用具有强密码的'pkcs8',并对密码保密。
const {
generateKeyPairSync,
} = await import('node:crypto');
const {
publicKey,
privateKey,
} = generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: 'top secret',
},
});const {
generateKeyPairSync,
} = require('node:crypto');
const {
publicKey,
privateKey,
} = generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: 'top secret',
},
});
返回值{ publicKey, privateKey }代表生成的密钥对。当选择 PEM 编码时,相应的密钥将是一个字符串,否则它将是一个包含编码为 DER 的数据的缓冲区。
crypto.generateKeySync(type, options)#
type: <string>生成的密钥的预期用途。目前接受的值为'hmac'和'aes'。options:<对象>length:<number>要生成的密钥的位长度。- 如果
type为'hmac',则最小值为 8,最大长度为 2 31 -1。如果该值不是 8 的倍数,则生成的密钥将被截断为Math.floor(length / 8)。 - 如果
type为'aes',则长度必须为128、192或256之一。
- 如果
- 返回:<KeyObject>
同步生成给定length的新随机密钥。type将确定将在length上执行哪些验证。
const {
generateKeySync,
} = await import('node:crypto');
const key = generateKeySync('hmac', { length: 512 });
console.log(key.export().toString('hex')); // e89..........41econst {
generateKeySync,
} = require('node:crypto');
const key = generateKeySync('hmac', { length: 512 });
console.log(key.export().toString('hex')); // e89..........41e
生成的 HMAC 密钥的大小不应超过底层哈希函数的块大小。请参阅crypto.createHmac()了解更多信息。
crypto.generatePrime(size[, options[, callback]])#
生成size位的伪随机素数。
如果options.safe是true,则素数将是安全素数 - 也就是说,
(prime - 1) / 2也将是素数。
options.add和options.rem参数可用于强制执行附加要求,例如,对于 Diffie-Hellman:
- 如果
options.add和options.rem均已设置,则质数将满足prime % add = rem的条件。 - 如果仅设置了
options.add并且options.safe不是true,则素数将满足prime % add = 1条件。 - 如果仅设置了
options.add且options.safe设置为true,则质数将满足prime % add = 3条件。这是必要的,因为options.add > 2的prime % add = 1会与options.safe强制执行的条件相矛盾。 - 如果未给出
options.add,则忽略options.rem。
如果以ArrayBuffer、SharedArrayBuffer、 TypedArray 形式给出,则options.add 和options.rem 都必须编码为大端序列}、Buffer或
DataView。
默认情况下,素数在<ArrayBuffer>中被编码为八位字节的大端序列。如果bigint选项为true,则
提供<bigint> 。
crypto.generatePrimeSync(size[, options])#
size<number>要生成的素数的大小(以位为单位)。options<对象>- 返回:<ArrayBuffer> | <bigint>
生成size位的伪随机素数。
如果options.safe是true,则素数将是安全素数 - 也就是说,
(prime - 1) / 2也将是素数。
options.add和options.rem参数可用于强制执行附加要求,例如对于 Diffie-Hellman:
- 如果
options.add和options.rem均已设置,则素数将满足prime % add = rem的条件。 - 如果仅设置了
options.add并且options.safe不是true,则素数将满足prime % add = 1条件。 - 如果仅设置了
options.add且options.safe设置为true,则质数将满足prime % add = 3条件。这是必要的,因为options.add > 2的prime % add = 1会与options.safe强制执行的条件相矛盾。 - 如果未给出
options.add,则忽略options.rem。
如果以ArrayBuffer、SharedArrayBuffer、 TypedArray 形式给出,则options.add和options.rem 都必须编码为大端序列}、Buffer或
DataView。
默认情况下,素数在<ArrayBuffer>中被编码为八位字节的大端序列。如果bigint选项为true,则
提供<bigint> 。
crypto.getCipherInfo(nameOrNid[, options])#
返回有关给定密码的信息。
一些密码接受可变长度密钥和初始化向量。默认情况下,crypto.getCipherInfo()方法将返回这些密码的默认值。要测试给定密钥长度或 iv 长度对于给定密码是否可接受,请使用keyLength和ivLength选项。如果给定的值不可接受,则返回undefined 。
crypto.getCiphers()#
- 返回:<string[]>包含受支持的密码算法名称的数组。
const {
getCiphers,
} = await import('node:crypto');
console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]const {
getCiphers,
} = require('node:crypto');
console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
crypto.getCurves()#
- 返回:<string[]>包含受支持的椭圆曲线名称的数组。
const {
getCurves,
} = await import('node:crypto');
console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]const {
getCurves,
} = require('node:crypto');
console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
crypto.getDiffieHellman(groupName)#
groupName<字符串>- 返回:<DiffieHellmanGroup>
创建预定义的DiffieHellmanGroup密钥交换对象。DiffieHellmanGroup的文档中列出了受支持的组。
返回的对象模仿crypto.createDiffieHellman()创建的对象的接口
,但不允许更改键(例如,使用diffieHellman.setPublicKey() )。使用此方法的优点是各方不必预先生成或交换群模数,从而节省了处理器和通信时间。
示例(获取共享秘密):
const {
getDiffieHellman,
} = await import('node:crypto');
const alice = getDiffieHellman('modp14');
const bob = getDiffieHellman('modp14');
alice.generateKeys();
bob.generateKeys();
const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
/* aliceSecret and bobSecret should be the same */
console.log(aliceSecret === bobSecret);const {
getDiffieHellman,
} = require('node:crypto');
const alice = getDiffieHellman('modp14');
const bob = getDiffieHellman('modp14');
alice.generateKeys();
bob.generateKeys();
const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
/* aliceSecret and bobSecret should be the same */
console.log(aliceSecret === bobSecret);
crypto.getFips()#
crypto.getHashes()#
- 返回:<string[]>支持的哈希算法名称的数组,例如
'RSA-SHA256'。哈希算法也称为“摘要”算法。
const {
getHashes,
} = await import('node:crypto');
console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]const {
getHashes,
} = require('node:crypto');
console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
crypto.getRandomValues(typedArray)#
typedArray<缓冲区> | <类型化数组> | <数据视图> | <数组缓冲区>- 返回:<缓冲区> | <类型化数组> | <数据视图> | <ArrayBuffer>返回
typedArray。
crypto.webcrypto.getRandomValues()的方便别名。此实现不符合 Web Crypto 规范,要编写与 Web 兼容的代码,请改用crypto.webcrypto.getRandomValues()。
crypto.hkdf(digest, ikm, salt, info, keylen, callback)#
digest<string>要使用的摘要算法。ikm<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <KeyObject>输入密钥材料。必须提供,但长度可以为零。salt<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <DataView>盐值。必须提供,但长度可以为零。info<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <DataView>附加信息值。必须提供,但长度可以为零,且不能超过 1024 字节。keylen<number>要生成的密钥的长度。必须大于 0。最大允许值为255乘以所选摘要函数生成的字节数(例如sha512生成 64 字节哈希值,使得最大 HKDF 输出为 16320字节)。callback<函数>err<错误>derivedKey<ArrayBuffer>
HKDF 是 RFC 5869 中定义的简单密钥派生函数。给定的ikm、
salt和info与digest一起使用来派生keylen字节的密钥。
使用两个参数调用提供的callback函数: err和
derivedKey。如果在派生密钥时发生错误,则将设置err ;否则err将是null。成功生成的derivedKey将作为<ArrayBuffer>传递给回调。如果任何输入参数指定无效值或类型,将会引发错误。
import { Buffer } from 'node:buffer';
const {
hkdf,
} = await import('node:crypto');
hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
if (err) throw err;
console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
});const {
hkdf,
} = require('node:crypto');
const { Buffer } = require('node:buffer');
hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
if (err) throw err;
console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
});
crypto.hkdfSync(digest, ikm, salt, info, keylen)#
digest<string>要使用的摘要算法。ikm<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <KeyObject>输入密钥材料。必须提供,但长度可以为零。salt<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <DataView>盐值。必须提供,但长度可以为零。info<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <DataView>附加信息值。必须提供,但长度可以为零,且不能超过 1024 字节。keylen<number>要生成的密钥的长度。必须大于 0。最大允许值为255乘以所选摘要函数生成的字节数(例如sha512生成 64 字节哈希值,使得最大 HKDF 输出为 16320字节)。- 返回:<ArrayBuffer>
提供RFC 5869 中定义的同步 HKDF 密钥派生函数。给定的ikm、salt和info与digest一起使用派生一个keylen字节的密钥
。
成功生成的derivedKey将作为<ArrayBuffer>返回。
如果任何输入参数指定无效值或类型,或者无法生成派生键,则会引发错误。
import { Buffer } from 'node:buffer';
const {
hkdfSync,
} = await import('node:crypto');
const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'const {
hkdfSync,
} = require('node:crypto');
const { Buffer } = require('node:buffer');
const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)#
password<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>salt<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>iterations<数字>keylen<数字>digest<字符串>callback<函数>
提供异步基于密码的密钥派生函数 2 (PBKDF2) 实现。应用由digest指定的选定 HMAC 摘要算法,从
password、salt 派生出请求字节长度 ( keylen ) 的密钥}和iterations。
使用两个参数调用提供的callback函数: err和
derivedKey。如果在派生密钥时发生错误,则将设置err ;否则err将是null。默认情况下,成功生成的
derivedKey将作为Buffer传递给回调。如果任何输入参数指定无效值或类型,将会引发错误。
iterations参数必须是设置得尽可能高的数字。迭代次数越多,派生密钥就越安全,但需要更长的时间才能完成。
salt应尽可能唯一。建议盐是随机的且至少 16 字节长。有关详细信息,请参阅NIST SP 800-132。
传递password或salt的字符串时,请在使用字符串作为加密 API 的输入时考虑
注意事项。
const {
pbkdf2,
} = await import('node:crypto');
pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
});const {
pbkdf2,
} = require('node:crypto');
pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
});
可以使用crypto.getHashes()检索支持的摘要函数的数组
。
该 API 使用 libuv 的线程池,这可能会对某些应用程序产生令人惊讶的负面性能影响;有关更多信息,请参阅
UV_THREADPOOL_SIZE文档。
crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)#
password<字符串> | <缓冲区> | <类型化数组> | <数据视图>salt<字符串> | <缓冲区> | <类型化数组> | <数据视图>iterations<数字>keylen<数字>digest<字符串>- 返回:<缓冲区>
提供同步的基于密码的密钥派生函数 2 (PBKDF2) 实现。应用由digest指定的选定 HMAC 摘要算法,从
password、salt 派生出请求字节长度 ( keylen ) 的密钥}和iterations。
如果发生错误,将抛出Error,否则派生密钥将作为Buffer返回。
iterations参数必须是设置得尽可能高的数字。迭代次数越多,派生密钥就越安全,但需要更长的时间才能完成。
salt应尽可能唯一。建议盐是随机的且至少 16 字节长。有关详细信息,请参阅NIST SP 800-132。
传递password或salt的字符串时,请
在使用字符串作为加密 API 的输入时考虑注意事项。
const {
pbkdf2Sync,
} = await import('node:crypto');
const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
console.log(key.toString('hex')); // '3745e48...08d59ae'const {
pbkdf2Sync,
} = require('node:crypto');
const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
console.log(key.toString('hex')); // '3745e48...08d59ae'
可以使用crypto.getHashes()检索支持的摘要函数的数组
。
crypto.privateDecrypt(privateKey, buffer)#
privateKey<对象> | <字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <关键对象> | <加密密钥>oaepHash<string>用于 OAEP 填充和 MGF1 的哈希函数。 默认值:'sha1'oaepLabel<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <DataView>用于 OAEP 填充的标签。如果未指定,则不使用标签。padding<crypto.constants>在crypto.constants中定义的可选填充值 ,可能是:crypto.constants.RSA_NO_PADDING、crypto.constants.RSA_PKCS1_PADDING或crypto.constants.RSA_PKCS1_OAEP_PADDING。
buffer<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>- 返回:<Buffer>包含解密内容的新
Buffer。
使用privateKey解密buffer。buffer之前已使用相应的公钥进行加密,例如使用crypto.publicEncrypt()。
如果privateKey不是KeyObject,则此函数的行为就像
privateKey已传递给crypto.createPrivateKey()。如果是对象,则可以传递padding属性。否则,此函数使用
RSA_PKCS1_OAEP_PADDING。
crypto.privateEncrypt(privateKey, buffer)#
privateKey<对象> | <字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <关键对象> | <加密密钥>key<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <关键对象> | <CryptoKey> PEM 编码的私钥。passphrase<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <DataView>私钥的可选密码。padding<crypto.constants>在crypto.constants中定义的可选填充值 ,可能是:crypto.constants.RSA_NO_PADDING或crypto.constants.RSA_PKCS1_PADDING。encoding<string>当buffer、key或passphrase为字符串时使用的字符串编码。
buffer<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>- 返回:<Buffer>包含加密内容的新
Buffer。
使用privateKey加密buffer。返回的数据可以使用相应的公钥进行解密,例如使用crypto.publicDecrypt()。
如果privateKey不是KeyObject,则此函数的行为就像
privateKey已传递给crypto.createPrivateKey()。如果是对象,则可以传递padding属性。否则,此函数使用
RSA_PKCS1_PADDING。
crypto.publicDecrypt(key, buffer)#
key<对象> | <字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <关键对象> | <加密密钥>passphrase<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <DataView>私钥的可选密码。padding<crypto.constants>在crypto.constants中定义的可选填充值 ,可能是:crypto.constants.RSA_NO_PADDING或crypto.constants.RSA_PKCS1_PADDING。encoding<string>当buffer、key或passphrase为字符串时使用的字符串编码。
buffer<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>- 返回:<Buffer>包含解密内容的新
Buffer。
使用key解密buffer。buffer之前已使用相应的私钥加密,例如使用crypto.privateEncrypt()。
如果key不是KeyObject,则此函数的行为就像
key已传递给crypto.createPublicKey()。如果是对象,则可以传递padding属性。否则,此函数使用
RSA_PKCS1_PADDING。
由于 RSA 公钥可以从私钥派生,因此可以传递私钥而不是公钥。
crypto.publicEncrypt(key, buffer)#
key<对象> | <字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <关键对象> | <加密密钥>key<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <关键对象> | <CryptoKey> PEM 编码的公钥或私钥、<KeyObject>或<CryptoKey>。oaepHash<string>用于 OAEP 填充和 MGF1 的哈希函数。 默认值:'sha1'oaepLabel<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <DataView>用于 OAEP 填充的标签。如果未指定,则不使用标签。passphrase<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <DataView>私钥的可选密码。padding<crypto.constants>在crypto.constants中定义的可选填充值 ,可能是:crypto.constants.RSA_NO_PADDING、crypto.constants.RSA_PKCS1_PADDING或crypto.constants.RSA_PKCS1_OAEP_PADDING。encoding<string>当buffer、key、oaepLabel或passphrase为字符串时使用的字符串编码。
buffer<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>- 返回:<Buffer>包含加密内容的新
Buffer。
使用key加密buffer的内容,并返回包含加密内容的新
Buffer 。返回的数据可以使用相应的私钥进行解密,例如使用crypto.privateDecrypt()。
如果key不是KeyObject,则此函数的行为就像
key已传递给crypto.createPublicKey()。如果是对象,则可以传递padding属性。否则,此函数使用
RSA_PKCS1_OAEP_PADDING。
由于 RSA 公钥可以从私钥派生,因此可以传递私钥而不是公钥。
crypto.randomBytes(size[, callback])#
size<number>要生成的字节数。size不得大于2**31 - 1。callback<函数>- 如果未提供
callback函数,则返回:<Buffer> 。
生成加密的强伪随机数据。size参数是一个数字,指示要生成的字节数。
如果提供了callback函数,则会异步生成字节,并使用两个参数调用callback函数: err和buf。如果发生错误,err将是一个Error对象;否则是null。buf参数
是包含生成字节的Buffer 。
// Asynchronous
const {
randomBytes,
} = await import('node:crypto');
randomBytes(256, (err, buf) => {
if (err) throw err;
console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});// Asynchronous
const {
randomBytes,
} = require('node:crypto');
randomBytes(256, (err, buf) => {
if (err) throw err;
console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});
如果未提供callback函数,则会同步生成随机字节并以Buffer形式返回。如果生成字节时出现问题,将会抛出错误。
// Synchronous
const {
randomBytes,
} = await import('node:crypto');
const buf = randomBytes(256);
console.log(
`${buf.length} bytes of random data: ${buf.toString('hex')}`);// Synchronous
const {
randomBytes,
} = require('node:crypto');
const buf = randomBytes(256);
console.log(
`${buf.length} bytes of random data: ${buf.toString('hex')}`);
在有足够的可用熵之前,crypto.randomBytes()方法将不会完成。这通常不会超过几毫秒。生成随机字节可能会阻塞较长时间的唯一时间是在启动后,此时整个系统的熵仍然很低。
该 API 使用 libuv 的线程池,这可能会对某些应用程序产生令人惊讶的负面性能影响;有关更多信息,请参阅
UV_THREADPOOL_SIZE文档。
crypto.randomBytes()的异步版本是在单个线程池请求中执行的。为了最大限度地减少线程池任务长度变化,请在满足客户端请求时对大型randomBytes请求进行分区。
crypto.randomFillSync(buffer[, offset][, size])#
buffer<ArrayBuffer> | <缓冲区> | <类型化数组> | <DataView>必须提供。提供的buffer的大小不得大于2**31 - 1。offset<数字> 默认值:0size<数字> 默认值:buffer.length - offset。size不得大于2**31 - 1。- 返回:<ArrayBuffer> | <缓冲区> | <类型化数组> | <DataView>作为
buffer参数传递的对象 。
crypto.randomFill()的同步版本。
import { Buffer } from 'node:buffer';
const { randomFillSync } = await import('node:crypto');
const buf = Buffer.alloc(10);
console.log(randomFillSync(buf).toString('hex'));
randomFillSync(buf, 5);
console.log(buf.toString('hex'));
// The above is equivalent to the following:
randomFillSync(buf, 5, 5);
console.log(buf.toString('hex'));const { randomFillSync } = require('node:crypto');
const { Buffer } = require('node:buffer');
const buf = Buffer.alloc(10);
console.log(randomFillSync(buf).toString('hex'));
randomFillSync(buf, 5);
console.log(buf.toString('hex'));
// The above is equivalent to the following:
randomFillSync(buf, 5, 5);
console.log(buf.toString('hex'));
任何ArrayBuffer、TypedArray或DataView实例都可以作为
buffer传递。
import { Buffer } from 'node:buffer';
const { randomFillSync } = await import('node:crypto');
const a = new Uint32Array(10);
console.log(Buffer.from(randomFillSync(a).buffer,
a.byteOffset, a.byteLength).toString('hex'));
const b = new DataView(new ArrayBuffer(10));
console.log(Buffer.from(randomFillSync(b).buffer,
b.byteOffset, b.byteLength).toString('hex'));
const c = new ArrayBuffer(10);
console.log(Buffer.from(randomFillSync(c)).toString('hex'));const { randomFillSync } = require('node:crypto');
const { Buffer } = require('node:buffer');
const a = new Uint32Array(10);
console.log(Buffer.from(randomFillSync(a).buffer,
a.byteOffset, a.byteLength).toString('hex'));
const b = new DataView(new ArrayBuffer(10));
console.log(Buffer.from(randomFillSync(b).buffer,
b.byteOffset, b.byteLength).toString('hex'));
const c = new ArrayBuffer(10);
console.log(Buffer.from(randomFillSync(c)).toString('hex'));
crypto.randomFill(buffer[, offset][, size], callback)#
buffer<ArrayBuffer> | <缓冲区> | <类型化数组> | <DataView>必须提供。提供的buffer的大小不得大于2**31 - 1。offset<数字> 默认值:0size<数字> 默认值:buffer.length - offset。size不得大于2**31 - 1。callback<函数>function(err, buf) {}.
此函数与crypto.randomBytes()类似,但要求第一个参数是要填充的Buffer 。它还需要传入一个回调。
如果未提供callback函数,则会抛出错误。
import { Buffer } from 'node:buffer';
const { randomFill } = await import('node:crypto');
const buf = Buffer.alloc(10);
randomFill(buf, (err, buf) => {
if (err) throw err;
console.log(buf.toString('hex'));
});
randomFill(buf, 5, (err, buf) => {
if (err) throw err;
console.log(buf.toString('hex'));
});
// The above is equivalent to the following:
randomFill(buf, 5, 5, (err, buf) => {
if (err) throw err;
console.log(buf.toString('hex'));
});const { randomFill } = require('node:crypto');
const { Buffer } = require('node:buffer');
const buf = Buffer.alloc(10);
randomFill(buf, (err, buf) => {
if (err) throw err;
console.log(buf.toString('hex'));
});
randomFill(buf, 5, (err, buf) => {
if (err) throw err;
console.log(buf.toString('hex'));
});
// The above is equivalent to the following:
randomFill(buf, 5, 5, (err, buf) => {
if (err) throw err;
console.log(buf.toString('hex'));
});
任何ArrayBuffer、TypedArray或DataView实例都可以作为
buffer传递。
虽然这包括Float32Array和Float64Array的实例,但此函数不应用于生成随机浮点数。结果可能包含+Infinity、-Infinity和NaN,即使数组仅包含有限数字,它们也不是从均匀随机分布中抽取的,并且具有没有有意义的下限或上限。
import { Buffer } from 'node:buffer';
const { randomFill } = await import('node:crypto');
const a = new Uint32Array(10);
randomFill(a, (err, buf) => {
if (err) throw err;
console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
.toString('hex'));
});
const b = new DataView(new ArrayBuffer(10));
randomFill(b, (err, buf) => {
if (err) throw err;
console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
.toString('hex'));
});
const c = new ArrayBuffer(10);
randomFill(c, (err, buf) => {
if (err) throw err;
console.log(Buffer.from(buf).toString('hex'));
});const { randomFill } = require('node:crypto');
const { Buffer } = require('node:buffer');
const a = new Uint32Array(10);
randomFill(a, (err, buf) => {
if (err) throw err;
console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
.toString('hex'));
});
const b = new DataView(new ArrayBuffer(10));
randomFill(b, (err, buf) => {
if (err) throw err;
console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
.toString('hex'));
});
const c = new ArrayBuffer(10);
randomFill(c, (err, buf) => {
if (err) throw err;
console.log(Buffer.from(buf).toString('hex'));
});
该 API 使用 libuv 的线程池,这可能会对某些应用程序产生令人惊讶的负面性能影响;有关更多信息,请参阅
UV_THREADPOOL_SIZE文档。
crypto.randomFill()的异步版本在单个线程池请求中执行。为了最大限度地减少线程池任务长度变化,请在满足客户端请求时对大型randomFill请求进行分区。
crypto.randomInt([min, ]max[, callback])#
返回一个随机整数n使得min <= n < max。该实现避免了模偏差。
范围 ( max - min ) 必须小于 2 48。min和max必须是安全整数。
如果不提供callback函数,则同步生成随机整数。
// Asynchronous
const {
randomInt,
} = await import('node:crypto');
randomInt(3, (err, n) => {
if (err) throw err;
console.log(`Random number chosen from (0, 1, 2): ${n}`);
});// Asynchronous
const {
randomInt,
} = require('node:crypto');
randomInt(3, (err, n) => {
if (err) throw err;
console.log(`Random number chosen from (0, 1, 2): ${n}`);
});
// Synchronous
const {
randomInt,
} = await import('node:crypto');
const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);// Synchronous
const {
randomInt,
} = require('node:crypto');
const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);
// With `min` argument
const {
randomInt,
} = await import('node:crypto');
const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);// With `min` argument
const {
randomInt,
} = require('node:crypto');
const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);
crypto.randomUUID([options])#
options<对象>disableEntropyCache<boolean>默认情况下,为了提高性能,Node.js 会生成并缓存足够的随机数据,以生成最多 128 个随机 UUID。要在不使用缓存的情况下生成 UUID,请将disableEntropyCache设置为true。 默认值:false。
- 返回:<字符串>
生成随机RFC 4122版本 4 UUID。UUID 是使用加密伪随机数生成器生成的。
crypto.scrypt(password, salt, keylen[, options], callback)#
password<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>salt<字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图>keylen<数字>options<对象>callback<函数>
提供异步scrypt实现。Scrypt 是一种基于密码的密钥派生函数,其设计在计算和内存方面都非常昂贵,以便使暴力攻击变得无益。
salt应尽可能唯一。建议盐是随机的且至少 16 字节长。有关详细信息,请参阅NIST SP 800-132。
传递password或salt的字符串时,请考虑
使用字符串作为加密 API 的输入时的注意事项。
使用两个参数调用callback函数: err和derivedKey。
当密钥派生失败时, err是一个异常对象,否则err是
null。derivedKey作为Buffer传递给回调。
当任何输入参数指定无效值或类型时,将引发异常。
const {
scrypt,
} = await import('node:crypto');
// Using the factory defaults.
scrypt('password', 'salt', 64, (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
});
// Using a custom N parameter. Must be a power of two.
scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'
});const {
scrypt,
} = require('node:crypto');
// Using the factory defaults.
scrypt('password', 'salt', 64, (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
});
// Using a custom N parameter. Must be a power of two.
scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
if (err) throw err;
console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'
});
crypto.scryptSync(password, salt, keylen[, options])#
password<字符串> | <缓冲区> | <类型化数组> | <数据视图>salt<字符串> | <缓冲区> | <类型化数组> | <数据视图>keylen<数字>options<对象>- 返回:<缓冲区>
提供同步scrypt实现。Scrypt 是一种基于密码的密钥派生函数,其设计在计算和内存方面都非常昂贵,以便使暴力攻击变得无益。
salt应尽可能唯一。建议盐是随机的且至少 16 字节长。有关详细信息,请参阅NIST SP 800-132。
传递password或salt的字符串时,请考虑
使用字符串作为加密 API 的输入时的注意事项。
当密钥派生失败时会引发异常,否则派生密钥将作为Buffer返回。
当任何输入参数指定无效值或类型时,将引发异常。
const {
scryptSync,
} = await import('node:crypto');
// Using the factory defaults.
const key1 = scryptSync('password', 'salt', 64);
console.log(key1.toString('hex')); // '3745e48...08d59ae'
// Using a custom N parameter. Must be a power of two.
const key2 = scryptSync('password', 'salt', 64, { N: 1024 });
console.log(key2.toString('hex')); // '3745e48...aa39b34'const {
scryptSync,
} = require('node:crypto');
// Using the factory defaults.
const key1 = scryptSync('password', 'salt', 64);
console.log(key1.toString('hex')); // '3745e48...08d59ae'
// Using a custom N parameter. Must be a power of two.
const key2 = scryptSync('password', 'salt', 64, { N: 1024 });
console.log(key2.toString('hex')); // '3745e48...aa39b34'
crypto.secureHeapUsed()#
- 返回:<对象>
total<number>使用--secure-heap=n命令行标志指定的分配的总安全堆大小。min<number>使用--secure-heap-min命令行标志指定的安全堆的最小分配量。used<number>当前从安全堆分配的字节总数。utilization<number>计算出的used与total分配字节的比率。
crypto.setEngine(engine[, flags])#
engine<字符串>flags<crypto.constants> 默认值:crypto.constants.ENGINE_METHOD_ALL
为部分或所有 OpenSSL 函数(通过标志选择)加载并设置engine 。
engine可以是引擎共享库的 ID 或路径。
可选的flags参数默认使用ENGINE_METHOD_ALL 。flags是一个位字段
,采用以下标志之一或组合(在
crypto.constants中定义):
crypto.constants.ENGINE_METHOD_RSAcrypto.constants.ENGINE_METHOD_DSAcrypto.constants.ENGINE_METHOD_DHcrypto.constants.ENGINE_METHOD_RANDcrypto.constants.ENGINE_METHOD_ECcrypto.constants.ENGINE_METHOD_CIPHERScrypto.constants.ENGINE_METHOD_DIGESTScrypto.constants.ENGINE_METHOD_PKEY_METHScrypto.constants.ENGINE_METHOD_PKEY_ASN1_METHScrypto.constants.ENGINE_METHOD_ALLcrypto.constants.ENGINE_METHOD_NONE
crypto.setFips(bool)#
bool<boolean>true启用 FIPS 模式。
在启用 FIPS 的 Node.js 构建中启用符合 FIPS 的加密提供程序。如果 FIPS 模式不可用,则会引发错误。
crypto.sign(algorithm, data, key[, callback])#
algorithm<字符串> | <空> | <未定义>data<ArrayBuffer> | <缓冲区> | <类型化数组> | <数据视图>key<对象> | <字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <关键对象> | <加密密钥>callback<函数>- 如果未提供
callback函数,则返回:<Buffer> 。
使用给定的私钥和算法计算并返回data的签名。如果algorithm是null或undefined,则算法取决于密钥类型(尤其是 Ed25519 和 Ed448)。
如果key不是KeyObject,则此函数的行为就像key已传递给crypto.createPrivateKey()。如果它是一个对象,可以传递以下附加属性:
-
dsaEncoding<string>对于 DSA 和 ECDSA,此选项指定生成的签名的格式。它可以是以下之一:'der'(默认):DER 编码的 ASN.1 签名结构编码(r, s)。'ieee-p1363': IEEE-P1363 中建议的签名格式r || s。
-
padding<integer> RSA 的可选填充值,以下之一:crypto.constants.RSA_PKCS1_PADDING(默认)crypto.constants.RSA_PKCS1_PSS_PADDING
RSA_PKCS1_PSS_PADDING将使用 MGF1 以及用于对消息进行签名的相同哈希函数(如RFC 4055的第 3.1 节中指定) 。 -
saltLength<integer>当填充为RSA_PKCS1_PSS_PADDING时的盐长度。特殊值crypto.constants.RSA_PSS_SALTLEN_DIGEST将盐长度设置为摘要大小,crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN(默认)将其设置为最大允许值。
如果提供了callback函数,则该函数使用 libuv 的线程池。
crypto.subtle#
- 类型:<微妙加密>
crypto.webcrypto.subtle的方便别名。
crypto.timingSafeEqual(a, b)#
a<ArrayBuffer> | <缓冲区> | <类型化数组> | <数据视图>b<ArrayBuffer> | <缓冲区> | <类型化数组> | <数据视图>- 返回:<布尔值>
此函数使用恒定时间算法比较表示给定
ArrayBuffer、TypedArray或DataView实例的基础字节。
此函数不会泄漏允许攻击者猜测其中一个值的计时信息。这适用于比较 HMAC 摘要或秘密值,例如身份验证 cookie 或 功能 url。
a和b必须都是Buffer s、TypedArray s 或DataView s,并且它们必须具有相同的字节长度。如果a和b具有不同的字节长度,则会引发错误。
如果a和b中至少有一个是每个条目超过一个字节的TypedArray ,例如Uint16Array,则结果将为使用平台字节顺序计算。
当两个输入都是Float32Array或
Float64Array时,由于浮点数的 IEEE 754 编码,此函数可能会返回意外结果。特别是,x === y和
Object.is(x, y)都不意味着两个浮点数x和y的字节表示形式相等。
使用crypto.timingSafeEqual并不能保证周围的代码是计时安全的。应注意确保周围的代码不会引入计时漏洞。
crypto.verify(algorithm, data, key, signature[, callback])#
algorithm<字符串> | <空> | <未定义>data<ArrayBuffer> | <缓冲区> | <类型化数组> | <数据视图>key<对象> | <字符串> | <数组缓冲区> | <缓冲区> | <类型化数组> | <数据视图> | <关键对象> | <加密密钥>signature<ArrayBuffer> | <缓冲区> | <类型化数组> | <数据视图>callback<函数>- 返回:<boolean>
true或false,具体取决于数据和公钥签名的有效性(如果未提供callback函数)。
使用给定的密钥和算法验证data的给定签名。如果
algorithm是null或undefined,则算法取决于密钥类型(尤其是 Ed25519 和 Ed448)。
如果key不是KeyObject,则此函数的行为就像key已传递给crypto.createPublicKey()。如果它是一个对象,可以传递以下附加属性:
-
dsaEncoding<string>对于 DSA 和 ECDSA,此选项指定签名的格式。它可以是以下之一:'der'(默认):DER 编码的 ASN.1 签名结构编码(r, s)。'ieee-p1363': IEEE-P1363 中建议的签名格式r || s。
-
padding<integer> RSA 的可选填充值,以下之一:crypto.constants.RSA_PKCS1_PADDING(默认)crypto.constants.RSA_PKCS1_PSS_PADDING
RSA_PKCS1_PSS_PADDING将使用 MGF1 以及用于对消息进行签名的相同哈希函数(如RFC 4055的第 3.1 节中指定) 。 -
saltLength<integer>当填充为RSA_PKCS1_PSS_PADDING时的盐长度。特殊值crypto.constants.RSA_PSS_SALTLEN_DIGEST将盐长度设置为摘要大小,crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN(默认)将其设置为最大允许值。
signature参数是先前计算的data签名。
由于公钥可以从私钥派生,因此可以为key传递私钥或公钥。
如果提供了callback函数,则该函数使用 libuv 的线程池。
crypto.webcrypto#
类型:<Crypto> Web Crypto API 标准的实现。
有关详细信息,请参阅Web Crypto API 文档。
注意#
使用字符串作为加密 API 的输入#
由于历史原因,Node.js 提供的许多加密 API 接受字符串作为输入,其中底层加密算法对字节序列起作用。这些实例包括明文、密文、对称密钥、初始化向量、密码、盐、身份验证标签和其他经过身份验证的数据。
将字符串传递给加密 API 时,请考虑以下因素。
-
并非所有字节序列都是有效的 UTF-8 字符串。因此,当从字符串导出长度为
n的字节序列时,其熵通常低于随机或伪随机n字节序列的熵。例如,任何 UTF-8 字符串都不会产生字节序列c0 af。密钥几乎应该完全是随机或伪随机字节序列。 -
同样,当将随机或伪随机字节序列转换为 UTF-8 字符串时,不表示有效代码点的子序列可能会被 Unicode 替换字符 (
U+FFFD)替换。因此,生成的 Unicode 字符串的字节表示形式可能不等于创建该字符串的字节序列。const original = [0xc0, 0xaf]; const bytesAsString = Buffer.from(original).toString('utf8'); const stringAsBytes = Buffer.from(bytesAsString, 'utf8'); console.log(stringAsBytes); // Prints '<Buffer ef bf bd ef bf bd>'.密码、哈希函数、签名算法和密钥派生函数的输出是伪随机字节序列,不应用作 Unicode 字符串。
-
当从用户输入获取字符串时,某些 Unicode 字符可以用多种等效方式表示,从而产生不同的字节序列。例如,当将用户密码传递给密钥派生函数(例如 PBKDF2 或 scrypt)时,密钥派生函数的结果取决于字符串是使用组合字符还是分解字符。Node.js 不会标准化字符表示。开发人员应考虑 在将用户输入传递给加密 API 之前对用户输入使用
String.prototype.normalize()。
旧版流 API(Node.js 0.10 之前的版本)#
Crypto 模块是在统一 Stream API 的概念出现之前以及用于处理二进制数据的Buffer对象之前添加到 Node.js 中的。因此,许多crypto类具有在实现Streams API的其他 Node.js 类中通常找不到的方法
(例如update()、final()或digest() 此外,许多方法默认接受并返回'latin1'编码的字符串,而不是Buffer。在 Node.js v0.8 之后,此默认值已更改为默认使用Buffer对象。
支持弱或受损的算法#
node:crypto模块仍然支持一些已经受到损害的算法,目前不建议使用。该 API 还允许使用密钥大小较小的密码和散列,这些密码和散列对于安全使用来说太弱了。
用户应根据自己的安全要求承担选择加密算法和密钥大小的全部责任。
根据NIST SP 800-131A的建议:
- 在需要抗冲突性(例如数字签名)的情况下,MD5 和 SHA-1 不再被接受。
- RSA、DSA和DH算法使用的密钥建议至少有2048位,ECDSA和ECDH曲线的密钥至少有224位,这样可以安全使用几年。
modp1、modp2和modp5的 DH 组的密钥大小小于 2048 位,不推荐使用。
有关其他建议和详细信息,请参阅参考资料。
一些具有已知弱点且在实践中意义不大的算法只能通过遗留提供商获得,默认情况下未启用该提供商。
CCM模式#
CCM 是支持的AEAD 算法之一。使用此模式的应用程序在使用密码 API 时必须遵守某些限制:
- 身份验证标记长度必须在密码创建期间通过设置
authTagLength选项来指定,并且必须是 4、6、8、10、12、14 或 16 字节之一。 - 初始化向量(随机数)
N的长度必须介于 7 到 13 个字节 (7 ≤ N ≤ 13) 之间。 - 明文的长度限制为
2 ** (8 * (15 - N))字节。 - 解密时,必须在调用
update()之前通过setAuthTag()设置身份验证标记。否则,解密将失败,并且final()将抛出符合RFC 3610第 2.6 节的错误。 - 在 CCM 模式下使用
write(data)、end(data)或pipe()等流方法可能会失败,因为 CCM 无法为每个实例处理多个数据块。 - 传递其他经过身份验证的数据 (AAD) 时,必须通过
plaintextLength选项将实际消息的长度(以字节为单位)传递到setAAD()。许多加密库在密文中包含身份验证标签,这意味着它们会生成长度为plaintextLength + authTagLength的密文。Node.js 不包含身份验证标签,因此密文长度始终为plaintextLength。如果不使用 AAD,则不需要这样做。 - 由于 CCM 会立即处理整个消息,因此必须仅调用一次
update()。 - 尽管调用
update()足以加密/解密消息,但应用程序必须调用final()来计算或验证身份验证标记。
import { Buffer } from 'node:buffer';
const {
createCipheriv,
createDecipheriv,
randomBytes,
} = await import('node:crypto');
const key = 'keykeykeykeykeykeykeykey';
const nonce = randomBytes(12);
const aad = Buffer.from('0123456789', 'hex');
const cipher = createCipheriv('aes-192-ccm', key, nonce, {
authTagLength: 16,
});
const plaintext = 'Hello world';
cipher.setAAD(aad, {
plaintextLength: Buffer.byteLength(plaintext),
});
const ciphertext = cipher.update(plaintext, 'utf8');
cipher.final();
const tag = cipher.getAuthTag();
// Now transmit { ciphertext, nonce, tag }.
const decipher = createDecipheriv('aes-192-ccm', key, nonce, {
authTagLength: 16,
});
decipher.setAuthTag(tag);
decipher.setAAD(aad, {
plaintextLength: ciphertext.length,
});
const receivedPlaintext = decipher.update(ciphertext, null, 'utf8');
try {
decipher.final();
} catch (err) {
throw new Error('Authentication failed!', { cause: err });
}
console.log(receivedPlaintext);const { Buffer } = require('node:buffer');
const {
createCipheriv,
createDecipheriv,
randomBytes,
} = require('node:crypto');
const key = 'keykeykeykeykeykeykeykey';
const nonce = randomBytes(12);
const aad = Buffer.from('0123456789', 'hex');
const cipher = createCipheriv('aes-192-ccm', key, nonce, {
authTagLength: 16,
});
const plaintext = 'Hello world';
cipher.setAAD(aad, {
plaintextLength: Buffer.byteLength(plaintext),
});
const ciphertext = cipher.update(plaintext, 'utf8');
cipher.final();
const tag = cipher.getAuthTag();
// Now transmit { ciphertext, nonce, tag }.
const decipher = createDecipheriv('aes-192-ccm', key, nonce, {
authTagLength: 16,
});
decipher.setAuthTag(tag);
decipher.setAAD(aad, {
plaintextLength: ciphertext.length,
});
const receivedPlaintext = decipher.update(ciphertext, null, 'utf8');
try {
decipher.final();
} catch (err) {
throw new Error('Authentication failed!', { cause: err });
}
console.log(receivedPlaintext);
FIPS模式#
使用 OpenSSL 3 时,Node.js 在与适当的 OpenSSL 3 提供程序(例如OpenSSL 3 中的 FIPS 提供程序)一起使用时支持 FIPS 140-2 ,可以按照OpenSSL 的 FIPS README 文件中的说明进行安装。
要在 Node.js 中支持 FIPS,您将需要:
- 正确安装的 OpenSSL 3 FIPS 提供程序。
- OpenSSL 3 FIPS 模块配置文件。
- 引用 FIPS 模块配置文件的 OpenSSL 3 配置文件。
Node.js 需要使用指向 FIPS 提供商的 OpenSSL 配置文件进行配置。示例配置文件如下所示:
nodejs_conf = nodejs_init
.include /<absolute path>/fipsmodule.cnf
[nodejs_init]
providers = provider_sect
[provider_sect]
default = default_sect
# The fips section name should match the section name inside the
# included fipsmodule.cnf.
fips = fips_sect
[default_sect]
activate = 1
其中fipsmodule.cnf是 FIPS 提供程序安装步骤生成的 FIPS 模块配置文件:
openssl fipsinstall
将OPENSSL_CONF环境变量设置为指向您的配置文件,并将OPENSSL_MODULES设置为 FIPS 提供程序动态库的位置。例如
export OPENSSL_CONF=/<path to configuration file>/nodejs.cnf
export OPENSSL_MODULES=/<path to openssl lib>/ossl-modules
然后可以通过以下方式在 Node.js 中启用 FIPS 模式:
- 使用
--enable-fips或--force-fips命令行标志启动 Node.js。 - 以编程方式调用
crypto.setFips(true)。
(可选)可以通过 OpenSSL 配置文件在 Node.js 中启用 FIPS 模式。例如
nodejs_conf = nodejs_init
.include /<absolute path>/fipsmodule.cnf
[nodejs_init]
providers = provider_sect
alg_section = algorithm_sect
[provider_sect]
default = default_sect
# The fips section name should match the section name inside the
# included fipsmodule.cnf.
fips = fips_sect
[default_sect]
activate = 1
[algorithm_sect]
default_properties = fips=yes
加密常量#
由crypto.constants导出的以下常量适用于node:crypto、node:tls和node:https模块的各种使用,并且通常特定于 OpenSSL。
OpenSSL 选项#
有关详细信息,请参阅SSL OP 标志列表。
| 持续的 | 描述 |
|---|---|
SSL_OP_ALL |
在 OpenSSL 中应用多个错误解决方法。有关详细信息,请参阅 https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html 。 |
SSL_OP_ALLOW_NO_DHE_KEX |
指示 OpenSSL 允许 TLS v1.3 使用基于非 [EC]DHE 的密钥交换模式 |
SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION |
允许 OpenSSL 与未打补丁的客户端或服务器之间进行传统的不安全重新协商。请参阅 https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html。 |
SSL_OP_CIPHER_SERVER_PREFERENCE |
选择密码时尝试使用服务器的首选项而不是客户端的首选项。行为取决于协议版本。请参阅 https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html。 |
SSL_OP_CISCO_ANYCONNECT |
指示 OpenSSL 使用 Cisco 的“speshul”版本的 DTLS_BAD_VER。 |
SSL_OP_COOKIE_EXCHANGE |
指示 OpenSSL 打开 cookie 交换。 |
SSL_OP_CRYPTOPRO_TLSEXT_BUG |
指示 OpenSSL 从 cryptopro 草案的早期版本添加 server-hello 扩展。 |
SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS |
指示 OpenSSL 禁用 OpenSSL 0.9.6d 中添加的 SSL 3.0/TLS 1.0 漏洞解决方法。 |
SSL_OP_LEGACY_SERVER_CONNECT |
允许初始连接到不支持 RI 的服务器。 |
SSL_OP_NO_COMPRESSION |
指示 OpenSSL 禁用对 SSL/TLS 压缩的支持。 |
SSL_OP_NO_ENCRYPT_THEN_MAC |
指示 OpenSSL 禁用先加密后 MAC。 |
SSL_OP_NO_QUERY_MTU |
|
SSL_OP_NO_RENEGOTIATION |
指示 OpenSSL 禁用重新协商。 |
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION |
指示 OpenSSL 在执行重新协商时始终启动新会话。 |
SSL_OP_NO_SSLv2 |
指示 OpenSSL 关闭 SSL v2 |
SSL_OP_NO_SSLv3 |
指示 OpenSSL 关闭 SSL v3 |
SSL_OP_NO_TICKET |
指示 OpenSSL 禁用 RFC4507bis 票证的使用。 |
SSL_OP_NO_TLSv1 |
指示 OpenSSL 关闭 TLS v1 |
SSL_OP_NO_TLSv1_1 |
指示 OpenSSL 关闭 TLS v1.1 |
SSL_OP_NO_TLSv1_2 |
指示 OpenSSL 关闭 TLS v1.2 |
SSL_OP_NO_TLSv1_3 |
指示 OpenSSL 关闭 TLS v1.3 |
SSL_OP_PRIORITIZE_CHACHA |
当客户端这样做时,指示 OpenSSL 服务器优先考虑 ChaCha20-Poly1305。
如果未启用SSL_OP_CIPHER_SERVER_PREFERENCE,则此选项无效
。 |
SSL_OP_TLS_ROLLBACK_BUG |
指示 OpenSSL 禁用版本回滚攻击检测。 |
OpenSSL 引擎常量#
| 持续的 | 描述 |
|---|---|
ENGINE_METHOD_RSA |
限制 RSA 引擎的使用 |
ENGINE_METHOD_DSA |
将引擎的使用限制为 DSA |
ENGINE_METHOD_DH |
将引擎的使用限制为 DH |
ENGINE_METHOD_RAND |
将引擎的使用限制为 RAND |
ENGINE_METHOD_EC |
将引擎的使用限制为 EC |
ENGINE_METHOD_CIPHERS |
将引擎的使用限制为 CIPHERS |
ENGINE_METHOD_DIGESTS |
将引擎的使用限制为 DIGESTS |
ENGINE_METHOD_PKEY_METHS |
将引擎使用限制为 PKEY_METHDS |
ENGINE_METHOD_PKEY_ASN1_METHS |
将引擎使用限制为 PKEY_ASN1_METHS |
ENGINE_METHOD_ALL |
|
ENGINE_METHOD_NONE |
其他 OpenSSL 常量#
| 持续的 | 描述 |
|---|---|
DH_CHECK_P_NOT_SAFE_PRIME |
|
DH_CHECK_P_NOT_PRIME |
|
DH_UNABLE_TO_CHECK_GENERATOR |
|
DH_NOT_SUITABLE_GENERATOR |
|
ALPN_ENABLED |
|
RSA_PKCS1_PADDING |
|
RSA_SSLV23_PADDING |
|
RSA_NO_PADDING |
|
RSA_PKCS1_OAEP_PADDING |
|
RSA_X931_PADDING |
|
RSA_PKCS1_PSS_PADDING |
|
RSA_PSS_SALTLEN_DIGEST |
签名或验证时将RSA_PKCS1_PSS_PADDING的盐长度设置为摘要大小。 |
RSA_PSS_SALTLEN_MAX_SIGN |
对数据进行签名时,将RSA_PKCS1_PSS_PADDING的盐长度设置为允许的最大值。 |
RSA_PSS_SALTLEN_AUTO |
导致验证签名时自动确定RSA_PKCS1_PSS_PADDING的盐长度。 |
POINT_CONVERSION_COMPRESSED |
|
POINT_CONVERSION_UNCOMPRESSED |
|
POINT_CONVERSION_HYBRID |
Node.js 加密常量#
| 持续的 | 描述 |
|---|---|
defaultCoreCipherList |
指定 Node.js 使用的内置默认密码列表。 |
defaultCipherList |
指定当前 Node.js 进程使用的事件默认密码列表。 |