Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Node .js encryption


May 10, 2021 Node.js


Table of contents


Encryption

稳定性: 2 - 不稳定; 正在讨论未来版本的 API 改进,会尽量减少重大变化。详见后文。

As the name implies, the Node .js encryption module allows you to use encryption, and the Node .js require('crypto')

Node .js encryption module provides a way to encapsulate security credentials during HTTP or HTTPS connections.

Node .js encryption module also provides the hash, hmac, encryption (cipher), decryption (decipher), signature (sign), and authentication (verify) methods of OpenSSL.

crypto.setEngine(engine[, flags])

Load and set the engine for some/all OpenSSL functions (set according to parameter flags).

engine may be an id, or a path to the engine shared library.

flags are optional parameters, and the default ENGINE_METHOD_ALL which can be a combination of one or more of the following parameters constants

  • ENGINE_METHOD_RSA
  • ENGINE_METHOD_DSA
  • ENGINE_METHOD_DH
  • ENGINE_METHOD_RAND
  • ENGINE_METHOD_ECDH
  • ENGINE_METHOD_ECDSA
  • ENGINE_METHOD_CIPHERS
  • ENGINE_METHOD_DIGESTS
  • ENGINE_METHOD_STORE
  • ENGINE_METHOD_PKEY_METH
  • ENGINE_METHOD_PKEY_ASN1_METH
  • ENGINE_METHOD_ALL
  • ENGINE_METHOD_NONE

crypto.getCiphers()

Returns an array of supported encryption algorithm names.

For example:

var ciphers = crypto.getCiphers();
console.log(ciphers); // ['AES-128-CBC', 'AES-128-CBC-HMAC-SHA1', ...]

crypto.getHashes()

Returns an array of supported hash algorithm names.

For example:

var hashes = crypto.getHashes();
console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]

crypto.createCredentials(details)

稳定性: 0 - 抛弃。用 [tls.createSecureContext][] 替换

Create an encrypted credential object based on the parameter details. The parameters are dictionaries, and keys include:

  • pfx A string or buffer object that represents a private key, certificate, and CA certificate encoded by PFX or PKCS12
  • key : Entered the PEM encoded private key
  • passphrase The password for the private key or pfx
  • cert A PEM-coded certificate
  • ca An array of strings or strings, PEM-encoded trusted CA certificates.
  • crl : String or string array, PEM encoded CRLs (Certificate Revocation List).
  • ciphers Strings, encryption algorithms that are used or excluded. See http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT .

If 'ca' is not specified, node .js will use the CA in the list below http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.

crypto.createHash(algorithm)

Create and return a hash object that uses the specified algorithm to generate a hash summary.

The parameter algorithm on the algorithm supported by the OpenSSL version of the platform. F or example, 'sha1' 'md5' 'sha256' 'sha512' on. In a recent release, openssllist-message-digest-algorithms all algorithms.

For example: This program calculates the amount of sha1 in the file.

var filename = process.argv[2];
var crypto = require('crypto');
var fs = require('fs');

var shasum = crypto.createHash('sha1');

var s = fs.ReadStream(filename);
s.on('data', function(d) {
  shasum.update(d);
});

s.on('end', function() {
  var d = shasum.digest('hex');
  console.log(d + '  ' + filename);
});

Class: Hash

Hase is used to generate hash values for data.

It is a read-write stream. T he data written is used to calculate the hash value. W hen the write flow ends, use read() method to get the calculated hash value. The old update and update are digest supported.

Return crypto.createHash

hash.update(data[, input_encoding])

The data content is updated based on input_encoding 'utf8' 'ascii' 'binary' I f there are no incoming values, the default 'binary' I f data is Buffer input_encoding be ignored.

Because it is streaming data, it can be called many times with different data.

hash.digest([encoding])

A hash summary of the incoming data is calculated.

encoding be 'hex' 'binary' 'base64' and encoding a buffer is returned.
Note: The digest() be used after the hash called.

crypto.createHmac(algorithm, key)

Create and return a hmac object to generate the hmac map using the specified algorithm and key.

It is a read-write stream. W rite the data to calculate hmac. W hen the write stream ends, use read() method to get the calculated value. The old update and update are digest supported.

The algorithm depends on the algorithm supported by the OpenSSL version of the platform, see the previous createHash. key is the key used in the hmac algorithm.

Class: Hmac

Used to create a hmac encryption map.

Return crypto.createHmac

hmac.update(data)

Update data object based on data. Because it is streaming data, it can be called multiple times with the new data.

hmac.digest([encoding])

Calculate the hmac value of the incoming data. encoding be 'hex' 'binary' 'base64' and encoding a buffer is returned.

Note: The digest() be used after the hmac called.

crypto.createCipher(algorithm, password)

Use incoming algorithms and keys to generate and return encrypted objects.

algorithm on OpenSSL, 'aes192' etc. I n a recent release, openssl list-cipher-algorithms available. password is used to derive key and IV, which must be 'binary' encoded string or a buffer.

It is a streaming stream that can be read and written. W rite the data to calculate hmac. W hen the write stream ends, use read() method to get the calculated value. Older update and update are digest supported.

Note that when the OpenSSL function EVP_BytesToKey digest algorithm is an iteration without the need for a salt value (no salt) MD5, createCipher the key for it. T he lack of salt values makes dictionary attacks, and the same password always generates the same key, low iteration times and unencrypted hash algorithms, making password testing very fast.

OpenSSL recommends replacing the EVP_BytesToKey with pbkdf2, crypto.pbkdf2 to derive keys and iv, and create Cipheriv() to create encrypted streams.

crypto.createCipheriv(algorithm, key, iv)

Create and return an encrypted object with the specified algorithm, key and iv.

algorithm parameter createCipher() key is used in the algorithm. iv is an initialization vector .

key and iv be 'binary' strings or buffers .

Class: Cipher

The class that encrypts the data.

Return crypto.createCipher crypto.createCipheriv

It is a streaming stream that can be read and written. W rite the data to calculate hmac. W hen the write stream ends, use read() method to get the calculated value. T he old update and update are digest supported.

cipher.update(data[, input_encoding][, output_encoding])

Update the hash content based on data input_encoding according to 'utf8' 'ascii' 'binary' I f there are no incoming values, the default 'binary' I f data is Buffer input_encoding be ignored.

output_encoding the encoding format of the 'binary' 'base64' 'hex' If no encoding is provided, a buffer is returned.

The encrypted content is returned because it is streaming data, so it can be called many times with different data.

cipher.final([output_encoding])

Returns encrypted content, encoded output_encoding which can 'binary' 'base64' 'hex' If there is no incoming value, a buffer is returned.

Note: cipher object cannot be final() method.

cipher.setAutoPadding(auto_padding=true)

You can disable the ability to automatically populate input data to block size. I f auto_padding false, the length of the input data must be a full number of the size of the block of the encryptor, final will fail. T his is useful for non-standard padding, such as 0x0 instead of PKCS. This function must be cipher.final

cipher.getAuthTag()

Encrypted authentication mode (currently supported: GCM), which returns the calculated certification flag Buffer The final method final to fully encrypt after the call.

cipher.setAAD(buffer)

Encrypted authentication mode (currently supported: GCM), which sets up additional authentication data (AAD).

crypto.createDecipher(algorithm, password)

Create and return a decryption object based on the incoming algorithm and key. This is a mirror image of createCipher().

crypto.createDecipheriv(algorithm, key, iv)

Create and return a decrypted object based on the incoming algorithm, key, and iv. This is a mirror image of createCipheriv().

Class: Decipher

Decrypt the data class.

Return crypto.createDecipher crypto.createDecipheriv

The decrypted object is a readable stream stream. C reate readable plain text data from written encrypted data. O lder update and update are digest supported.

decipher.update(data[, input_encoding][, output_encoding])

Use the parameter data update what needs to be decrypted 'binary' 'base64' 'hex' If no encoding is specified, data buffer object.

If data is Buffer ignore input_encoding parameter.

The output_decoding the format of the returned text and is 'binary' 'ascii' 'utf8' If no encoding format is provided, a buffer is returned.

decipher.final([output_encoding])

Returns the remaining decrypted content, parameter output_encoding 'binary' 'ascii' 'utf8' and if no encoding method is specified, back to buffer.

Note: decipher cannot be final() method.

decipher.setAutoPadding(auto_padding=true)

If the encrypted data is a non-standard block, it can be automatically populated to prevent decipher.final checked and removed. V alid only if the length of the input data is an integer of the length of the encrypted block. You must decipher.update

decipher.setAuthTag(buffer)

For crypto authentication mode (currently supported: GCM), this method must be used to pass the received authentication flag. If no flag is provided, or the red text is tampered with, the final authentication fails, and the red flag is discarded.

decipher.setAAD(buffer)

For crypto authentication mode (currently supported: GCM), this method is used to set up additional authentication data (AAD).

crypto.createSign(algorithm)

Create and return a signature data based on the incoming algorithm. In the most recent version of openssl list-public-key-algorithms such 'RSA-SHA256'

Class: Sign

The class that generates the digital signature.

Return crypto.createSign

The signature object is a stream stream that can be read and written. W riteable data is used to generate signatures. W hen all the data is finished, sign signature method returns the signature. O lder update and update are digest supported.

sign.update(data)

Update the data with the parameter data. Because it is streaming data, it can be called multiple times.

sign.sign(private_key[, output_format])

Electronic signatures are calculated based on the data transmitted to the sign.

private_key can be an object or a string. If it's a string, it's going to be taken as a key without a password.

private_key :

  • key The private key that contains the PEM encoding
  • passphrase The password for the private key

The return output_format a digital signature in the format 'binary' 'hex' or 'base64' I f encoding a buffer is returned.

Note: sign object cannot be sign() method.

crypto.createVerify(algorithm)

The validation object is created and returned based on the incoming algorithm. is a mirror image of the signature object.

Class: Verify

The class used to verify the signature.

Return crypto.createVerify

is a writeable stream stream stream. W riteable data is used to validate the signature. O nce all the data has been written, the verify method, such as signing verify true

The old update method is update

verifier.update(data)

Update the data with the parameter data. Because it is streaming data, it can be called multiple times.

verifier.verify(object, signature[, signature_format])

Validate object data signature and signature. A rgument object a string that contains PEM encoded objects, which can be RSA public key, DSA public key, or X.509 certificate. signature a previously calculated digital signature. signature_format be 'binary' 'hex' 'base64' and if you don't specify how to encode, the default is a buffer object.

Verify signature validity based on data and public keys to return true or false.

Note: verifier object cannot be verify() method.

crypto.createDiffieHellman(prime_length[, generator])

Create a Diffie-Hellman key exchange object and generate a mass based on a given bit length. If you do not specify generator the default 2

crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding])

Create a generator key interaction object using the incoming prime and generator.

generator can be a number, string, or Buffer.

If generator is generator specified, 2 .

prime_encoding and generator_encoding can be 'binary' 'hex' 'base64'

If no prime_encoding specified, Buffer is prime

If the generator_encoding Buffer is generator

Class: Diffie Hellman

Create a class for Diffie-Hellman key exchange.

Return crypto.createDiffieHellman

diffieHellman.verifyError

This is reflected when initialization occurs if there is a warning or error. It is the following value (defined in constants module):

  • DH_CHECK_P_NOT_SAFE_PRIME
  • DH_CHECK_P_NOT_PRIME
  • DH_UNABLE_TO_CHECK_GENERATOR
  • DH_NOT_SUITABLE_GENERATOR

diffieHellman.generateKeys([encoding])

Generates the key and public key, and returns the public key in the specified format. T his value must be passed to other parts. C oded 'binary' 'hex' or 'base64' I f no encoding method is specified, a buffer is returned.

diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding])

Use other_public_key a third-party public key to calculate and return shared secrets. T he key is input_encoding the file. C oded 'binary' 'hex' or 'base64' I f you do not specify how to code, the default is buffer.

If no return encoding is specified, a buffer is returned.

diffieHellman.getPrime([encoding])

The Diffie-Hellman number is returned in the encoding method indicated by the parameter encoding, which is: 'binary' 'hex' 'base64' If no encoding method is specified, a buffer is returned.

diffieHellman.getGenerator([encoding])

The Diffie-Hellman generator is returned in the encoding method indicated by the parameter encoding, which is: 'binary' 'hex' 'base64' If no encoding method is specified, a buffer is returned.

diffieHellman.getPublicKey([encoding])

The Diffie-Hellman public key is returned in the encoding indicated by the parameter encoding in the following manner: 'binary' 'hex' 'base64' I f no encoding method is specified, a buffer is returned.

diffieHellman.getPrivateKey([encoding])

The Diffie-Hellman private key is returned in the encoding indicated by the parameter encoding in the following manner: 'binary' 'hex' 'base64' I f no encoding method is specified, a buffer is returned.

diffieHellman.setPublicKey(public_key[, encoding])

Set Diffie-Hellman's public key 'binary' 'hex' 'base64' which defaults to buffer if no encoding method is specified.

diffieHellman.setPrivateKey(private_key[, encoding])

Set Diffie-Hellman's private key 'binary' 'hex' 'base64' which defaults to buffer if no encoding is specified.

crypto.getDiffieHellman(group_name)

Create a predefined Diffie-Hellman key exchange object. S upported 'modp1' 'modp2' 'modp5' (defined in RFC 2412), 'modp14' 'modp15' 'modp16' 'modp17' 'modp18' (defined in RFC 3526). T he return object mimics the crypto.createDiffie Hellman() object created above, but does not allow the key exchange to be modified (for example, diffieHellman.setPublicKey(). The benefit of using this process is that both parties do not need to generate or exchange group remainings, saving computing and communication time.

For example (get a shared secret):

var crypto = require('crypto');
var alice = crypto.getDiffieHellman('modp5');
var bob = crypto.getDiffieHellman('modp5');

alice.generateKeys();
bob.generateKeys();

var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');

/* alice_secret and bob_secret should be the same */
console.log(alice_secret == bob_secret);

crypto.createECDH(curve_name)

Create an curve_name Eliptic (EC) Diffie-Hellman key exchange object using the incoming parameters to create a key exchange object.

Class: ECDH

This class is used to create an EC Diffie-Hellman key exchange.

Return crypto.createECDH

ECDH.generateKeys([encoding[, format]])

The KEY and public key of EC Diffie-Hellman are generated and returned in the specified format and encoded public key, which is passed to a third party.

The format is 'compressed' 'uncompressed' 'hybrid' If not specified, the 'uncompressed'

The encoding is 'binary' 'hex' or 'base64' I f no encoding method is specified, a buffer is returned.

ECDH.computeSecret(other_public_key[, input_encoding][, output_encoding])

Use other_public_key a third-party public key calculation to share secrets and return them. T he key is input_encoding the key. T he codes 'binary' 'hex' 'base64' If no encoding method is specified, the default is buffer.

If no encoding method is specified, a buffer is returned.

ECDH.getPublicKey([encoding[, format]])

The EC Diffie-Hellman public key is returned in the encoding indicated by the parameter encoding in 'compressed' 'uncompressed' 'hybrid' If no encoding method is 'uncompressed'

The codes 'binary' 'hex' 'base64' I f you do not specify how to code, the default is buffer.

ECDH.getPrivateKey([encoding])

The EC Diffie-Hellman private key is returned in the encoding indicated by the parameter encoding, which is: 'binary' 'hex' 'base64' If you do not specify how to code, the default is buffer.

ECDH.setPublicKey(public_key[, encoding])

Set ec Diffie-Hellman's public key 'binary' 'base64' which defaults to buffer if no encoding method is specified. 'hex'

ECDH.setPrivateKey(private_key[, encoding])

Set ec Diffie-Hellman's private key 'binary' or 'base64' which defaults to buffer if no encoding method is specified. 'hex'

For example (containing a shared secret):

var crypto = require('crypto');
var alice = crypto.createECDH('secp256k1');
var bob = crypto.createECDH('secp256k1');

alice.generateKeys();
bob.generateKeys();

var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');

/* alice_secret and bob_secret should be the same */
console.log(alice_secret == bob_secret);

crypto.pbkdf2(password, salt, iterations, keylen[, digest], callback)

Asynchronous PBKDF2 provides a pseudo-random function, HMAC-SHA1, to arrive at a key based on the length of a given password, salt, and iterations. The callback function gets two arguments (err, derivedKey).

For example:

crypto.pbkdf2('secret', 'salt', 4096, 512, 'sha256', function(err, key) {
  if (err)
    throw err;
  console.log(key.toString('hex'));  // 'c5e478d...1469e50'
});

There is a list of supported summary functions in crypto.getHashes().

crypto.pbkdf2Sync(password, salt, iterations, keylen[, digest])

Asynchronous PBKDF2 function, returns aderivedKey or throws an error.

crypto.randomBytes(size[, callback])

To generate a random data for password strength:

// async
crypto.randomBytes(256, function(ex, buf) {
  if (ex) throw ex;
  console.log('Have %d bytes of random data: %s', buf.length, buf);
});

// sync
try {
  var buf = crypto.randomBytes(256);
  console.log('Have %d bytes of random data: %s', buf.length, buf);
} catch (ex) {
  // handle error
  // most likely, entropy sources are drained
}

Note: If there is not enough accumulated entropy to generate a random strength password, an error will be thrown or a callback function will be called to return an error. In other words, crypto.randomBytes if all entropy is exhausted.

crypto.pseudoRandomBytes(size[, callback])

Pseudo-random data generated for non-cryptological strength. I f the data is long enough, a unique data is returned, but this number may be predictable. T herefore, do not use this function when it is not expected to be important. For example, when an encrypted key is generated.

The usage is crypto.randomBytes

Class: Certificate

This class deals with signed public keys. The most important scenario is to work with the elements of <keygen> http://www.openssl.org/docs/apps/spkac.html.

By crypto.Certificate returns.

Certificate.verifySpkac(spkac)

Return true or false according to SPKAC.

Certificate.exportChallenge(spkac)

According to the SPKAC provided, the encrypted public key is returned.

Certificate.exportPublicKey(spkac)

The output is associated with the SPKAC encoding challenge.

crypto.publicEncrypt(public_key, buffer)

Use public_key encrypt the buffer Currently only RSA is supported.

public_key be an object or a string. If public_key is a string, it will be used as a key without a password and will RSA_PKCS1_OAEP_PADDING

public_key :

  • key : Contains a private key encoded with PEM.
  • padding Fill values, as follows
    • constants.RSA_NO_PADDING
    • constants.RSA_PKCS1_PADDING
    • constants.RSA_PKCS1_OAEP_PADDING

Note: All fill values are defined in constants module.

crypto.privateDecrypt(private_key, buffer)

Use private_key decrypt the buffer .

private_key :

  • key : Contains a private key encoded with PEM
  • passphrase The password for the private key
  • padding Fill values, as follows:
    • constants.RSA_NO_PADDING
    • constants.RSA_PKCS1_PADDING
    • constants.RSA_PKCS1_OAEP_PADDING

Note: All fill values are defined constants module.

crypto. DEFAULT_ENCODING

Functions can be encoded as strings or buffers, with the default value of 'buffer'. This is to make the encryption module compatible with legacy programs that default to 'binary' as encoding.

Note: The new program wants to use the buffer object, so this is a temporary means.

Recent API Changes

The Crypto module was added to Node before the unified streaming API concept emerged, before the Buffalo object was introduced to handle binary data.

Therefore, there are no other typical methods in the flow-related class, and many methods receive and return second-level encoded strings instead of Buffers. In a recent release, these functions were changed to use Buffers by default.

This is a significant change for some scenarios.

For example, if you use the default parameters to sign a class and return the results to the authentication class, with no validation data in the middle, the program will work. Previously you would get binary encoded strings and pass them to the validation class, now it's Buffer.

If the string data you used earlier doesn't work in the Buffalo object (for example, connecting data and storing it in a database). O r you pass a binary string to an encryption function, but you don't specify how to encode it, and now you need to provide encoding parameters. I f you want to switch back to the original style, crypto.DEFAULT_ENCODING set to 'binary'. Note that the new program is possible as a buffers, so the previous method can only be used as a temporary solution.