一、引入rsa
npm install jsencrypt --save-dev
npm install encryptlong -S
二朝巫、在utils創(chuàng)建rsa.js文件
1.在rsa.js中引入
/* 產(chǎn)引入jsencrypt實現(xiàn)數(shù)據(jù)RSA加密 */
import JSEncrypt from 'jsencrypt' // 處理長文本數(shù)據(jù)時報錯 jsencrypt.js Message too long for RSA
/* 產(chǎn)引入encryptlong實現(xiàn)數(shù)據(jù)RSA加密 */
import Encrypt from 'encryptlong' // encryptlong是基于jsencrypt擴展的長文本分段加解密功能劈猿。
2.準備publicKey(公鑰)&& privateKey(私鑰)
// 公鑰key
const publicKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANL378k3RiZHWx5AfJqdH9xRNBmD9wGD\n' +
'2iRe41HdTNF8RUhNnHit5NpMNtGL0NPTSSpPjjI1kJfVorRvaQerUgkCAwEAAQ=='
// 私鑰key
const privateKey = 'MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEA0vfvyTdGJkdbHkB8\n' +
'mp0f3FE0GYP3AYPaJF7jUd1M0XxFSE2ceK3k2kw20YvQ09NJKk+OMjWQl9WitG9p\n' +
'B6tSCQIDAQABAkA2SimBrWC2/wvauBuYqjCFwLvYiRYqZKThUS3MZlebXJiLB+Ue\n' +
'/gUifAAKIg1avttUZsHBHrop4qfJCwAI0+YRAiEA+W3NK/RaXtnRqmoUUkb59zsZ\n' +
'UBLpvZgQPfj1MhyHDz0CIQDYhsAhPJ3mgS64NbUZmGWuuNKp5coY2GIj/zYDMJp6\n' +
'vQIgUueLFXv/eZ1ekgz2Oi67MNCk5jeTF2BurZqNLR3MSmUCIFT3Q6uHMtsB9Eha\n' +
'4u7hS31tj1UWE+D+ADzp59MGnoftAiBeHT7gDMuqeJHPL4b+kC+gzV4FGTfhR9q3\n' +
'tTbklZkD2A=='
3.自定義加密解密函數(shù)
export default {
/* JSEncrypt加密 */
rsaPublicData(data) {
var jsencrypt = new JSEncrypt()
jsencrypt.setPublicKey(publicKey)
// 如果是對象/數(shù)組的話揪荣,需要先JSON.stringify轉(zhuǎn)換成字符串
var result = jsencrypt.encrypt(data)
return result
},
/* JSEncrypt解密 */
rsaPrivateData(data) {
var jsencrypt = new JSEncrypt()
jsencrypt.setPrivateKey(privateKey)
// 如果是對象/數(shù)組的話,需要先JSON.stringify轉(zhuǎn)換成字符串
var result = jsencrypt.encrypt(data)
return result
},
/* 加密 */
encrypt(data) {
const PUBLIC_KEY = publicKey
var encryptor = new Encrypt()
encryptor.setPublicKey(PUBLIC_KEY)
// 如果是對象/數(shù)組的話佛舱,需要先JSON.stringify轉(zhuǎn)換成字符串
const result = encryptor.encryptLong(data)
return result
},
/* 解密 - PRIVATE_KEY - 驗證 */
decrypt(data) {
const PRIVATE_KEY = privateKey
var encryptor = new Encrypt()
encryptor.setPrivateKey(PRIVATE_KEY)
// 如果是對象/數(shù)組的話挨决,需要先JSON.stringify轉(zhuǎn)換成字符串
var result = encryptor.decryptLong(data)
return result
}
}
三、在main.js引入
import Rsa from "@/utils/rsa.js"
Vue.prototype.$Rsa = Rsa; //掛載到vue實例上
四肆捕、使用
password = this.$Rsa.rsaPublicData(password);