NodeJS使用 node-rsa 加密解密

a 夏天 提交于 2020-01-11 09:56:24
const NodeRSA = require('node-rsa');
const fs = require('fs');

// 公钥加密
function encrypt(data) {
const publicKey = fs.readFileSync('./files/rsa_public_key_1024.txt');
const nodersa = new NodeRSA(publicKey);
// nodersa.setOptions({ encryptionScheme: 'pkcs1' });
const encrypted = nodersa.encrypt(data, 'base64');
return encrypted;
}


// 私钥解密
function decrypt(data) {
const privateKey = fs.readFileSync('./files/rsa_private_key_1024.txt');
const nodersa = new NodeRSA(privateKey);
const decrypted = nodersa.decrypt(data, 'utf8');
return decrypted;
}


// 实例
const data = { name: 'owen', age: 20 };
const encrypted = encrypt(data);
console.log('encrypted:', encrypted);

const decrypted = decrypt(encrypted);
console.log('decrypted:', decrypted);

  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!