使用JSEncrypt加密解密
<!-- 引入非对称 RSA 加密工具 -->
import
{ JSEncrypt } from
'jsencrypt'
// 加密公钥
const key = `----`
实际项目中 let key ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDtID8+nPhjcHtIIo+ACbcx
4ijCyNMXRZeP5dCIaYaS915lFtrwFUPPzpTwA3O
S12zQjowKh/v7ING0KhVQ66n+kI5oEUdAyqrBEY
GCoUDszQ9SRm/zb3KR1dMjKrhRLEC3Q5h7zR7QMLKYg0/Qj0tJtHXsUMjxGE6Wes9dCNKewQIDAQAB"
//
加密,msg就是需要加密的密码,通过ajax发送至后台export
function
setEncrypt (msg) {
const jsencrypt =
new
JSEncrypt()
jsencrypt.setPublicKey(key)
return
jsencrypt.encrypt(msg)
}
// 解密私钥
const privateKey = `---`
// 解密
export
function
decrypt (msg) {
let
decrypt =
new
JSEncrypt()
decrypt.setPrivateKey(privateKey)
var
decryptMsg = decrypt.decrypt(msg)
return
decryptMsg
}
(1)导入JSEncrypt插件 cnpm install jsencrypt --save (2)引入插件 全局引入和局部引入的区别:如果插件在项目的多个文件中使用建议全局引入,如果在单个文件中使用建议局部引入 //main.js全局引入并挂载 import JSEncrypt from "jsencrypt"; Vue.prototype.$jsEncrypt = JSEncrypt; 在要引入的单个文件中导入 import JSEncrypt from 'jsencrypt'; (3)代码编写 //以下代码使用全局引入方式编写; //公钥获取有两种方式:1.跟后端要密钥生成的接口 2.后端直接给你一个公钥字符串 const publicKeyStr = '公钥xxxxxxxxxxxxxxxxxxxxxxxxxx'; //创建jsencrypt加密对象 const jsRsa = new this.$jsEncrypt(); //设置公钥 jsRsa.setPublicKey(publicKeyStr); //使用加密对象给密码加密也可以对用户名等加密 let Rsapassword = jsRsa.encrypt(this.userForm.credential);
// 新建JESencrypt对象 const encryptor = new JSEncrypt() const publicKey = '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCNOM5OeBxGFRPj2jIpXv8KGrgBolN3duFBwSoDLNFfwd6atlyVM2DgbMLwWsE7zNedPlDB62/e3OzCcxZgjWaEBrnVznqdfL/vhp5RdtZ30qGZxtDraCZBu45I5rELE3wifGvyYWzWVLnA3eiLvhjga+XXvx99LAgg7uadrb1CzwIDAQAB-----END PUBLIC KEY-----' // 设置公钥 encryptor.setPublicKey(publicKey) // publicKey为公钥 // 获取当前时分秒 let time = new Date() let year = time.getFullYear() + '' let month = (time.getMonth() + 1) > 9 ? (time.getMonth() + 1) : '0' + (time.getMonth() + 1) + '' let day = time.getDate() > 9 ? time.getDate() : '0' + time.getDate() let h = time.getHours() let m = time.getMinutes() let s = time.getSeconds() let timeStr = year + month + day + ' ' + h + ':' + m + ':' + s // 使用加密对象给密码加密也可以对用户名等加密 let Rsapassword = encryptor.encrypt(`GY2PJ0N3U*P2^cYwZVVLXxDzO^j8SosI#${timeStr}`); console.log('当前时间', timeStr) console.log('getNewsDetail', Rsapassword)