Nodejs's crypto encryption

Source: Internet
Author: User
Tags base64 cast5 hmac ming openssl version sha1

Previous words

Cryptographic modules provide a way to encapsulate security credentials during an HTTP or HTTPS connection. It also provides encapsulation of OpenSSL's hash, HMAC, encryption (cipher), decryption (decipher), signature (sign), and authentication (verify) methods. This article describes the encryption crypto in detail

Crypto

"Crypto.setengine (engine[, flags])"

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

The engine may be an ID, or a path to a shared library of engines.

Flags is an optional parameter, and 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_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 the supported cryptographic algorithms an array group

varCrypto = require (' crypto ')); Console.log (Crypto.getciphers ());[' AES-128-CBC ', ' aes-128-ccm ', ' aes-128-cfb ', ' aes-128-cfb1 ', ' aes-128-cfb8 ', ' aes-128-ctr ', ' AES-128-ECB ', ' AES -128-gcm ', ' aes-128-ofb ', ' aes-128-xts ', ' AES-192-CBC ', ' aes-192-ccm ', ' aes-192-cfb ', ' aes-192-cfb1 ', ' aes-192-cfb8 ', ' aes-192-ctr ', ' AES-192-ECB ', ' aes-192-gcm ', ' aes-192-ofb ', ' AES-256-CBC ', ' aes-256-ccm ', ' aes-256-cfb ', ' aes-2 ' 56-cfb1 ', ' aes-256-cfb8 ', ' aes-256-ctr ', ' AES-256-ECB ', ' aes-256-gcm ', ' aes-256-ofb ', ' aes-256-xts ', ' aes128 ', ' AE s192 ', ' aes256 ', ' bf ', ' BF-CBC ', ' bf-cfb ', ' BF-ECB ', ' bf-ofb ', ' blowfish ', ' CAMELLIA-128-CBC ', ' CAMELLIA-128-CFB ' , ' camellia-128-cfb1 ', ' camellia-128-cfb8 ', ' CAMELLIA-128-ECB ', ' camellia-128-ofb ', ' CAMELLIA-192-CBC ', ' camellia-19 2-CFB ', ' camellia-192-cfb1 ', ' camellia-192-cfb8 ', ' CAMELLIA-192-ECB ', ' camellia-192-ofb ', ' CAMELLIA-256-CBC ', ' Camel LIA-256-CFB ', ' camellia-256-cfb1 ', ' camellia-256-cfb8 ', ' CAMELLIA-256-ECB ', ' camellia-256-ofb ', ' camellia128 ', ' came ' llia192 ', ' camellia256 ', ' cast ', ' CAST-CBC ', ' CAST5-CBC ', ' cast5-cfb ', ' CAST5-ECB ', ' cast5-ofb ', ' des ', ' des-cbc ', ' des-cfb ', ' DES-CFB1 ' ', ' des-cfb8 ', ' DES-ECB ', ' des-ede ', ' DES-EDE-CBC ', ' des-ede-cfb ', ' des-ede-ofb ', ' des-ede3 ', ' des-ede3-cbc ', ' de S-EDE3-CFB ', ' des-ede3-cfb1 ', ' des-ede3-cfb8 ', ' des-ede3-ofb ', ' des-ofb ', ' des3 ', ' desx ', ' DESX-CBC ', ' id-aes128-c ' CM ', ' id-aes128-gcm ', ' id-aes128-wrap ', ' id-aes192-ccm ', ' id-aes192-gcm ', ' id-aes192-wrap ', ' id-aes256-ccm ', ' id-ae S256-gcm ', ' id-aes256-wrap ', ' id-smime-alg-cms3deswrap ', ' idea ', ' IDEA-CBC ', ' idea-cfb ', ' IDEA-ECB ', ' idea-ofb ',. .. More items]

"Crypto.getciphers ()"

Returns a supported hash algorithm for the An array group.

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 the supported Elliptic curve an array group.

varCrypto = require (' crypto ')); Console.log (Crypto.getcurves ());//[' oakley-ec2n-3 ', ' oakley-ec2n-4 ', ' brainpoolp160r1 ', ' brainpoolp160t1 ', ' brainpoolp192r1 ', ' brainpoolp192t1 ', ' bra ' Inpoolp224r1 ', ' brainpoolp224t1 ', ' brainpoolp256r1 ', ' brainpoolp256t1 ', ' brainpoolp320r1 ', ' brainpoolp320t1 ', ' brain ' Poolp384r1 ', ' brainpoolp384t1 ', ' brainpoolp512r1 ', ' brainpoolp512t1 ', ' c2pnb163v1 ', ' c2pnb163v2 ', ' c2pnb163v3 ', ' C2 Pnb176v1 ', ' c2pnb208w1 ', ' c2pnb272w1 ', ' c2pnb304w1 ', ' c2pnb368w1 ', ' c2tnb191v1 ', ' c2tnb191v2 ', ' c2tnb191v3 ', ' c2tn ' B239v1 ', ' c2tnb239v2 ', ' c2tnb239v3 ', ' c2tnb359v1 ', ' c2tnb431r1 ', ' prime192v1 ', ' prime192v2 ', ' prime192v3 ', ' prime2 '  39v1 ', ' prime239v2 ', ' prime239v3 ', ' prime256v1 ', ' secp112r1 ', ' secp112r2 ', ' secp128r1 ', ' secp128r2 ', ' secp160k1 ', ' Secp160r1 ', ' secp160r2 ', ' secp192k1 ', ' secp224k1 ', ' secp224r1 ', ' secp256k1 ', ' secp384r1 ', ' secp521r1 ', ' sect113r ' 1 ', ' sect113r2 ', ' sect131r1 ', ' sect131r2 ', ' sect163k1 ', ' sect163r1 ', ' sect163r2 ', ' sect193r1 ', ' sect193r2 ', ' sect 233k1 ', ' 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 common hashing algorithm 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 digest.

The parameter algorithm depends on the algorithm supported by the OpenSSL version 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, encoded according to input_encoding, with ' 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])"

Computes a hash summary of the incoming data. Encoding can be ' hex ', ' binary ' or ' base64 ', and if no encoding is specified, the buffer will be returned.

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

var crypto = require (' crypto '); var hash = Crypto.createhash (' MD5 '); // update () can be called any number of times ():hash.update (' Hello, world! ' ); Hash.update (' Hello, nodejs! ' ); Console.log (Hash.digest (//  7e1977739c748beac0c0fd14fd26a544

Hmac

The HMAC algorithm is also a hashing algorithm that can take advantage of hashing algorithms such as MD5 or SHA1. The difference is that the HMAC also requires a key:

"Crypto.createhmac (algorithm, key)"

Creates and returns an HMAC object that generates an HMAC map with the specified algorithm and secret key.

It is a read-write streaming stream. Writes the data to use to compute the HMAC. When the write stream finishes, use the Read () method to get the computed 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 previous CreateHash. Key is the key used in the HMAC algorithm

"Hmac.update (data)"

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

"Hmac.digest ([encoding])"

Computes the HMAC value of the incoming data. Encoding can be ' hex ', ' binary ' or ' base64 ', and if no encoding is specified, the 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! ' ); // e82a58066cae2fae4f44e58be1d589b66a5d102c2e8846d796607f02a88c1649

Aes

AES is a common symmetric encryption algorithm that uses the same key for encryption and decryption. The Crypto module provides AES support, but needs to encapsulate its own functions for ease of use:

"Crypto.createcipher (algorithm, password)"

Uses the incoming algorithm and secret key to generate and return the encrypted object.

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

It is a read-write streaming stream. Writes the data to use to compute the HMAC. When the write stream finishes, use the Read () method to get the computed value. The old update and digest methods are also supported.

"Cipher.update (data[, input_encoding][, output_encoding])"

According to data to update the hash content, encoding according to Input_encoding, there is ' 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 encoded format of the output encrypted data, which can be used as ' binary ', ' base64 ' or ' hex '. If no encoding is provided, buffer is returned.

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

"Cipher.final ([output_encoding])"

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

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

varCrypto = require (' crypto '));functionaesencrypt (data, key) {Const cipher= Crypto.createcipher (' aes192 ', key); varcrypted = cipher.update (data, ' UTF8 ', ' hex ')); Crypted+ = cipher.final (' hex ')); returncrypted;}vardata = ' Hello, this is a secret message! ';varKey = ' password! ';varencrypted =aesencrypt (data, key);//8a944d97bdabc157a5b7a40cb180e713f901d2eb454220d6aaa1984831e17231f87799ef334e3825123658c80e0e5d0cConsole.log (encrypted);

"Crypto.createdecipher (algorithm, password)"

Creates and returns a decrypted object based on the algorithm and key passed in. This is the mirror of the Createcipher ()

"Decipher.update (data[, input_encoding][, output_encoding])"

Use the parameter data to update the content that needs to be decrypted, which is encoded in ' 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 either ' binary ', ' ascii ' or ' UTF8 '. If no encoding format is provided, the buffer is returned.

"Decipher.final ([output_encoding])"

Returns the remaining decrypted content, the parameter output_encoding is ' binary ', ' ascii ' or ' UTF8 ', and returns buffer if no encoding is specified.

[Note that the]decipher object cannot be used after the final () method.)

varCrypto = require (' crypto '));functionAesdecrypt (encrypted, key) {Const Decipher= Crypto.createdecipher (' aes192 ', key); vardecrypted = Decipher.update (encrypted, ' hex ', ' UTF8 '); Decrypted+ = decipher.final (' UTF8 '); returndecrypted;}vardata = ' Hello, this is a secret message! ';varKey = ' password! ';varencrypted = ' 8a944d97bdabc157a5b7a40cb180e713f901d2eb454220d6aaa1984831e17231f87799ef334e3825123658c80e0e5d0c ';vardecrypted =Aesdecrypt (encrypted, key); Console.log (decrypted);//Hello, this is a secret message!

As you can see, the encrypted string gets the original content by decrypting it.

Note that AES has a number of different algorithms, such as,, and aes192 aes-128-ecb aes-256-cbc so on, AES can also specify IV (Initial Vector) In addition to the key, different systems as long as the IV different, with the same key to encrypt the same data obtained by the encryption results are also different. There are usually two ways to express encryption results: Hex and Base64, these functions Nodejs all support, but in the application should note that if the two sides of the decryption side with Nodejs, the other side with Java, PHP and other languages, need to carefully test. If the decryption is not correct, to confirm whether the two sides follow the same AES algorithm, the string key and IV are the same, the encrypted data is unified in hex or base64 format

"Crypto.createcipheriv (algorithm, key, IV)"

Creates and returns an encrypted object, using the specified algorithm, key and IV.

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

The key and IV must be ' binary ' encoded strings or buffers.

"Crypto.createdecipheriv (algorithm, key, IV)"

Creates and returns a decrypted object based on the incoming algorithm, key, and IV. This is the mirror of the Createcipheriv ().

Const CRYPTO = require (' crypto ');functionaesencryptiv (data, KEY,IV) {Const cipher= Crypto.createcipher (' aes192 ', key, IV); varcrypted = cipher.update (data, ' UTF8 ', ' hex ')); Crypted+ = cipher.final (' hex ')); returncrypted;}functionAesdecryptiv (encrypted, KEY,IV) {const decipher= Crypto.createdecipher (' aes192 ', key, IV); vardecrypted = Decipher.update (encrypted, ' hex ', ' UTF8 '); Decrypted+ = decipher.final (' UTF8 '); returndecrypted;}vardata = ' Hello, this is a secret message! ';varKey = ' password! ';variv = ' Match ';varencrypted =aesencryptiv (data, key, iv);vardecrypted =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);

Diffie-hellman

"Crypto.creatediffiehellman (prime[, prime_encoding][, generator][, generator_encoding])"

Creates a Diffie-hellman key interaction object using the incoming prime and generator.

Generator can be a number, a string, or a buffer. If generator is not specified, use 2

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

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

"Diffiehellman.generatekeys ([encoding])"

Generates a 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 encoded method indicated by the parameter encoding, encoded as: ' binary ', ' hex ', or ' base64 '. If no encoding is specified, buffer is returned.

"Diffiehellman.getgenerator ([encoding])"

The Diffie-hellman generator is returned with the encoded method indicated by the parameter encoding, encoded as: ' 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 (Gkfx secret). The secret key is encoded with input_encoding. The encoding 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

The DH algorithm is a key exchange protocol that allows both parties to negotiate a key without leaking the key. The DH algorithm is based on mathematical principles, such as Xiao Ming and Xiao Hong want to negotiate a key, you can do this:

1, Xiao Ming first select a prime and a base, for example, Prime p=23, base g=5 (base can be optional), and then select a secret Integer a=6, calculate a=g^a mod p=8, and then loudly tell Xiao Red: p=23,g=5,a=8;

2, small red received Xiao Ming sent P,g,a, also choose a secret integer b=15, and then calculate B=g^b mod p=19, and loudly told Xiaoming: b=19;

3, Xiao Ming himself calculated s=b^a mod p=2, small red also calculate s=a^b mod p=2, therefore, the final negotiated key S is 2.

In this process, the key 2 is not Xiao Ming told Xiao Red, also not Little Red told Xiaoming, but the two sides negotiated calculated. Third parties can only know p=23,g=5,a=8,b=19, because they do not know the two sides selected secret integer a=6 and b=15, therefore cannot calculate the key 2.

The DH algorithm is implemented using the Crypto module as follows:

varCrypto = require (' crypto '));//xiaoming ' s keys:varming = Crypto.creatediffiehellman (512);varMing_keys =Ming.generatekeys ();varPrime =ming.getprime ();varGenerator =ming.getgenerator ();//Prime: 8df777257625c66821af697652f28e93af05b9f779af919111b89816faa11c36fcf9df04c76811471a6099800213c4fe8e3fbec8d2f90bd00795e4b7f d241603Console.log (' Prime: ' + prime.tostring (' hex ')));//generator:02Console.log (' Generator: ' + generator.tostring (' hex ')));//Xiaohong ' s keys:varHong =Crypto.creatediffiehellman (Prime, generator);varHong_keys =Hong.generatekeys ();//exchange and generate secret:varMing_secret =Ming.computesecret (Hong_keys);varHong_secret =Hong.computesecret (Ming_keys);//Secret of Xiao Ming: 4237157ab4c9211f78ffdb67d127d749cec91780d594b81a7e75f1fb591fecb84f33ae6591e1edda4bc9685b503010fe8f9928c6ed69e4ff9fdb44adb 9ba1539Console.log (' Secret of Xiao Ming: ' + ming_secret.tostring (' hex ')));//Secret of Xiao Hong: 4237157ab4c9211f78ffdb67d127d749cec91780d594b81a7e75f1fb591fecb84f33ae6591e1edda4bc9685b503010fe8f9928c6ed69e4ff9fdb44adb 9ba1539Console.log (' Secret of Xiao Hong: ' + hong_secret.tostring (' hex '))

[note] Each output is different, because the prime number selection is random.

Nodejs's crypto encryption

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.