一、安装jsencrypt
1 npm i jsencrypt
node_modules文件夹中出现jsencrypt
二、引入jsencrypt
在main.js中import:
1 import JsEncrypt from ‘jsencrypt‘
2 Vue.prototype.$jsEncrypt = JsEncrypt
三、生成公钥和私钥(服务端生成)
1 // 私钥
2 openssl genrsa -out rsa_1024_priv.pem 1024
3 // cat rsa_1024_priv.pem 读取私钥内容
4 // 公钥
5 openssl rsa -pubout -in rsa_1024_priv.pem -out rsa_1024_pub.pem
6 // cat rsa_1024_pub.pem 读取公钥内容
四、JSEncrypt实例化(此部分可做成工具类,供项目中各模块使用)
1 // 实例化一个JSEncrypt对象
2 let jse = new this.$jsEncrypt.JSEncrypt()
3 jse.setPublicKey(`-----BEGIN PUBLIC KEY-----
4 MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC8ygMKjJLSUpnfXqt8lRSAdDxA
5 HWKi9GbTFkCbAjkRCR6VUakxxXLXHQUtPCizKcvNpuYqZ5bO8LEgpY7SL3JEdEI9
6 OuMnZ6ToeHPfcHeS+EgN0oYmdQ49RB5wZkcBEFk80OBEAM6VhnE0IuHGkU5ko9oP
7 Hq3boEQ3Ej6r3T+UhQIDAQAB
8 -----END PUBLIC KEY-----`)
五、加解密(公钥加密,私钥解密)
1 // 设置需要加密的字符串
2 let encrypted = jse.encrypt(‘Hello, world‘)
3 // 输出加密结果
4 console.log(encrypted)
5 // 设置密钥
6 jse.setPrivateKey(`-----BEGIN RSA PRIVATE KEY-----
7 MIICXgIBAAKBgQC8ygMKjJLSUpnfXqt8lRSAdDxAHWKi9GbTFkCbAjkRCR6VUakx
8 xXLXHQUtPCizKcvNpuYqZ5bO8LEgpY7SL3JEdEI9OuMnZ6ToeHPfcHeS+EgN0oYm
9 dQ49RB5wZkcBEFk80OBEAM6VhnE0IuHGkU5ko9oPHq3boEQ3Ej6r3T+UhQIDAQAB
10 AoGBAIO8JwEedHlE4FBovBsT4Bl+gmhu2NxC1NlpBq3jkDSd+3RQZlLvp6IJgwo8
11 l13lxWv8kVF3tVkzxTW1sQJjz0RYShH8vXLl94gf6mFkJbeOPP6uA0mGDG81yINw
12 KUpE0RM6ZM9yKEeVdK3u67TkEBcC6Td5KBl8Yof3q7qxiOWhAkEA4BXEtpnfhgm3
13 7s1VjDxdIHTtWL1PihMT+SCOqp+Vv27ABVrxtDW/w2R3ZzR5ezROI2v1DVhj5wvs
14 xPGXx6OpSQJBANetVvazS/5SQNvb+Cmjw9Rt5NilyxfX5IsSswaIojbwhZY2FVZy
15 AlFH9K/YS2FYFyU7iIqN6IIkOxXpOcj/bV0CQQCRYM4MgWuotClmfkSgBJGOew14
16 4uj1dUch+2NTgtFOLvXZA5WICs7sXwOwKzUdH2QKSwHitJOr0+q6ItsLpDwxAkBX
17 zvDK+/CCmIZjfMkqWsxN3nf/ZHCtQm5/2Jsem94/M+mPYHGLgltDMGKEfTEjbrPt
18 qrFKh8ATzCBqKUwncybZAkEAmVNW1dftWWoriZZXXMvfFkTDgYvRmytoVEThhnd0
19 J/AOhZiUAs9+kHfGKivlTE209AY6Bw8aRzuTCziSwQhhBQ==
20 -----END RSA PRIVATE KEY-----`)
21 // 解密加密过的字符串
22 let decrypted = jse.decrypt(encrypted)
23 // 打印结果
24 console.log(decrypted)
我在项目中的使用如下图(this.publicKey从接口获取):
以上为我的使用方式,欢迎大家批评指正~
参考地址:http://travistidwell.com/jsencrypt/#