步骤:
1,前端或者后端生成公钥和私钥
前端rsa测试:https://www.bejson.com/enc/rsa/
2,加密:把需要加密字符串和公钥一起,就可以生成加密文(每次生成的加密文都是随机的)
3,解密:把加密文和私钥,就可以解密出,明文字符串
安装
npm i jsencrypt -S //main.js import JsEncrypt from 'jsencrypt' Vue.prototype.$jsEncrypt = JsEncrypt
let jse = new this.$jsEncrypt()
jse.setPublicKey(`-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApu6nwOArjseGbKDtJ5Xf
GxUM1JcGUKdHd20Nv17QXsHmuuZ42uP0RjbQgJa1hEvfjsGIh2XHGWoV4uI0ZMJR
fgJPQFDdrS1Hn9me6jz4QnuWtV6iQ7TQlmDg9BcV5WTt5Y/CLqWaFPqE0telXZud
uPud20wyTonJz93dvBET/FQhPadkhEG6mgpBg05Htui8sfup8kgvFyCXski7Lnk+
vIoQYjtDfv7ruQp2t4cNV6nK+jwITWGPoAI5gGekqwJJ9oDOlu6L15RpsNs7W+iU
Fko92uiJOetcu9mJYqO6/Bfy1s8xkp9zKWEe8WWPgrcUFH3y/fhaaWb+DX59AZkH
pwIDAQAB
-----END PUBLIC KEY-----
`)
//要加密的字符串
let encrypted = jse.encrypt('Hello, world')
// 输出加密结果
// console.log(encrypted)
jse.setPrivateKey(`-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCm7qfA4CuOx4Zs
oO0nld8bFQzUlwZQp0d3bQ2/XtBewea65nja4/RGNtCAlrWES9+OwYiHZccZahXi
4jRkwlF+Ak9AUN2tLUef2Z7qPPhCe5a1XqJDtNCWYOD0FxXlZO3lj8IupZoU+oTS
16Vdm524+53bTDJOicnP3d28ERP8VCE9p2SEQbqaCkGDTke26Lyx+6nySC8XIJey
SLsueT68ihBiO0N+/uu5Cna3hw1Xqcr6PAhNYY+gAjmAZ6SrAkn2gM6W7ovXlGmw
2ztb6JQ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VklM/6jyowMgcg3C
gOOZuQEVOg0yhN9MRnPOGiljvgHyseOF3kxdJXuSTQKBgQCwWQoi7907z8C6j92G
fNHXKvv1Qh9tRJU91XWFe5nLqikFInQO3PrTELmxQCdgV/3RsaL38vzy7EM0XMzP
WqXkf9QyVzng/zY1P7VDyryTUor3Kej8tWBAEz2a8xaIKnLZYK0zLuS7xSVL8KnC
n24uXVRRouRmgwrccVXWEXgHgQ==
-----END PRIVATE KEY-----
`)
// 解密加密过的字符串
let decrypted = jse.decrypt(encrypted)
// 打印结果
// console.log(decrypted)