Rock笔记
~/rocknotes/articles/384.md article
// article · vue

vue 中的 RSA 加密

1、安装组件

npm install  --save jsencrypt


2、引入组件

import JsEncrypt from 'jsencrypt'


3、对明文使用公钥进行加密

let publicKey = '1341343141234';// 公钥
let jse = new JsEncrypt();//新建JSEncrypt对象
jse.setPublicKey(publicKey);// 设置公钥
let token = jse.encrypt('这是需要加密的明文字符串');//加密
//如果需要直接对对象进行加密,需要先用JSON.stringify转化一次成字符再加密,否则解密不出来
let token = jse.encrypt((JSON.stringify({'id':1})));


我们可以创建方法供其他地方直接调用

// rsa公钥:加密
const rsaPublicKey = '';//写入自己的公钥
// rsa私钥:解密
const rsaPrivateKey'';//写入自己的私钥

/**
 * rsa加密
 * @param {*} word
 * @returns
 */
export function setRsa(word) {
  const jsencrypt = new JSEncrypt();
  jsencrypt.setPublicKey(rsaPublicKey);
  return jsencrypt.encrypt(word);
}
/**
 * rsa解密
 * @param {*} word
 * @returns
 */
export function getRsa(word) {
  const decrypt = new JSEncrypt();
  decrypt.setPrivateKey(rsaPrivateKey);
  return decrypt.decrypt(word);
}


但当需要加密的数据比较长时,会导致加密失败,加密返回false,如下图:

image.png

这时可以使用另一个组件:encryptlong。

安装encryptlong

npm install --save encryptlong


如果字符过长,上面的方法就解密不出来了,换一种方法 (encryptor.encryptLong) 解密

// rsa公钥:加密
const rsaPublicKey = '';//写入自己的公钥
// rsa私钥:解密
const rsaPrivateKey'';//写入自己的私钥

/* 加密 */
export function encryptLong(data) {
  var encryptor = new Encrypt();
  encryptor.setPublicKey(rsaPublicKey)
  const result = encryptor.encryptLong(data)
  return result;
}
/* 解密 - PRIVATE_KEY - 验证 */
export function decrypt(data) {
  var encryptor = new Encrypt();
  encryptor.setPrivateKey(rsaPrivateKey)
  var result = encryptor.decryptLong(data)
  return result;
}



参考:

https://blog.csdn.net/qq_32442967/article/details/101759723

https://blog.csdn.net/lovelessdream/article/details/103557600

https://www.zybuluo.com/octopus/note/1398009


回复// 0 replies

最新回复 ↓
// 暂无回复

回复功能沿用原详情页:前往原页面参与讨论 →