SoFunction
Updated on 2025-03-10

JavaScript uses crypto module to implement encryption and decryption

1. Hash (hash) algorithm

Hash function (English: Hash function), also known as hash algorithm and hash function, is a method to create small digital "fingerprints" from any kind of data. The basic principle is to input data of any length and finally output a fixed length result.

  • The hash algorithm has the following characteristics:
  • The same input produces the same output
  • Different outputs will produce different outputs
  • Any input length is the same
  • The input value cannot be calculated from the output. Because of these characteristics of the hash algorithm, the hash algorithm is mainly used for: encryption, data verification, version identification, load balancing, and distributed (consistent hash).

1. How to get all hash algorithms

(());

2. How to use

(algorithm);//Create HASH object(data,[input_encoding]);//Add data to add the summary. You can use multiple updates before outputting the summary([encoding]);//Output summary content, after output, no summary content can be added

3. Hash algorithm example

const crypto = require('crypto');
const md5 = ('md5');//Return hashing algorithmconst md5Sum = ('hello world');//Specify the original content to be summarized. You can use multiple update methods to add the summary content before the summary is output.const result = ('hex');//Summary output, after using the digest method, you cannot append the summary content to the hash object.(result);

4. Update multiple times

var fs = require('fs');
var shasum = ('sha1');//Return sha1 hashing algorithmvar rs = ('./');
('data', function (data) {
    (data);//Specify the original content to be summarized. You can use multiple update methods to add the summary content before the summary is output.});
('end', function () {
    var result = ('hex');//Summary output, after using the digest method, you cannot append the summary content to the hash object.    (result);
})

2. HMac algorithm

The hash algorithm is also called a digest algorithm. This algorithm can convert data of any length into hash values ​​of fixed length, which is irreversible. You can convert a novel into hash data, but you can't reverse it from this hash data back to a novel. Therefore, if you want to obtain the original data of hash, you can only rely on dictionary collisions.

This algorithm is usually used more frequently when checking text and storing passwords. Although the digest algorithm is used to store passwords, strictly speaking, the digest algorithm is not considered an encryption algorithm. Here is an example of encryption using hash

const crypto = require("crypto");

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

    const hmac = (algorithm, key);
    (data);
    return ("hex");
}

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

3. Symmetric AES encryption

Check out all encryption algorithms supported by nodejs:

();

Nodejs provides the Cipher class and the Decipher class, which are used for encryption and decryption respectively. Both inherit Transfrom Stream, and the API usage methods are similar to those of hash functions.

1. How to encrypt

1. The first method

//aes encryptionencrypt (word) {
      const key = .("1234567890000000"); // Encryption key 16 bit      const iv = .("1234567890000000");  // Encryption vector      let encrypted = '';
      if (typeof(word) == 'string') {
        let srcs = .(word);
        encrypted = (srcs, key, {
          iv: iv,
          mode: ,
          padding: .Pkcs7
        });
      } else if (typeof(word) == 'object') { //Convert object format to json string        data = (word);
        let srcs = .(data);
        encrypted = (srcs, key, {
          iv: iv,
          mode: ,
          padding: .Pkcs7
        })
      }
      return ();
    }
}

The data here can be in two data formats, one is a string and the other is an object. Then we process the data and then call the AES algorithm based on the secret key and vector defined by our own definition for encryption.

2. The second method

encryption (data) {
    let strs=[];
    for(let i in data){
        (i+'='+data[i]);
    }
    ();  // Array sorting    strs=('&'); //Array change string    let endData=strs+'&sign='+CryptoJS.MD5(strs+'ADfj3kcadc2349akvm1CPFFCD84f')
    .toString(); // MD5 encryption    let key = .("0880076B18D7EE81"); // Encryption key    let iv = .("CB3EC842D7C69578");  // Vector    let encryptResult = (endData,key, {   // AES encryption        iv: iv,
        mode: ,
        padding: .Pkcs7  // The background is pad.Pkcs5, and the front desk corresponds to Pkcs7    });
    return encodeURIComponent(.());  // Base64 encryption and encode;}

First, we sort the data, then MD5 encryption is used as the interface signature, then the sorted data and interface signature are spliced ​​for AES encryption. The penultimate step is to base64 encryption the AES encrypted ciphertext, and finally the final ciphertext encodeURIComponent.

2. How to decrypt

1. The data returned in 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 = .("0880076B18D7EE81");  // Encryption key    let iv = .("CB3EC842D7C69578");   // Vector    let baseResult=.(data);   // Base64 decryption    let ciphertext=.(baseResult);     // Base64 decryption    let decryptResult = (ciphertext,key, {    // AES decryption        iv: iv,
        mode: ,
        padding: .Pkcs7
    });
// The first type    let resData=(.Utf8).toString();
    return (resData);
   // The second typereturn .(decryptResult)
}

encryption

export const encryptionData = (word)=>{
var key = .("46cc793c53dc451b");
var srcs = .(word);
var encrypted = (srcs, key, {
  mode: ,
  padding: .Pkcs7
});
return ();
}

Decryption

export const decryptData = (data)=>{
var key = .("46cc793c53dc451b");
var decrypt = (data, key, {
  mode: ,
  padding: .Pkcs7
});
return .(decrypt).toString();
}

The above is the detailed content of JavaScript using the crypto module to implement encryption and decryption. For more information about JavaScript crypto encryption and decryption, please pay attention to my other related articles!