Table of Contents
Previous words
crypto
MD5
Hmac
AES
Diffie-Hellman
Home Web Front-end JS Tutorial Detailed explanation of nodeJS's crypto encryption method

Detailed explanation of nodeJS's crypto encryption method

Jun 24, 2017 pm 02:49 PM
Crypto javascript nodejs encryption

Previous words

The encryption module provides a method of encapsulating security credentials during HTTP or HTTPS connections. Encapsulation of OpenSSL's hash, hmac, encryption (cipher), decryption (decipher), signature (sign) and verify (verify) methods is also provided. This article will introduce encryption crypto

crypto

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

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

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

Flags is an optional parameter, the default value is ENGINE_METHOD_ALL, which can be a combination of one or more of the following parameters (defined in 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
Copy after login

[crypto.getCiphers ()】

Returns an array of supported encryption algorithm names

 crypto = require('crypto'
Copy after login

【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' ]
Copy after login

【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',  'c2pnb163v3',  'c2pnb176v1',  'c2pnb208w1',  'c2pnb272w1',  'c2pnb304w1',  'c2pnb368w1',  'c2tnb191v1',  'c2tnb191v2',  'c2tnb191v3',  'c2tnb239v1',  'c2tnb239v2',  'c2tnb239v3',  'c2tnb359v1',  'c2tnb431r1',  'prime192v1',  'prime192v2',  'prime192v3',  'prime239v1',  'prime239v2',  'prime239v3',  'prime256v1',  'secp112r1',  'secp112r2',  'secp128r1',  'secp128r2',  'secp160k1',  'secp160r1',  'secp160r2',  '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' ]
Copy after login

MD5

MD5 is a commonly used hash algorithm used to give any data a "signature". This signature is usually represented by a hexadecimal string:

[crypto.createHash(algorithm)]

Create and return a hash object, using the specified algorithm to generate the hash Summary.

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

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

 Update the hash content based on data , the encoding method is determined according to input_encoding, including 'utf8', 'ascii' or 'binary'. If no value is passed in, the default encoding is 'utf8'. If data is a Buffer, input_encoding will be ignored.

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

【hash.digest([encoding])】

Calculate the hash digest of the incoming data. encoding can be 'hex', 'binary' or 'base64', if encoding is not specified, buffer will be returned.

 [Note] The hash object cannot be used after calling digest().

var crypto = require('crypto');var hash = crypto.createHash('md5');// 可任意多次调用update():hash.update('Hello, world!');
hash.update('Hello, nodejs!');

console.log(hash.digest('hex')); // 7e1977739c748beac0c0fd14fd26a544
Copy after login

Hmac

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

[crypto.createHmac(algorithm, key)]

Create and return an hmac object, and use the specified algorithm and secret key to generate an hmac map. .

 It is a readable and writable stream stream. The written data is used to calculate hmac. When writing to the stream has finished, use the read() method to obtain the calculated value. The old update and digest methods are also supported.

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

[hmac.update(data)]

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

【hmac.digest([encoding])】

Calculate the hmac value of the incoming data. encoding can be 'hex', 'binary' or 'base64', if encoding is not specified, buffer will be returned.

 [Note] The hmac object cannot be used after calling digest()

var crypto = require('crypto');var hmac = crypto.createHmac('sha256', 'match');

hmac.update('Hello, world!');
hmac.update('Hello, nodejs!');//e82a58066cae2fae4f44e58be1d589b66a5d102c2e8846d796607f02a88c1649console.log(hmac.digest('hex'));
Copy after login

 

AES

  AES是一种常用的对称加密算法,加解密都用同一个密钥。crypto模块提供了AES支持,但是需要自己封装好函数,便于使用:

【crypto.createCipher(algorithm, password)】

  使用传入的算法和秘钥来生成并返回加密对象。

  algorithm 取决于 OpenSSL,例如'aes192'等。password 用来派生 key 和 IV,它必须是一个'binary' 编码的字符串或者一个buffer。

  它是可读写的流 stream 。写入的数据来用计算 hmac。当写入流结束后,使用 read() 方法来获取计算后的值。也支持老的update 和 digest 方法。

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

  根据 data 来更新哈希内容,编码方式根据 input_encoding 来定,有 'utf8', 'ascii' or 'binary'。如果没有传入值,默认编码方式是'binary'。如果data 是 Buffer,input_encoding 将会被忽略。

  output_encoding 指定了输出的加密数据的编码格式,它可用是 'binary', 'base64' 或 'hex'。如果没有提供编码,将返回 buffer 。

  返回加密后的内容,因为它是流式数据,所以可以使用不同的数据调用很多次。

【cipher.final([output_encoding])】

  返回加密后的内容,编码方式是由 output_encoding 指定,可以是 'binary', 'base64' 或 'hex'。如果没有传入值,将返回 buffer。

  [注意]cipher 对象不能在 final() 方法之后调用。

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 message!';var key = 'Password!';var encrypted = aesEncrypt(data, key);//8a944d97bdabc157a5b7a40cb180e713f901d2eb454220d6aaa1984831e17231f87799ef334e3825123658c80e0e5d0cconsole.log(encrypted);
Copy after login

【crypto.createDecipher(algorithm, password)】

  根据传入的算法和密钥,创建并返回一个解密对象。这是 createCipher() 的镜像

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

  使用参数 data 更新需要解密的内容,其编码方式是 'binary','base64' 或 'hex'。如果没有指定编码方式,则把 data 当成 buffer 对象。

  如果 data 是 Buffer,则忽略 input_encoding 参数。

  参数 output_decoding 指定返回文本的格式,是 'binary', 'ascii' 或 'utf8' 之一。如果没有提供编码格式,则返回 buffer。

【decipher.final([output_encoding])】

  返回剩余的解密过的内容,参数 output_encoding 是 'binary', 'ascii' 或 'utf8',如果没有指定编码方式,返回 buffer。

  [注意]decipher对象不能在 final() 方法之后使用。

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 message!';var key = 'Password!';var encrypted = '8a944d97bdabc157a5b7a40cb180e713f901d2eb454220d6aaa1984831e17231f87799ef334e3825123658c80e0e5d0c';var decrypted = aesDecrypt(encrypted, key);
console.log(decrypted);//Hello, this is a secret message!
Copy after login

  可以看出,加密后的字符串通过解密又得到了原始内容。

  注意到AES有很多不同的算法,如aes192aes-128-ecbaes-256-cbc等,AES除了密钥外还可以指定IV(Initial Vector),不同的系统只要IV不同,用相同的密钥加密相同的数据得到的加密结果也是不同的。加密结果通常有两种表示方法:hex和base64,这些功能Nodejs全部都支持,但是在应用中要注意,如果加解密双方一方用Nodejs,另一方用Java、PHP等其它语言,需要仔细测试。如果无法正确解密,要确认双方是否遵循同样的AES算法,字符串密钥和IV是否相同,加密后的数据是否统一为hex或base64格式

【crypto.createCipheriv(algorithm, key, iv)】

  创建并返回一个加密对象,用指定的算法,key 和 iv。

  algorithm 参数和 createCipher() 一致。key 在算法中用到.iv 是一个initialization vector.

  key 和 iv 必须是 'binary' 的编码字符串或buffers.

【crypto.createDecipheriv(algorithm, key, iv)】

  根据传入的算法,密钥和 iv,创建并返回一个解密对象。这是 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 message!';var key = 'Password!';var iv = 'match';var encrypted = aesEncryptiv(data, key, iv);var decrypted = aesDecryptiv(encrypted, key, iv);//Hello, this is a secret message!console.log(data);//8a944d97bdabc157a5b7a40cb180e713f901d2eb454220d6aaa1984831e17231f87799ef334e3825123658c80e0e5d0cconsole.log(encrypted);//Hello, this is a secret message!console.log(decrypted);
Copy after login

 

Diffie-Hellman

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

  使用传入的 prime 和 generator 创建 Diffie-Hellman 秘钥交互对象。

  generator 可以是数字,字符串或Buffer。如果没有指定 generator,使用 2

  prime_encoding 和 generator_encoding 可以是 'binary', 'hex', 或 'base64'。

  如果没有指定 prime_encoding, 则 Buffer 为 prime。如果没有指定 generator_encoding ,则 Buffer 为 generator。

【diffieHellman.generateKeys([encoding])】

  生成秘钥和公钥,并返回指定格式的公钥。这个值必须传给其他部分。编码方式: 'binary', 'hex', 或 'base64'。如果没有指定编码方式,将返回 buffer。

【diffieHellman.getPrime([encoding])】

  用参数 encoding 指明的编码方式返回 Diffie-Hellman 质数,编码方式为: 'binary', 'hex', 或 'base64'。 如果没有指定编码方式,将返回 buffer。

【diffieHellman.getGenerator([encoding])】

  用参数 encoding 指明的编码方式返回 Diffie-Hellman 生成器,编码方式为: 'binary', 'hex', 或 'base64'. 如果没有指定编码方式 ,将返回 buffer。

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

  使用 other_public_key 作为第三方公钥来计算并返回共享秘密(shared secret)。秘钥用input_encoding 编码。编码方式为:'binary', 'hex', 或 'base64'。如果没有指定编码方式 ,默认为 buffer。

  如果没有指定返回编码方式,将返回 buffer。

DH算法

  DH算法是一种密钥交换协议,它可以让双方在不泄漏密钥的情况下协商出一个密钥来。DH算法基于数学原理,比如小明和小红想要协商一个密钥,可以这么做:

  1、小明先选一个素数和一个底数,例如,素数p=23,底数g=5(底数可以任选),再选择一个秘密整数a=6,计算A=g^a mod p=8,然后大声告诉小红:p=23,g=5,A=8;

  2、小红收到小明发来的p,g,A后,也选一个秘密整数b=15,然后计算B=g^b mod p=19,并大声告诉小明:B=19;

  3、小明自己计算出s=B^a mod p=2,小红也自己计算出s=A^b mod p=2,因此,最终协商的密钥s为2。

  在这个过程中,密钥2并不是小明告诉小红的,也不是小红告诉小明的,而是双方协商计算出来的。第三方只能知道p=23,g=5,A=8,B=19,由于不知道双方选的秘密整数a=6和b=15,因此无法计算出密钥2。

  用crypto模块实现DH算法如下:

var crypto = require('crypto');// xiaoming's keys:var ming = crypto.createDiffieHellman(512);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'))
Copy after login

   [注意]每次输出都不一样,因为素数的选择是随机的。

The above is the detailed content of Detailed explanation of nodeJS's crypto encryption method. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The Next Meme Coin Supercycle: Meet XYZVerse (XYZ), the Heavyweight Champion of Sports and Meme Culture The Next Meme Coin Supercycle: Meet XYZVerse (XYZ), the Heavyweight Champion of Sports and Meme Culture Nov 03, 2024 pm 09:36 PM

As excitement builds in the crypto world for the last quarter of 2024, investors are on the lookout for digital assets with the potential to deliver extraordinary returns. Insights from successful crypto figures indicate that certain tokens could exp

Get the gate.io installation package for free Get the gate.io installation package for free Feb 21, 2025 pm 08:21 PM

Gate.io is a popular cryptocurrency exchange that users can use by downloading its installation package and installing it on their devices. The steps to obtain the installation package are as follows: Visit the official website of Gate.io, click "Download", select the corresponding operating system (Windows, Mac or Linux), and download the installation package to your computer. It is recommended to temporarily disable antivirus software or firewall during installation to ensure smooth installation. After completion, the user needs to create a Gate.io account to start using it.

Crypto Influencer Cobie Burns 60% of the Supply of a Solana (SOL) Meme Coin Issued via Pump.fun Crypto Influencer Cobie Burns 60% of the Supply of a Solana (SOL) Meme Coin Issued via Pump.fun Nov 09, 2024 am 04:14 AM

Jordan Fish, known more popularly as Cobie, burned 60% of the supply of a Solana (SOL) meme coin issued via Pump.fun on Friday, Nov. 8

List of top ten exchanges in the currency circle List of top ten exchanges in the currency circle Feb 21, 2025 pm 10:18 PM

The top ten exchanges in the currency circle are ranked by trading volume: Binance Ouyihuobi FTXKrakenCoinbaseGeminiBitfinexBybitGate.io

Which of the top ten virtual currency trading apps is the best? Which of the top ten virtual currency trading apps is the most reliable Which of the top ten virtual currency trading apps is the best? Which of the top ten virtual currency trading apps is the most reliable Mar 19, 2025 pm 05:00 PM

Top 10 virtual currency trading apps rankings: 1. OKX, 2. Binance, 3. Gate.io, 4. Kraken, 5. Huobi, 6. Coinbase, 7. KuCoin, 8. Crypto.com, 9. Bitfinex, 10. Gemini. Security, liquidity, handling fees, currency selection, user interface and customer support should be considered when choosing a platform.

Login on the official entrance of Ouyi ok exchange Login on the official entrance of Ouyi ok exchange Feb 21, 2025 pm 05:33 PM

Ouyi Exchange, one of the world's leading cryptocurrency trading platforms, provides users with safe and reliable digital asset trading services. Its official portal connection can directly access the platform, making asset management, transactions and investments conveniently and efficiently. By adopting advanced technology and risk control measures, Ouyi is committed to creating a safe and stable trading environment, allowing users to trade with confidence and enjoy the convenience and benefits of the digital asset world.

Bitcoin Purchase Platform Ranking (Latest Update in 2025) Bitcoin Purchase Platform Ranking (Latest Update in 2025) Feb 21, 2025 pm 07:12 PM

In the digital asset space, Bitcoin, as a highly-anticipated cryptocurrency, has a growing demand for transactions. This article will explore the top ten Bitcoin trading platforms in the world, provide a comprehensive ranking list, and help readers choose the platform that best suits their trading needs.

Top 10 Digital Virtual Currency Trading Platforms Ranking 2025 Latest Top 10 Digital Virtual Currency Trading Platforms Ranking 2025 Latest Mar 21, 2025 pm 03:27 PM

Top 10 digital virtual currency trading platforms in 2025: 1. OKX, 2. Binance, 3. Gate.io, 4. Kraken, 5. Huobi Global, 6. Coinbase, 7. KuCoin, 8. Crypto.com, 9. Bitfinex, 10. MEXC Global. These platforms were selected as the best due to their transaction volume, user experience, security and currency richness. When choosing, transaction fees and platform security must be considered.

See all articles