1、安裝jsencryptnode
1 npm i jsencrypt
node_modules文件夾中出現jsencryptnpm
2、引入jsencrypt工具
在main.js中import:this
1 import JsEncrypt from 'jsencrypt' 2 Vue.prototype.$jsEncrypt = JsEncrypt
3、生成公鑰和私鑰(服務端生成)加密
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 讀取公鑰內容
4、JSEncrypt實例化(此部分可作成工具類,供項目中各模塊使用)spa
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-----`)
5、加解密(公鑰加密,私鑰解密)prototype
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從接口獲取):3d
以上爲個人使用方式,歡迎你們批評指正~code
參考地址:http://travistidwell.com/jsencrypt/#對象