安装依赖
cnpm install jsencrypt --save-dev
页面引入
import JSEncrypt from 'jsencrypt'
//加密
1 //str 未加密字符串 2 export function getEncryCode(str) { 3 //实例化JSEncrypt 4 let jse = new JSEncrypt(); 5 //加密公钥(由服务端生成) 6 let pubKey = `-----BEGIN PUBLIC KEY----- 7 MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCuJEc8NP 8 4IVWZUqpJpmNvl90rUrNE8PfqvjQ8NOzEGh7OlFlxtsSzDVhPEKW 9 6aOs/+elMol96SbCzD8l7HFOha0mQ07UCgx8Gb 10 -----END PUBLIC KEY-----` 11 12 jse.setPublicKey(pubKey); 13 let data = jse.encrypt(str.toString()); // 进行加密 14 return data; 15 }
//解密
1 //params 待解密字符串 2 export function sendEncryCode(params) { 3 //实例化JSEncrypt 4 let jse = new JSEncrypt(); 5 //使用前端私钥解密(私钥由服务端生成) 6 let privKey = `-----BEGIN PRIVATE KEY-----MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAK4kRzw0/ghV 7 KzCoClilgqx0MfTfLU113n1eQmiiJTGvHIjqvzD533o/WFMEvPv3M2pyCz/IMkSavKwCVAh2/TBjJM0ECQQDz3uyxyWS3Xj3o9XDi 8 UpWy/JwE9PyMj5dSxiNbpBatfMrrHkMpfqsVWAQgsuRkj12ROsYo2x5tAGjZvGvV94eHAkEAts2H4nEwVfVpDESPhOdPZD/fqR6 9 UO/ThwCK2vOj1ShcIZSvuCSlFZDqq39Qk/PZQdAmUHril+nVf4Ohs3/QvMQJAeM9Mjl5oaHZlUQyV2Wh0BHEjkUkT+0X+/uBtD6 10 7gFR2nIIajWuEHO9GYaeJ1RmPHRHTLSd4S2ojDaGnxOdQf7QJBAIFOhW5CDqTfQX1yCetDC7+oBvfEL6rxn7afV4/tYYUVIdU 11 e6/QDA5jQfwpxL/DX8zUBiYrppk6yNC4NeuY3/iECQE0BBsDeCJRbrJPl3F8xX8+dam6rclzPrT5A6Ux0dPABtr2qHKSl/M6fkMrR2r 12 P3YOmfsXmQW/VmUb5Q6OTYOwo= 13 -----END PRIVATE KEY-----` 14 15 jse.setPrivateKey(privKey); 16 let data = jse.decrypt(params); //解密 17 18 return data; 19 }
//使用方法
let ddata = getEncryCode( JSON.stringify({ keyword: "lalala", userId: "111111111", versionnum: "333", devicetype: "3" }) ); console.log(ddata); let dds = JSON.parse(sendEncryCode(ddata)); console.log(dds);