The Crypto module provides encryption capabilities, including a complete package of OpenSSL’s hashing, HMAC, encryption, decryption, signature, and authentication capabilities.

One, hash (hash) algorithm

A Hash function is a method of creating small digital “fingerprints” from any kind of data. The basic idea is to input data of arbitrary length and output results of fixed length.

  • The hash algorithm has the following features:
  • The same input produces the same output
  • Different outputs produce different outputs
  • Any input length is the same as the output length
  • The input value cannot be deduced from the output

Due to these features, the hash algorithm is mainly used for encryption, data verification, version identification, load balancing, and distribution (consistent hash).

1. How to obtain all hashing algorithms

console.log(crypto.getHashes());
Copy the code

2. Use method

crypto.createHash(algorithm);// Create a HASH object
hash.update(data,[input_encoding]);// Update the data to be abstracted. You can use the update multiple times before the digest output
hash.digest([encoding]);// Output the summary content, after the output can not add the summary content
Copy the code

3. Hashing algorithm example

const crypto = require('crypto');
const md5 = crypto.createHash('md5');// Return hash algorithm
const md5Sum = md5.update('hello world');// Specify the original content to be digested. You can use the update method to add the digest multiple times before the digest is printed
const result = md5Sum.digest('hex');// Digest output. No digest can be appented to the hash object after the digest method is used.
console.log(result);
Copy the code

4. Update multiple times

var fs = require('fs');
var shasum = crypto.createHash('sha1');// Return sha1 hash algorithm
var rs = fs.createReadStream('./readme.txt');
rs.on('data'.function (data) {
    shasum.update(data);// Specify the original content to be digested. You can use the update method to add the digest multiple times before the digest is printed
});
rs.on('end'.function () {
    var result = shasum.digest('hex');// Digest output. No digest can be appented to the hash object after the digest method is used.
    console.log(result);
})

Copy the code

Two, HMac algorithm

The hash algorithm, also known as the digest algorithm, can convert data of any length into a fixed length hash value. This method is irreversibly. You can convert a novel to hash data, but you can’t reverse the hash data back to a novel. Therefore, the only way to get the raw data of the hash is by dictionary collision.

This algorithm is often used in text verification and password storage. Although the digest algorithm is used for the storage of passwords, it is not strictly an encryption algorithm. Here is an example of hash encryption

const crypto = require("crypto");

function encryptData(data, key, algorithm) {
    if(! crypto.getHashes().includes(algorithm)) {throw new Error("This hash function is not supported.");
    }

    const hmac = crypto.createHmac(algorithm, key);
    hmac.update(data);
    return hmac.digest("hex");
}

// output: 30267bcf2a476abaa9b9a87dd39a1f8d6906d1180451abdcb8145b384b9f76a5
console.log(encryptData("root"."7(23y*&745^%I"."sha256"));

Copy the code

Three, symmetric AES encryption

View all the encryption algorithms supported by Nodejs:

crypto.getCiphers();
Copy the code

Nodejs provides the Cipher and Decipher classes for encryption and decryption, respectively. Both inherit from Transfrom Stream and use the API in a similar way to the hash function.

1. How to encrypt

1. The first method

/ / aes encryption
encrypt (word) {
      const key = CryptoJS.enc.Utf8.parse("1234567890000000"); // Add 16 bits to the secret key
      const iv = CryptoJS.enc.Utf8.parse("1234567890000000");  // Encryption vector
      let encrypted = ' ';
      if (typeof(word) == 'string') {
        let srcs = CryptoJS.enc.Utf8.parse(word);
        encrypted = CryptoJS.AES.encrypt(srcs, key, {
          iv: iv,
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7
        });
      } else if (typeof(word) == 'object') { // Convert object format to JSON string
        data = JSON.stringify(word);
        let srcs = CryptoJS.enc.Utf8.parse(data);
        encrypted = CryptoJS.AES.encrypt(srcs, key, {
          iv: iv,
          mode: CryptoJS.mode.CBC,
          padding: CryptoJS.pad.Pkcs7
        })
      }
      returnencrypted.ciphertext.toString(); }},Copy the code

The data here can be in one of two data formats, a string or an object. Then we process the data and then call the AES algorithm to encrypt it based on the secret keys and vectors that we define.

2. The second method

encryption (data) {
    let strs=[];
    for(let i in data){
        strs.push(i+'='+data[i]);
    }
    strs.sort();  // Array sort
    strs=strs.join('&'); // Array variable string
    let endData=strs+'&sign='+CryptoJS.MD5(strs+'ADfj3kcadc2349akvm1CPFFCD84f')
    .toString(); / / the MD5 encryption
    let key = CryptoJS.enc.Utf8.parse("0880076B18D7EE81"); // Add the secret key
    let iv = CryptoJS.enc.Utf8.parse("CB3EC842D7C69578");  / / vector
    let encryptResult = CryptoJS.AES.encrypt(endData,key, {   / / AES encryption
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7  Pkcs5 is used in the background and Pkcs7 is used in the foreground
    });
    return encodeURIComponent(CryptoJS.enc.Base64.stringify(encryptResult.ciphertext));  // Base64 encrypt and encode;
}
Copy the code

First, we sort the data, then encrypt the sorted data with MD5 as the signature of the interface, and then splice the sorted data and the interface signature for AES encryption. In the penultimate step, the CIphertext encrypted by AES is encrypted with Base64, and finally the final ciphertext encodeURIComponent is encrypted.

2, how to decrypt

1. The data returned from the background is also ciphertext

2. The data returned in the background is in JSON format

The code is as follows:

decryption(data) {
    let key = CryptoJS.enc.Utf8.parse("0880076B18D7EE81");  // Add the secret key
    let iv = CryptoJS.enc.Utf8.parse("CB3EC842D7C69578");   / / vector
    let baseResult=CryptoJS.enc.Base64.parse(data);   / / Base64 decryption
    let ciphertext=CryptoJS.enc.Base64.stringify(baseResult);     / / Base64 decryption
    let decryptResult = CryptoJS.AES.decrypt(ciphertext,key, {    / / AES decryption
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7 });/ / the first
    let resData=decryptResult.toString(CryptoJS.enc.Utf8).toString();
    return JSON.parse(resData);
   / / the second
  return CryptoJS.enc.Utf8.stringify(decryptResult)
}
Copy the code

encryption

export const encryptionData = (word) = >{
var key = CryptoJS.enc.Utf8.parse("46cc793c53dc451b");
var srcs = CryptoJS.enc.Utf8.parse(word);
var encrypted = CryptoJS.AES.encrypt(srcs, key, {
  mode: CryptoJS.mode.ECB,
  padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString();
}

Copy the code

decryption

export const decryptData = (data) = >{
var key = CryptoJS.enc.Utf8.parse("46cc793c53dc451b");
var decrypt = CryptoJS.AES.decrypt(data, key, {
  mode: CryptoJS.mode.ECB,
  padding: CryptoJS.pad.Pkcs7
});
return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
Copy the code