Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Crypto encryption of nodeJS

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

The encryption module provides a way to encapsulate security credentials during HTTP or HTTPS connections. OpenSSL also provides encapsulation of hash, hmac, encryption (cipher), decryption (decipher), signature (sign) and verification (verify) methods. This article will introduce encryption crypto in detail

Crypto

[crypto.setEngine (engine [, flags])]

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

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

Flags is an optional parameter with a default value of ENGINE_METHOD_ALL, which can be a combination of one or more of the following parameters (defined in constants)

ENGINE_METHOD_RSAENGINE_METHOD_DSAENGINE_METHOD_DHENGINE_METHOD_RANDENGINE_METHOD_ECDHENGINE_METHOD_ECDSAENGINE_METHOD_CIPHERSENGINE_METHOD_DIGESTSENGINE_METHOD_STOREENGINE_METHOD_PKEY_METHENGINE_METHOD_PKEY_ASN1_METHENGINE_METHOD_ALLENGINE_METHOD_NONE

[crypto.getCiphers ()]

Returns an array of supported encryption algorithm names

Crypto = require ('crypto'

[crypto.getCiphers ()]

Returns an array of supported hash algorithm names.

Var crypto = require ('crypto'); console.log (crypto.getHashes ()) / / ['DSA',' DSA-SHA', 'DSA-SHA1',' DSA-SHA1-old', 'RSA-MD4',' RSA-MD5', 'RSA-MDC2',' RSA-RIPEMD160', 'RSA-SHA',' RSA-SHA1', 'RSA-SHA1-2,' RSA-SHA224', 'RSA-SHA256',' RSA-SHA384', 'RSA-SHA512',' dsaEncryption', 'dsaWithSHA',' dsaWithSHA1', 'dss1' 'ecdsa-with-SHA1', 'md4',' md4WithRSAEncryption', 'md5',' md5WithRSAEncryption', 'mdc2',' mdc2WithRSA', 'ripemd',' ripemd160', 'ripemd160WithRSA',' rmd160', 'sha',' sha1', 'sha1WithRSAEncryption',' sha224', 'sha224WithRSAEncryption',' sha256', 'sha256WithRSAEncryption',' sha384', 'sha384WithRSAEncryption',' sha512', 'sha512WithRSAEncryption',' shaWithRSAEncryption', 'ssl2-md5' 'ssl3-md5',' ssl3-sha1', 'whirlpool']

[crypto.getCurves ()]

Returns an array of supported elliptic curve names.

Var crypto = require ('crypto'); console.log (crypto.getCurves ()) / ['Oakley-EC2N-3',' Oakley-EC2N-4', 'brainpoolP160r1',' brainpoolP160t1', 'brainpoolP192r1',' brainpoolP192t1', 'brainpoolP224r1',' brainpoolP224t1', 'brainpoolP256r1',' brainpoolP256t1', 'brainpoolP320r1',' brainpoolP320t1', 'brainpoolP384r1',' brainpoolP384t1', 'brainpoolP512r1',' brainpoolP512t1', 'c2pnb163v1,' c2pnb163v2, 'c2pnb176v1,' c2pnb208w1, 'c2pnb272w1,' c2pnb304w1, 'c2pnb368w1' 'c2tnb191v1', 'c2tnb191v1v3', 'c2tnb191v3', 'c2tnb239v1', 'c2tnb239v2', 'c2tnb239v3', 'c2tnb431r1', 'prime192v1',' prime192v2', 'prime192v3',' prime239v1', 'prime239v2',' prime239v3', 'prime256v1',' secp112r1', 'secp128r1',' secp128r2', 'secp160k1',' secp160r1', 'secp192k1',' secp224k1', 'secp224r1',' secp256k1' 'secp384r1', 'secp521r1',' sect113r1', 'sect113r2',' sect131r1', 'sect131r2',' sect163k1', 'sect163r1',' sect163r2', 'sect193r1',' sect193r2', 'sect233k1',' sect233r1', 'sect239k1',' sect283k1', 'sect283r1',' sect409k1', 'sect409r1',' sect571k1', 'sect571r1',' wap-wsg-idm-ecid-wtls1', 'wap-wsg-idm-ecid-wtls10' 'wap-wsg-idm-ecid-wtls11', 'wap-wsg-idm-ecid-wtls12',' wap-wsg-idm-ecid-wtls3', 'wap-wsg-idm-ecid-wtls4',' wap-wsg-idm-ecid-wtls5', 'wap-wsg-idm-ecid-wtls6',' wap-wsg-idm-ecid-wtls7', 'wap-wsg-idm-ecid-wtls8',' wap-wsg-idm-ecid-wtls9']

MD5

MD5 is a commonly used hashing algorithm that is used to "sign" arbitrary data. This signature is usually represented by a hexadecimal string:

[crypto.createHash (algorithm)]

Creates and returns a hash object that uses the specified algorithm to generate a hash summary.

The parameter algorithm depends on the algorithm supported by the version of OpenSSL on the platform. For example, 'sha1',' md5', 'sha256',' sha512' and so on.

[hash.update (data [, input_encoding])]

The hash content is updated according to data, and the encoding method is based on input_encoding. There are 'utf8',' ascii' or 'binary''. If no value is passed in, the default encoding is' utf8'. If data is Buffer, input_encoding will be ignored.

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

[hash.digest ([encoding])]

Calculates the hash summary of the incoming data. Encoding can be 'hex',' binary' or 'base64',. If no encoding is specified, buffer will be returned.

[note] the hash object can no longer be used after calling digest ().

Var crypto = require ('crypto'); var hash = crypto.createHash (' md5'); / / you can call update () as many times as you like: hash.update ('Hello, worldview'); hash.update ('Hello, nodejs'); console.log (hash.digest ('hex')); / / 7e1977739c748beac0c0fd14fd26a544

Hmac

Hmac algorithm is also a hash algorithm, which can use hash algorithms such as MD5 or SHA1. The difference is that Hmac also needs a key:

[crypto.createHmac (algorithm, key)]

Creates and returns a hmac object that generates a hmac graph with the specified algorithm and secret key.

It is a read-write stream stream. The written data is used to calculate the hmac. When the write stream ends, use the read () method to get the calculated value. The old update and digest methods are also supported.

The parameter algorithm depends on the algorithms supported by the OpenSSL version on the platform, as shown in the previous createHash. Key is the key used in hmac algorithm.

[hmac.update (data)]

Update the hmac object according to data. Because it is streaming data, it can be called multiple times with new data.

[hmac.digest ([encoding])]

Calculates the hmac value of the incoming data. Encoding can be 'hex',' binary' or 'base64',. If no encoding is specified, buffer will be returned.

[note] the hmac object can no longer be used after calling digest ()

Var crypto = require ('crypto'); var hmac = crypto.createHmac (' sha256', 'match'); hmac.update (' Hello, worldview'); hmac.update ('Hello, Nodejs'); / / e82a58066cae2fae4f44e58be1d589b66a5d102c2e8846d796607f02a88c1649console.log (hmac.digest ('hex'))

AES

AES is a commonly used symmetric encryption algorithm, which uses the same key for encryption and decryption. The crypto module provides AES support, but you need to encapsulate the function to make it easy to use:

[crypto.createCipher (algorithm, password)]

Use the passed algorithm and secret key to generate and return encrypted objects.

Algorithm depends on OpenSSL, such as' aes192', etc. Password is used to derive key and IV, which must be a binary'-encoded string or a buffer.

It is a read-write stream stream. The written data is used to calculate the hmac. When the write stream ends, use the read () method to get the calculated value. The old update and digest methods are also supported.

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

The hash content is updated according to data, and the encoding method is determined according to input_encoding. There are 'utf8',' ascii' or 'binary'. If no value is passed in, the default encoding is' binary'. If data is Buffer,input_encoding, it will be ignored.

Output_encoding specifies the encoding format of the output encrypted data, which can be 'binary',' base64' or 'hex'. If no encoding is provided, buffer is returned.

Returns the encrypted content, which can be called many times with different data because it is streaming data.

[cipher.final ([output_encoding])]

Returns the encrypted content, which is encoded by output_encoding and can be 'binary',' base64' or 'hex'. If no value is passed in, buffer is returned.

[note] the cipher object cannot be called after the final () method.

Var crypto = require ('crypto'); function aesEncrypt (data, key) {const cipher = crypto.createCipher (' aes192', key); var crypted = cipher.update (data, 'utf8',' hex'); crypted + = cipher.final ('hex'); return crypted;} var data =' Hello, this is a secret messageswitting var encrypted = aesEncrypt (data, key); / / 8a944d97bdabc157a5b7a40cb180e713f901d2eb454220d6aaa1984831e17231f87799ef334e3825123658c80e0e5d0cconsole.log (encrypted)

[crypto.createDecipher (algorithm, password)]

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

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

Update the content that needs to be decrypted with the parameter data, which is encoded as' binary','base64' or 'hex'. If no encoding is specified, data is treated as a buffer object.

If data is Buffer, the input_encoding parameter is ignored.

The parameter output_decoding specifies the format of the returned text, which is one of 'binary',' ascii' or 'utf8'. If no encoding format is provided, buffer is returned.

[decipher.final ([output_encoding])]

Returns the rest of the decrypted content. The parameter output_encoding is' binary', 'ascii' or' utf8',. If no encoding method is specified, buffer is returned.

[note] decipher objects cannot be used after the final () method.

Var crypto = require ('crypto'); function aesDecrypt (encrypted, key) {const decipher = crypto.createDecipher (' aes192', key); var decrypted = decipher.update (encrypted, 'hex',' utf8'); decrypted + = decipher.final ('utf8'); return decrypted;} var data =' Hello, this is a secret messagehands dealing with var key = 'Passwordhands' political var encrypted = '8a944d97bdabc157a40cb180e713f901d2eb45420d6aaa1984831e17231f87799ef334e3825123658c80e0e5d0cexamples = aesDecrypt (encrypted, key); console.log (decrypted); / Hello

As you can see, the encrypted string gets the original content through decryption.

Note that AES has many different algorithms, such as aes192,aes-128-ecb,aes-256-cbc, etc. AES can also specify IV (Initial Vector) in addition to the key. As long as the IV is different in different systems, the encryption results obtained by encrypting the same data with the same key are also different. There are usually two ways to express the encryption result: hex and base64, all of which are supported by Nodejs, but it should be noted in the application that if one side of the encryption and decryption uses Nodejs, the other side uses Java, PHP and other languages, it needs to be tested carefully. If you cannot decrypt correctly, make sure whether both parties follow the same AES algorithm, whether the string key and IV are the same, and whether the encrypted data is in hex or base64 format.

[crypto.createCipheriv (algorithm, key, iv)]

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

The algorithm parameter is consistent with createCipher (). Key used in the algorithm. IV is an initialization vector.

Key and iv must be the encoded string of 'binary' or buffers.

[crypto.createDecipheriv (algorithm, key, iv)]

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

Const crypto = require ('crypto'); function aesEncryptiv (data, key,iv) {const cipher = crypto.createCipher (' aes192', key,iv); var crypted = cipher.update (data, 'utf8',' hex'); crypted + = cipher.final ('hex'); return crypted;} function aesDecryptiv (encrypted, key,iv) {const decipher = crypto.createDecipher (' aes192', key,iv); var decrypted = decipher.update (encrypted, 'hex',' utf8') Decrypted + = decipher.final ('utf8'); return decrypted;} var data =' Hello, this is a secret messageworthy console.log (encrypted); / / Hello, this is a secret messageconsole.log (decrypted)

Diffie-Hellman

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

Create an Diffie-Hellman key interaction object using the incoming prime and generator.

Generator can be a number, a string, or a Buffer. If no generator is specified, use 2

Prime_encoding and generator_encoding can be 'binary',' hex', or 'base64'.

If no prime_encoding is specified, Buffer is prime. If no generator_encoding is specified, Buffer is generator.

[diffieHellman.generateKeys ([encoding])]

Generates the secret key and public key and returns the public key in the specified format. This value must be passed to other parts. Encoding method: 'binary',' hex', or 'base64'. If no encoding is specified, buffer is returned.

[diffieHellman.getPrime ([encoding])]

The Diffie-Hellman prime number is returned with the encoding method specified in the parameter encoding, which is' binary', 'hex', or' base64'. If no encoding is specified, buffer is returned.

[diffieHellman.getGenerator ([encoding])]

Return the Diffie-Hellman generator with the encoding specified in the parameter encoding: 'binary',' hex', or 'base64'. If no encoding is specified, buffer is returned.

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

Use other_public_key as the third-party public key to calculate and return the shared secret (shared secret). The secret key is encoded in input_encoding. The encoding method is: 'binary',' hex', or 'base64'. If no encoding is specified, the default is buffer.

If no return encoding is specified, buffer is returned.

DH algorithm

DH algorithm is a key exchange protocol, which allows two parties to negotiate a key without revealing the key. The DH algorithm is based on mathematical principles. For example, if Xiao Ming and Xiao Hong want to negotiate a key, they can do this:

1. Xiao Ming first chooses a prime number and a base number, for example, prime 23 and base 5 (optional), and then selects a secret integer axiom 6, calculates A = g ^ a mod pendant 8, and then tells Xiao Hong loudly, "pendant 23, gallows, 5, and 8."

2. After Xiao Hong received the pjiggy A from Xiao Ming, she also chose a secret integer baked 15, and then calculated B = g ^ b mod pendant 19, and told Xiao Ming loudly: bang 19

3. Xiaoming calculated s = B ^ a mod paired 2, and Xiao Hong calculated s = A ^ b mod paired 2, so the final negotiated key s is 2.

In this process, the key 2 is not told to Xiao Hong by Xiao Ming, nor told by Xiao Hong, but calculated through negotiation between the two parties. The third party can only know the secret integers adept 6 and 15, so the key 2 can not be calculated.

The implementation of DH algorithm with crypto module is as follows:

Var crypto = require ('crypto'); / / xiaoming's keys:var ming = crypto.createDiffieHellman; var ming_keys = ming.generateKeys (); var prime = ming.getPrime (); var generator = ming.getGenerator (); / / Prime: 8df777257625c66821af697652f28e93af05b9f779af919111b89816faa11c36fcf9df04c76811471a6099800213c4fe8e3fbec8d2f90bd00795e4b7fd241603console.log (' Prime:'+ prime.toString ('hex')); / / Generator: 02console.log (' Generator:'+ generator.toString ('hex')); / / xiaohong's keys:var hong = crypto.createDiffieHellman (prime, generator) Var hong_keys = hong.generateKeys (); / / exchange and generate secret:var ming_secret = ming.computeSecret (hong_keys); var hong_secret = hong.computeSecret (ming_keys); / / Secret of Xiao Ming: 4237157ab4c9211f78ffdb67d127d749cec91780d594b81a7e75f1fb591fecb84f33ae6591e1edda4bc9685b503010fe8f9928c6ed69e4ff9fdb44adb9ba1539console.log ('Secret of Xiao Ming:' + ming_secret.toString ('hex')); / / Secret of Xiao Hong: 4237157ab4c9211f78ffdb67d127d749cec91780d594b81a7e75f1fb591fecb84f33ae6591e1edda4bc9685b503010fe8f9928c6ed69e4ff9fdb44adb9ba1539console.log (' Secret of Xiao Hong:'+ hong_secret.toString ('hex'))

[note] the output is different each time, because the choice of prime numbers is random.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report