1.Base64加密
//安装依赖
npm install --save base-64
//引入依赖
import Base64 from 'base-64';
//加密
Base64.encode(JSON.stringify(values));//加密
//解密
Base64.decode(JSON.parse(values));//解密
2.Rsa、Aes混合加密
//安装依赖
npm install jsencrypt
//引入依赖
import JSEncrypt from 'jsencrypt'
//引入公共方法
import {RsaEncrypt,RsaDecrypt,AesEncrypt,AesDecrypt,randomString} from '@/utils/rsa';
//加密过程
let randomStr = randomString(16)
let body = {
"requestData": AesEncrypt(JSON.stringify(values),randomStr),
"encrypted": RsaEncrypt(randomStr)
}
//解密过程
let key = RsaDecrypt(encrypted)
let datas = JSON.parse(AesDecrypt(requestData,key))
新建页面,加解密公共方法
//加解密 公共方法
const CryptoJS = require('crypto-js');
import JsEncrypt from 'jsencrypt'
//Aes加密方法
export function AesEncrypt(word, keyStr){
var key = CryptoJS.enc.Utf8.parse(keyStr);//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
var srcs = CryptoJS.enc.Utf8.parse(word);
var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
return encrypted.toString();
}
//Aes解密方法
export function AesDecrypt(word, keyStr){
var key = CryptoJS.enc.Utf8.parse(keyStr);//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
var decrypt = CryptoJS.AES.decrypt(word, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
//Rsa加密方法
export function RsaEncrypt(word){
let pubKey = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkuoiZut4NqmpIvap2e2mLHT4TkOSsUQZ8irHxEFaAL3GskYzrXmYzZolG+9Mk3C3hvUqTBf4YuNxV6RxLo4lxo9tapdktm0F2eqvG3ZKWdnOe4y0DkpYQrL/LxlhnXIjJgPfWj7UtWKSksMkEtrCQUj+9E2fBOfGisJoGWjKKOwIDAQAB
-----END PUBLIC KEY-----`;
var en = new JSEncrypt();
en.setPublicKey(pubKey);
return en.encrypt(word)
}
//Rsa解密方法
export function RsaDecrypt(word){
let priKey = `-----BEGIN RSA PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKS6iJm63g2qaki9qnZ7aYsdPhOQ5KxRBnyKsfEQVoAvcayRjOteZjNmiUb70yTcLeG9SpMF/hi43FXpHEujiXGj21ql2S2bQXZ6q8bdkpZ2c57jLQOSlhCsv8vGWGdciMmA99aPtS1YpKSwyQS2sJBSP70TZ8E58aKwmgZaMoo7AgMBAAECgYBD8WgcODYUXuC9pfUkL1zl8ybCfTXEWRsazT39luaGsorpSZNdFS+ELdubOozpHCOUgzW6FHOskLrYeHCiRg6O9dOkIWO2TqIsQWJLYUR34CTTKCKNNRu6No4Qm5xdde7bDczMBohofWhIsD8E/yNyzBaZniWyd9yurAMrtqgb8QJBANziXxQ9bJTNQPJEC/wFOtfEeW14at8vCluaxeVv2p2EfhRknWBqNG7MXMgEpnWUdp8hmyMaOoOHmRi0mBEij0kCQQC+6rhpk+CY0VDSZNMjskN0XOQpCyxtMouEtZ5gmdHoPUUZ3DcKj83yckDNIAgqPlZVu9cE45Kcn9NR93wAHxljAkBIqJZKHCJ5mEMC7mtazYWbsF+ZKQFOxTSNCY6LeI3bPtgScT5rlsQEpmjmytDO4LVchzt3Aou49IPh4pYbHNkxAkB0MglBAKaOe76z/nde320ckjivHkTQxRWTFLKq2pOdxESdQ6EgRXuz1oPIFHnDtCL5lRR9vkAKIWANIBIRRNw/AkEAoMDjGllrUniDthx8Kl69jF3LrOCGrPYqNrsycAJSI7HZwTX4w/u7d/xMSqBZ1fwHQH7LcVEjG1cXI9M/2PEIrQ==
-----END RSA PRIVATE KEY-----`;
var en = new JSEncrypt();
en.setPrivateKey(priKey);
return en.decrypt(word)
}
//获取随机字符串
export function randomString(e) {
e = e || 32;
var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
a = t.length,
n = "";
for (var i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
return n
}