关于Node.js v12.16.2中的Crypto模块
在Node.js版本v12.16.2中,crypto
模块提供了加密功能的实现接口。该模块基于OpenSSL库构建,支持多种哈希算法、HMACs、Cipher/Decipher、Signatures以及Diffie-Hellman密钥交换等功能。
为了获取有关Node.js crypto
模块的具体文档或使用指南,可以访问官方Node.js文档页面并查阅对应版本的内容。通常情况下,在特定版本下,可以通过指定URL参数来查看历史版本的手册。例如,对于v12.x系列,可以直接导航至以下链接:
https://nodejs.org/dist/latest-v12.x/docs/api/crypto.html
此页面包含了详细的API说明和示例代码片段,帮助开发者了解如何利用crypto
模块完成各种加密操作。
以下是几个常见的用法实例展示:
创建一个简单的SHA256散列函数
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.update('Hello world!');
console.log(hash.digest('hex'));
上述脚本会输出字符串“Hello world!”经过SHA-256处理后的十六进制表示形式。
使用AES加密解密数据流
// 加密部分
const crypto = require('crypto');
let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from('key'), Buffer.from('iv'));
let encrypted = cipher.update('plaintext data', 'utf8', 'hex') + cipher.final('hex');
console.log(`Encrypted text: ${
encrypted}`);
// 解密部分
let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from('key'), Buffer.from('iv'));
let decrypted = decipher.update(encrypted, 'hex', 'utf8') + decipher.final('utf8');
console.log(`Decrypted text: ${
decrypted}`);
以上程序展示了怎样通过高级加密标准(AES)方法保护敏感信息,并能够安全恢复原始消息内容。
另外需要注意的是,默认TLS密码列表可以在启动时重新定义以便满足特殊需求;而当涉及到网络请求的安全验证环节,则可能需要用到HTTPS客户端选项配置。
Node.js v12.16.2 Documentation Crypto
Node.js v12.16.2 Documentation
Index View on single page View as JSON View another version ▼
Edit on GitHub
Table of Contents
Crypto
Determining if crypto support is unavailable
Class: Certificate
Certificate.exportChallenge(spkac)
Certificate.exportPublicKey(spkac[, encoding])
Certificate.verifySpkac(spkac)
Legacy API
new crypto.Certificate()
certificate.exportChallenge(spkac)
certificate.exportPublicKey(spkac)
certificate.verifySpkac(spkac)
Class: Cipher
cipher.final([outputEncoding])
cipher.setAAD(buffer[, options])
cipher.getAuthTag()
cipher.setAutoPadding([autoPadding])
cipher.update(data[, inputEncoding][, outputEncoding])
Class: Decipher
decipher.final([outputEncoding])
decipher.setAAD(buffer[, options])
decipher.setAuthTag(buffer)
decipher.setAutoPadding([autoPadding])
decipher.update(data[, inputEncoding][, outputEncoding])
Class: DiffieHellman
diffieHellman.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
Class: DiffieHellmanGroup
Class: ECDH
Class Method: 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])
Class: Hash
hash.copy([options])
hash.digest([encoding])
hash.update(data[, inputEncoding])
Class: Hmac
hmac.digest([encoding])
hmac.update(data[, inputEncoding])
Class: KeyObject
keyObject.asymmetricKeyType
keyObject.export([options])
keyObject.symmetricKeySize
keyObject.type
Class: Sign
sign.sign(privateKey[, outputEncoding])
sign.update(data[, inputEncoding])
Class: Verify
verify.update(data[, inputEncoding])
verify.verify(object, signature[, signatureEncoding])
crypto module methods and properties
crypto.constants
crypto.DEFAULT_ENCODING
crypto.fips
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)
crypto.createSign(algorithm[, options])
crypto.createVerify(algorithm[, options])
crypto.generateKeyPair(type, options, callback)
crypto.generateKeyPairSync(type, options)
crypto.getCiphers()
crypto.getCurves()
crypto.getDiffieHellman(groupName)
crypto.getFips()
crypto.getHashes()
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.scrypt(password, salt, keylen[, options], callback)
crypto.scryptSync(password, salt, keylen[, options])
crypto.setEngine(engine[, flags])
crypto.setFips(bool)
crypto.sign(algorithm, data, key)
crypto.timingSafeEqual(a, b)
crypto.verify(algorithm, data, key, signature)
Notes
Legacy Streams API (pre Node.js v0.10)
Recent ECDH Changes
Support for weak or compromised algorithms
CCM mode
Crypto Constants
OpenSSL Options
OpenSSL Engine Constants
Other OpenSSL Constants
Node.js Crypto Constants
Crypto
Stability: 2 - Stable
The crypto module provides cryptographic functionality that includes a set of wrappers for OpenSSL’s hash, HMAC, cipher, decipher, sign, and verify functions.
Use require(‘crypto’) to access this module.
const crypto = require(‘crypto’);
const secret = ‘abcdefg’;
const hash = crypto.createHmac(‘sha256’, secret)
.update(‘I love cupcakes’)
.digest(‘hex’);
console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
Determining if crypto support is unavailable
It is possible for Node.js to be built without including support for the crypto module. In such cases, calling require(‘crypto’) will result in an error being thrown.
let crypto;
try {
crypto = require(‘crypto’);
} catch (err) {
console.log(‘crypto support is disabled!’);
}
Class: Certificate
Added in: v0.11.8
SPKAC is a Certificate Signing Request mechanism originally implemented by Netscape and was specified formally as part of HTML5’s keygen element.
is deprecated since HTML 5.2 and new projects should not use this element anymore.
The crypto module provides the Certificate class for working with SPKAC data. The most common usage is handling output generated by the HTML5 element. Node.js uses OpenSSL’s SPKAC implementation internally.
Certificate.exportChallenge(spkac)
Added in: v9.0.0
spkac <string> | <Buffer> | <TypedArray> | <DataView>
Returns: <Buffer> The challenge component of the spkac data structure, which includes a public key and a challenge.
const { Certificate } = require(‘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])
Added in: v9.0.0
spkac <string> | <Buffer> | <TypedArray> | <DataView>
encoding <string> The encoding of the spkac string.
Returns: <Buffer> The public key component of the spkac data structure, which includes a public key and a challenge.
const { Certificate } = require(‘crypto’);
const spkac = getSpkacSomehow();
const publicKey = Certificate.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as <Buffer …>
Certificate.verifySpkac(spkac)
Added in: v9.0.0
spkac <Buffer> | <TypedArray> | <DataView>
Returns: <boolean> true if the given spkac data structure is valid, false otherwise.
const { Certificate } = require(‘crypto’);
const spkac = getSpkacSomehow();
console.log(Certificate.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
Legacy API
As a still supported legacy interface, it is possible (but not recommended) to create new instances of the crypto.Certificate class as illustrated in the examples below.
new crypto.Certificate()
Instances of the Certificate class can be created using the new keyword or by calling crypto.Certificate() as a function:
const crypto = require(‘crypto’);
const cert1 = new crypto.Certificate();
const cert2 = crypto.Certificate();
certificate.exportChallenge(spkac)
Added in: v0.11.8
spkac <string> | <Buffer> | <TypedArray> | <DataView>
Returns: <Buffer> The challenge component of the spkac data structure, which includes a public key and a challenge.
const cert = require(‘crypto’).Certificate();
const spkac = getSpkacSomehow();
const challenge = cert.exportChallenge(spkac);
console.log(challenge.toString(‘utf8’));
// Prints: the challenge as a UTF8 string
certificate.exportPublicKey(spkac)
Added in: v0.11.8
spkac <string> | <Buffer> | <TypedArray> | <DataView>
Returns: <Buffer> The public key component of the spkac data structure, which includes a public key and a challenge.
const cert = require(‘crypto’).Certificate();
const spkac = getSpkacSomehow();
const publicKey = cert.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as <Buffer …>
certificate.verifySpkac(spkac)
Added in: v0.11.8
spkac <Buffer> | <TypedArray> | <DataView>
Returns: <boolean> true if the given spkac data structure is valid, false otherwise.
const cert = require(‘crypto’).Certificate();
const spkac = getSpkacSomehow();
console.log(cert.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
Class: Cipher
Added in: v0.1.94
Extends: <stream.Transform>
Instances of the Cipher class are used to encrypt data. The class can be used in one of two ways:
As a stream that is both readable and writable, where plain unencrypted data is written to produce encrypted data on the readable side, or
Using the cipher.update() and cipher.final() methods to produce the encrypted data.
The crypto.createCipher() or crypto.createCipheriv() methods are used to create Cipher instances. Cipher objects are not to be created directly using the new keyword.
Example: Using Cipher objects as streams:
const crypto = require(‘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 async crypto.scrypt()
instead.
const key = crypto.scryptSync(password, ‘salt’, 24);
// Use crypto.randomBytes()
to generate a random iv instead of the static iv
// shown here.
const iv = Buffer.alloc(16, 0); // Initialization vector.
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = ‘’;
cipher.on(‘readable’, () => {
let chunk;
while (null !== (chunk = cipher.read())) {
encrypted += chunk.toString(‘hex’);
}
});
cipher.on(‘end’, () => {
console.log(encrypted);
// Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa
});
cipher.write(‘some clear text data’);
cipher.end();
Example: Using Cipher and piped streams:
const crypto = require(‘crypto’);
const fs = require(‘fs’);
const algorithm = ‘aes-192-cbc’;
const password = ‘Password used to generate key’;
// Use the async crypto.scrypt()
instead.
const key = crypto.scryptSync(password, ‘salt’, 24);
// Use crypto.randomBytes()
to generate a random iv instead of the static iv
// shown here.
const iv = Buffer.alloc(16, 0); // Initialization vector.
const cipher = crypto.createCipheriv(algorithm, key, iv);
const input = fs.createReadStream(‘test.js’);
const output = fs.createWriteStream(‘test.enc’);
input.pipe(cipher).pipe(output);
Example: Using the cipher.update() and cipher.final() methods:
const crypto = require(‘crypto’);
const algorithm = ‘aes-192-cbc’;
const password = ‘Password used to generate key’;
// Use the async crypto.scrypt()
instead.
const key = crypto.scryptSync(password, ‘salt’, 24);
// Use crypto.randomBytes
to generate a random iv instead of the static iv
// shown here.
const iv = Buffer.alloc(16, 0); // Initialization vector.
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(‘some clear text data’, ‘utf8’, ‘hex’);
encrypted += cipher.final(‘hex’);
console.log(encrypted);
// Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa
cipher.final([outputEncoding])
Added in: v0.1.94
outputEncoding <string> The encoding of the return value.
Returns: <Buffer> | <string> Any remaining enciphered contents. If outputEncoding is specified, a string is returned. If an outputEncoding is not provided, a Buffer is returned.
Once the cipher.final() method has been called, the Cipher object can no longer be used to encrypt data. Attempts to call cipher.final() more than once will result in an error being thrown.
cipher.setAAD(buffer[, options])
Added in: v1.0.0
buffer <Buffer> | <TypedArray> | <DataView>
options <Object> stream.transform options
plaintextLength <number>
Returns: <Cipher> for method chaining.
When using an authenticated encryption mode (GCM, CCM and OCB are currently supported), the cipher.setAAD() method sets the value used for the additional authenticated data (AAD) input parameter.
The options argument is optional for GCM and OCB. When using CCM, the plaintextLength option must be specified and its value must match the length of the plaintext in bytes. See CCM mode.
The cipher.setAAD() method must be called before cipher.update().
cipher.getAuthTag()
Added in: v1.0.0
Returns: <Buffer> When using an authenticated encryption mode (GCM, CCM and OCB are currently supported), the cipher.getAuthTag() method returns a Buffer containing the authentication tag that has been computed from the given data.
The cipher.getAuthTag() method should only be called after encryption has been completed using the cipher.final() method.
cipher.setAutoPadding([autoPadding])
Added in: v0.7.1
autoPadding <boolean> Default: true
Returns: <Cipher> for method chaining.
When using block encryption algorithms, the Cipher class will automatically add padding to the input data to the appropriate block size. To disable the default padding call cipher.setAutoPadding(false).
When autoPadding is false, the length of the entire input data must be a multiple of the cipher’s block size or cipher.final() will throw an error. Disabling automatic padding is useful for non-standard padding, for instance using 0x0 instead of PKCS padding.
The cipher.setAutoPadding() method must be called before cipher.final().
cipher.update(data[, inputEncoding][, outputEncoding])
History
data <string> | <Buffer> | <TypedArray> | <DataView>
inputEncoding <string> The encoding of the data.
outputEncoding <string> The encoding of the return value.
Returns: <Buffer> | <string>
Updates the cipher with data. If the inputEncoding argument is given, the data argument is a string using the specified encoding. If the inputEncoding argument is not given, data must be a Buffer, TypedArray, or DataView. If data is a Buffer, TypedArray, or DataView, then inputEncoding is ignored.
The outputEncoding specifies the output format of the enciphered data. If the outputEncoding is specified, a string using the specified encoding is returned. If no outputEncoding is provided, a Buffer is returned.
The cipher.update() method can be called multiple times with new data until cipher.final() is called. Calling cipher.update() after cipher.final() will result in an error being thrown.
Class: Decipher