nodejs 公私钥文件加密解密
利用 openssl 生成公钥私钥
生成公钥: openssl genrsa -out privateKey.pem 1024
生成私钥: openssl rsa -in privateKey.pem -pubout -out publicKey.pem
const fs = require('fs')
const privateKey = fs.readFileSync(`privateKey.pem`).toString();
const publicKey = fs.readFileSync(`publicKey.pem`).toString();
const crypto = require('crypto');
const data = "eggsy";
//公钥加密
const encodeData = crypto.publicEncrypt(publicKey, Buffer.from(data)).toString('base64');
console.log("encode: ", encodeData)
//私钥解密
const decodeData = crypto.privateDecrypt(privateKey, Buffer.from(encodeData.toString('base64'), 'base64'));
console.log("decode: ", decodeData.toString())
console.log('---------------------------------')
//私钥加密
const encodeData2 = crypto.privateEncrypt(privateKey, Buffer.from(data)).toString('base64');
console.log("encode2: ", encodeData2)
//公钥解密
const decodeData2 = crypto.publicDecrypt(publicKey, Buffer.from(encodeData2.toString('base64'), 'base64'));
console.log("decode2: ", decodeData2.toString())