NodeJS使用 node-rsa 加密解密


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);

  



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM