jsencrypt前端加密和解密

1,181 阅读1分钟

// 密钥对生成在线地址 web.chacuo.net/netrsakeypa… const publicKey = '', //生成的公钥 const privateKey='', // 私钥

// 获取公钥字符串

export function getPubKey(data) {
  return http({
    url: "/publicKey", //根据项目接口修改
    method: "GET", // 同理
    data
  });
}

// 在前端使用接口 import { JSEncrypt } from "jsencrypt"; import { getPubKey } from "@/api"; //每个项目路径都会有区别

 getPubKey().then(({ result, data: keyData }) => { // getPubKey---获取公钥接口
        if (result) {
          const jse = new JSEncrypt(); // 实例化一个 jsEncrypt 对象
          jse.setPublicKey(keyData); //配置公钥
          let userAccount = jse.encrypt(this.loginForm.user); //加密账号
          let passWord = jse.encrypt(this.loginForm.password); //加密密码
          login({
            userAccount: userAccount,
            passWord: passWord,
          }).then(({ result, message }) => {
            if (result) {
              console.log("登录成功");
              // 登录成功后的操作
            } else {
              // 登录失败操作
              this.loginTextError = message;
            }
          });
        }
      });

// 前端加密

export function encrypt(password) {
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey) // 设置公钥
  return encryptor.encrypt(password) // 对登录密码数据进行加密
}

// 解密

export function decrypt(password) {
  const encryptor = new JSEncrypt()
  encryptor.setPrivateKey(privateKey) // 设置私钥
  return encryptor.decrypt(password) // 对登录密码数据进行解密
}

1.先安装和导入 yarn add jsencrypt -D 在vue模板中导入 import { JSEncrypt } from "jsencrypt";

  1. 加密
encryptPassWord(){
    const encrypt = new JSEncrypt();
    // 设置公钥
    //设置公钥
      encrypt.setPublicKey(
      "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIyqtTY0UZG+ddfJ9jGQpxriHOTLwgyEyZeCVEOfNYC0dqVs1mDP1oAmxwoduWUQk/ZnxcFlXvspuD4Gd0ILSpECAwEAAQ=="
      );
    return encrypt.encrypt(this.login_data.pass_word); // login_data表单对象
}