第一步需要先生成一个私钥和一个公钥。公钥用于加密,私钥用于解密。
去链接生成公钥和私钥;
![](https://i-blog.csdnimg.cn/blog_migrate/a266134480277208bb86952f3a5d8fb0.png)
加密、解密
![](https://i-blog.csdnimg.cn/blog_migrate/ea7aa28d4d6de1333faa6d68e3b30a7f.png)
安装插件
// 安装jsencrypt:
npm install jsencrypt --save
代码段
import JSEncrypt from "jsencrypt";
// 加密(origin:原始text,key:公钥)
xxx(origin, key) {
const encrypt = new JSEncrypt();
encrypt.setPublicKey(key);
return encrypt.encrypt(origin);
},
// 解密(origin:加密text,key:私钥)
yyy(cipher, key) {
const decrypt = new JSEncrypt();
decrypt.setPrivateKey(key);
return decrypt.decrypt(cipher);
},
zzz() {
console.log(this.text);
// 公钥
let gong = `-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxXwRhs+PtxLj6c2R/kF+T+mTy
WvFtGYIsuS8SKP67ecHMDKijV8ppHbWMXLQ9KNDOwjHGgfqNfPPb1iEhzD0Mg34y
dOdXMEvVudSUjNSd9tx/rd3OTu6nGZitLETIHYsQ2t9emdp9TTCYkyjg/hVJUQTp
tXZe7ljXlci0JlzNHwIDAQAB
-----END PUBLIC KEY-----`;
// 私钥
let si = `-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCxXwRhs+PtxLj6c2R/kF+T+mTyWvFtGYIsuS8SKP67ecHMDKij
V8ppHbWMXLQ9KNDOwjHGgfqNfPPb1iEhzD0Mg34ydOdXMEvVudSUjNSd9tx/rd3O
Tu6nGZitLETIHYsQ2t9emdp9TTCYkyjg/hVJUQTptXZe7ljXlci0JlzNHwIDAQAB
AoGASraxi85Q1pklKiptTOatvBGfcA8q3z/9e4VN9KJcGvCA18kFSDj0xC6FiOiL
669DtbRLb0jVF8BooFOkhS4ZEHPdzgPXp2boYehf5bt6HcA02Ntrjisuj6w87WPs
BPzdai2aCrXEB/lRyQXCFc+ICCA4MZWxfn3RvGL7Du5NEdECQQD/hxpT0qg79kFi
u7odGVCB0HFF89wzDRKe4fvXOMvm44qCQOwI4lI5dtUkefrjPrQGruMCTB3hhJru
0iWamRvNAkEAsbLvrqHZa9BoGW5e/tbev79klwTEoCZAHx/f26VIot7ggsFGe4qF
y4HOC5iz1AwE9Sqqcx0CkpqvQ50WoQTYmwJAPR7X0U0GKLGSmkdFEUjI1QRC0/Ss
qxlpZs+vKZ/QRf4PV3CoBMf92vjtqrfypwCMlzyl2BrU2uiZFp71l7Ef0QJBAJQy
2GQ7RTn+gKMdAorkprciJwEwD9BEtlt+2NK1YQO8f19tU5v65iTYaAAR5YAmWggi
Ai+o9RlRenQYUeQOR5sCQG7ED9om0VKPTWPst2jiCeRymy5EhcIgnxhfB+IOqiSa
hGp8pA1kC/0HNI+hY+GvFkseMkdwam9HKKHhNg3q3bY=
-----END RSA PRIVATE KEY-----`;
// 加密
let _str = this.xxx("123456989", gong);
//解密
console.log(this.yyy(_str, si));
},