npm install  crypto-js

utils/aes.js

const CryptoJS = require('crypto-js');
 
// 默认的 KEY 与 iv 如果没有给
const KEY = CryptoJS.enc.Utf8.parse('KrQ4KAYOEyAz66RS'); // 十六位十六进制数作为密钥
const IV = CryptoJS.enc.Utf8.parse('ep1YCmxXuxKe4eH1'); // 十六位十六进制数作为密钥偏移量
 
/**
 * AES加密 :字符串 key iv  返回base64
 * 把默认的KEY 与 iv赋值给变量
 * 如果有keyStr 重新赋值密钥
 * 重新设置密钥偏移量
 */
function encrypted(word, keyStr, ivStr) {
  let key = KEY;
  let iv = IV;
 
  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
    iv = CryptoJS.enc.Utf8.parse(ivStr);
  }
  const srcs = CryptoJS.enc.Utf8.parse(word);
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv, // 偏移量
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}
 
// 解密
function decrypted(word, keyStr, ivStr) {
  let key = KEY;
  let iv = IV;
 
  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
    iv = CryptoJS.enc.Utf8.parse(ivStr);
  }
  const base64 = CryptoJS.enc.Base64.parse(word);
  const src = CryptoJS.enc.Base64.stringify(base64);
  const decrypted = CryptoJS.AES.decrypt(src, key, {
    iv, // 偏移量
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  });
 
  const decryptedStr = decrypted.toString(CryptoJS.enc.Utf8);
  return decryptedStr.toString();
}
module.exports = {
  encrypted,
  decrypted
};

页面应用

var aes = require('../../utils/aes.js');

数据加密:

var encrypt = aes.encrypted(Date.now()+'@'+app.globalData.id+'@'+'booking');

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐