const fs = require('fs');
const NodeRSA = require('node-rsa');
const { pubkeyPath,prikeyPath } = require('../config');
// pubkeyPath:path.join(process.cwd(),'/auth/public.cer')
// prikeyPath:path.join(process.cwd(),'/auth/private.cer')
function generateKeys(){ //生成rsa秘钥
const newkey = new NodeRSA({b:512});
newkey.setOptions({ encryptionScheme: 'pkcs1' })
let public_key = newkey.exportKey('pkcs8-public') //公钥
let private_key = newkey.exportKey('pkcs8-private') //私钥
fs.writeFileSync(pubkeyPath,public_key);
fs.writeFileSync(prikeyPath,private_key);
}
function encrypt(plain){ //加密
let public_key = fs.readFileSync(pubkeyPath,'utf8');
const nodersa = new NodeRSA(public_key);
nodersa.setOptions({ encryptionScheme: 'pkcs1' });
const encrypted = nodersa.encrypt(plain,'base64');
return encrypted
}
function decrypt(cipher){ //解密
let private_key = fs.readFileSync(prikeyPath,'utf8');
const prikey = new NodeRSA(private_key);
prikey.setOptions({encryptionScheme : 'pkcs1'});
return prikey.decrypt(cipher,'utf8');
}
module.exports = {
generateKeys,encrypt,decrypt
}
Node RSA加解密
最新推荐文章于 2024-07-27 17:52:32 发布