node crypto生成公钥私钥进行数据加解密
crypto 是 node 内置的模块,用来做数据加解密,非常方便。
之前,我们的前端用的是 jsencrypt 做加密,后端则用 node-rsa 做解密,公钥和私钥都是通过 node-ras 生成的,代码如下
const NodeRSA = require('node-rsa')
let key = new NodeRSA({ b: 1024 })
key.setOptions({ encryptionScheme:'pkcs1'})
let pubkey = key.exportKey('public') //生成公钥,发给前端用于数据加密
let privkey = key.exportKey('private')//生成私钥,用于数据解密
解密的代码也很简单
let key = new NodeRSA(privkey)
key.setOptions({ encryptionScheme: 'pkcs1' })
//encryptData是加密后的数据
const s = encryptData.replace(/\s+/g, '+')
const decryptData = key.decrypt(s, 'utf8')
虽然很简单,但是额外安装的包依然让我很不爽,于是乎
const { generateKeyPairSync, publicEncrypt, privateDecrypt } = require('crypto')
//生成公钥和私钥
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
modulusLength: 1024,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
//需要加密的数据
const data = "data to crypto"
const pub = publicKey.toString('ascii')
const pri = privateKey.toString('ascii')
// console.log(pub, pri)
// 公钥加密
const encryptData = publicEncrypt(pub, Buffer.from(data)).toString('base64');
console.log('encode:', encryptData);
// 私钥解密
const decryptData = privateDecrypt(pri, Buffer.from(encryptData.toString('base64'), 'base64'));
console.log('decode:', decryptData.toString());
加密的结果
encode: Me+2EbDsMVLQHPKR8ZB3K88EDs4jNKuHsAZzMIjY3DCO7JEJGu3Tfkwv0tX4kDMiQvrxyJkR7tlpHQ1f91BrweAK6mkeyeyNQ3XOfsHwIEZJB+iv8IZpKiIlyE1KOGaUsN2Q8MyTRZ86IF+Qj4MwotDggXH/ADAHC0oJB/D5H5s=
解密的结果
decode: data to crypto
看看,加解密的过程是不是更简单呢