node 前端加密后端解密

前端jsencrypt加密

1
2
3
4
5
import JsEncrypt from 'jsencrypt'

const jsEncrypt = new JsEncrypt()
jsEncrypt.setPublicKey(public_key)
jsEncrypt.encrypt(username)

后端RSA解密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const NodeRSA = require('node-rsa'); 
const newkey = new NodeRSA({b: 1024});

//因为jsencrypt自身使用的是pkcs1加密方案,只有从后台改咯
const newkey.setOptions({encryptionScheme: 'pkcs1'});

const public_key = newkey.exportKey('pkcs8-public');//公钥,
const private_key = newkey.exportKey('pkcs8-private'); //私钥
const pubkey = new NodeRSA(public_key);
const prikey = new NodeRSA(private_key);

//因为jsencrypt自身使用的是pkcs1加密方案,只有从后台改咯
pubkey.setOptions({encryptionScheme: 'pkcs1'});

//因为jsencrypt自身使用的是pkcs1加密方案,只有从后台改咯
prikey.setOptions({encryptionScheme: 'pkcs1'});

//加密&&解密方法
const encrypted = pubkey.encrypt(yourstring,'base64');
const decrypted = prikey.decrypt(encrypted, 'utf8');