Front-end AES encryption details and source code

Foreword: Some sensitive information needs to be encrypted when the front end acquires or submits some data. For example, a bug was encountered recently. The test modified the user's level field when logging in, so that the page under the authority of other users can be seen.

There are two modes of AES encryption: ECB mode and CBC mode, the same mode needs to be used as agreed with the backend

First, introduce the js encryption algorithm class library

npm i crypto-js --save

ECB mode:

key is the key, which needs to be consistent with the backend agreement

const CryptoJS = require("crypto-js"); //引用AES源码js
//  加密方法
export function Encrypt(word) {
  let key = CryptoJS.enc.Utf8.parse("1234567891234567");  //16位数作为密钥
  let srcs = CryptoJS.enc.Utf8.parse(word);
  let encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.toString();
}

//  解密方法
export function Decrypt(word) {
  let key = CryptoJS.enc.Utf8.parse("1234567891234567");//16位数作为密钥
  let decrypt = CryptoJS.AES.decrypt(word, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

CBC mode:

key is the key, which needs to be consistent with the backend agreement, and iv is the key offset

const CryptoJS = require('crypto-js');  //引用AES源码js   
//解密方法
export function Decrypt(word) {
    const key = CryptoJS.enc.Utf8.parse("abcd1234abcd1234");  //16位数作为密钥
    const iv = CryptoJS.enc.Utf8.parse('ABCD1234ABCD1234');   //16位数作为密钥偏移量
    let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
    let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    let decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
    let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}

//加密方法
export function Encrypt(word) {
    const key = CryptoJS.enc.Utf8.parse("abcd1234abcd1234");  //16位数作为密钥
    const iv = CryptoJS.enc.Utf8.parse('ABCD1234ABCD1234');   //16位数作为密钥偏移量
    let srcs = CryptoJS.enc.Utf8.parse(word);
    let encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
    return encrypted.ciphertext.toString().toUpperCase();
}

Guess you like

Origin blog.csdn.net/wzy_PROTEIN/article/details/129663759