js usa crypto-js para cifrar y descifrar

Primero instale crypto-js

npm install crypto-js

Insertar descripción de la imagen aquí

El siguiente es el código completo: primero, se introducen AES y enc en crypto-js, y se declaran los métodos de cifrado y descifrado para realizar pruebas.

let { AES, enc } = require("crypto-js");

// 加密方法
function encryptString(str, key) {
  // 使用 AES 加密算法,将字符串转为字节数组
  const ciphertext = AES.encrypt(str, key).toString();
  // 将字节数组转为 Base64 编码的字符串
  const base64Ciphertext = enc.Base64.stringify(enc.Utf8.parse(ciphertext));
  return base64Ciphertext;
}
// 解密方法
function decryptString(ciphertext, key) {
  // 将 Base64 编码的字符串解码成字节数组
  const bytes = enc.Base64.parse(ciphertext);
  // 将字节数组转为 AES 加密后的数据
  const decryptedData = AES.decrypt(bytes.toString(enc.Utf8), key);
  // 将解密后的数据转为字符串
  const plaintext = decryptedData.toString(enc.Utf8);
  return plaintext;
}

const key = "qweasdzxc"; // 秘钥
const encryptionStr = "爱老虎油"; // 需要加密的字符串

let a1 = encryptString(encryptionStr, key);
console.log("加密后的字符串", a1);
let a2 = decryptString(a1, key);
console.log("解密后的字符串", a2);

Insertar descripción de la imagen aquí
Insertar descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/sywdebug/article/details/132763270
Recomendado
Clasificación