Common front-end encryption modes include RSA encryption, AES encryption, MD5 encryption, SHA256 encryption, and national secret

// Generate random strings
function randomString(len) {
    len = len || 16;
    const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /**** removes confusing characters oOLl,9gq,Vv,Uu,I1****/ by default
    const maxPos = $chars.length;
    let pwd = ' ';
    for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}
const aesKey = randomString(16);
Copy the code

One, AES encryption: security

  • AES encryption: symmetric encryption (one key, which is used for encryption and decryption)
  • AES is one secret at a time. Each encryption generates a new key
  • AES encryption improves packet security

1.1 Add decryption examples to ‘crypto-js’ library

  • npm: crypto-js

1.1.1 Plain Text Encryption

Encrypt ('my message', 'secret key 123').tostring (); // encrypt var ciphertext = cryptojs.aes. encrypt('my message', 'secret key 123').tostring (); // Decrypt var bytes = cryptojs.aes. decrypt(ciphertext, 'secret key 123'); var originalText = bytes.toString(CryptoJS.enc.Utf8); console.log(originalText); // 'my message'Copy the code

1.1.2 Object Encryption

var data = [{id: 1}, {id: 2}] // encrypt var ciphertext = cryptojs.aes. encrypt(json.stringify (data), 'secret key 123').tostring (); // Decrypt var bytes = cryptojs.aes. decrypt(ciphertext, 'secret key 123'); var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8)); console.log(decryptedData); // [{id: 1}, {id: 2}]Copy the code

1.2 Used in the project

// Introduce the crypto-js library
import * as CryptoJS from 'crypto-js';
import getSha256 from 'crypto-js/sha256';
Copy the code
/ * * *@param {string} data- Json.stringify (data) before sending encrypted data; *@param {string} key- Key used for encryption * CipherOption, some of the encryption options: * mode: CBC, CFB, CTR, CTRGladman, OFB, ECB, all in cryptojs. mode * padding: Pad object (Pkcs7, AnsiX923, Iso10126, Iso97971, ZeroPadding, NoPadding), all in the cryptojs.pad object * iv: The offset, mode === ECB, does not need iv * to return an encrypted object */
const key = CryptoJS.enc.Utf8.parse(aesKey);
let data = JSON.stringify(data);
const AESData = CryptoJS.AES.encrypt(data, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
});
// AESData is passed to the background
Copy the code

RSA encryption: security

  • usejsencrypt.js: is a JS library based on RSA encryption and decryption
  • RSA encryption: asymmetric encryption (with a pair of conventions and private keys, one public key for one private key)
  • The encryption principle comes from the prime factorization of large numbers
  • Encryption with a public key at the front and decryption with a private key at the back
  • AES encryption improves packet security

2.1 Used in the project

const JSEncrypt = require("jsencrypt"); // Import modules
const encrypt = new JSEncrypt.JSEncrypt(); // instantiate the encrypted objectEncrypt. SetPublicKey (public key);// Set the public key
const RSAData = encrypt.encrypt(aesKey); // The content to be encrypted
// RSAData passes to the background
Copy the code

SHA256 encryption: tamper-proof

  • Sha256 encryption, similar to MD5 encryption, converts a string according to a rule
  • The encryption process is irreversible (that is, A can be encrypted into B, but A cannot be decrypted out of B)
  • Abstract of article (tamper-proof) : Generally, SHA256 encryption or MD5 encryption is used for article summarization. That is, after the front-end uses SHA256 to encrypt the packets to be sent to the back end, the encrypted string is sent to the back end. After receiving the packets, the back end will encrypt the decrypted plaintext again with SHA256 encryption, and then compare it with the SHA256 ciphertext sent from the front end. Prove that the data has not been tampered with
// Simple string encryption
constEncryptData = cryptojs.sha256 (' string to be encrypted ').toString();Copy the code

3.1 Used in the project

import getSha256 from 'crypto-js/sha256'; 
const sha256Encrypt = getSha256(data).toString(); // data - The data to be encrypted
const encryptedHexStr = CryptoJS.enc.Hex.parse(sha256Encrypt);
const mic = CryptoJS.enc.Base64.stringify(encryptedHexStr); / / base64 encryption
// mic passes to background
Copy the code

Other encryption

4.1 ECC encryption

  • Asymmetric encryption, similar to RSA
  • There is a public key and a private key
  • The encryption principle comes from elliptic hyperbola

4.2 the MD5 encryption

  • Similar to SHA256 encryption (SHA256 is advanced version of MD5)

4.3 the secret

NPM address: sm-crypto

  • A set of encryption algorithms unique to China, including SM1, SM2, SM3 and SM4
  • SM1 – Similar to AES encryption, symmetric encryption, the algorithm is not public
  • SM2 – ECC based, asymmetric encryption
  • SM3 – similar to MD5 or SHA256 for article summaries
  • SM4 – Similar to AES encryption, symmetric encryption

Five, AES decryption

Used in the project

// Introduce the crypto-js library
import * as CryptoJS from 'crypto-js';
import getSha256 from 'crypto-js/sha256';
Copy the code
function decryption(res) {
    / * * *@param {object} res- response message response message format: * {data: 'QukvMrekoCs7xnvqVDorjD4x6YMJx52HOqYM76YSDeOdwhGEGJvRp5aUZnR, mic: 'YrPA7gr8PgqvR7MKCueWX9LB88vkhadK0Ktg='} */
    let decryptedData = CryptoJS.AES.decrypt(res.data, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    var decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8); // Clear text after decryption

    // SH256 encryption is performed on response packets
    const sha256Decode = getSha256(decryptedStr).toString();
    var encryptedHexStr = CryptoJS.enc.Hex.parse(sha256Decode);
    var sha256Result = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    
    // Compares the encrypted ciphertext between the front end and back end of the response packet. If the comparison is consistent, the data is not tampered with
    if (sha256Result === res.mic) {
        return JSON.parse(decryptedStr)
    } else {
        Toast.info('Decryption failed')}}Copy the code