生成密钥对
const NodeRSA = require('node-rsa');
const key = new NodeRSA({b: 512});
const publicKey = key.exportKey('public');
const privateKey = key.exportKey('private');
console.log('Public Key:', publicKey);
console.log('Private Key:', privateKey);
加密解密例子
const NodeRSA = require('node-rsa');
let pk="-----BEGIN PUBLIC KEY-----\n" +
"MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgFYiHvXY0EqYUAEuchLaOtpTfjxo\n" +
"l9v6Qt8keUw+LG6YwtpFz3c5r3ZezgjpCEq2EQzAdJzGPylfgQGL2mSr+whczz1i\n" +
"6uXAB7KYVY3DUY2C9LkfhdmWoWHPT0n8Po7mbWauddE7thgGcXHs6ngEq5tr6us6\n" +
"BpHo7rrm59ccjPHTAgMBAAE=\n" +
"-----END PUBLIC KEY-----"
// 私钥
let priK = "-----BEGIN RSA PRIVATE KEY-----\n" +
"MIICWwIBAAKBgFYiHvXY0EqYUAEuchLaOtpTfjxol9v6Qt8keUw+LG6YwtpFz3c5\n" +
"r3ZezgjpCEq2EQzAdJzGPylfgQGL2mSr+whczz1i6uXAB7KYVY3DUY2C9LkfhdmW\n" +
"oWHPT0n8Po7mbWauddE7thgGcXHs6ngEq5tr6us6BpHo7rrm59ccjPHTAgMBAAEC\n" +
"gYA6Ny+jzJnjgRS557F0KomSnNH6dFsHdBuUhCtzq6YOTjOMoZh6pcOBBszM2uwe\n" +
"yvW1H7Lxb1CrXwBrkiHW3yJ4mIy7M/VnO4n1YD6S5yZs+F72EyXxzEbVHSw3MZRg\n" +
"HMQ/fEmjfTCTxAkpDThKI45x0iCWPYrAdJZo5D+jK/ajKQJBAJs7U52eMoIxEuuZ\n" +
"E7kmdiiYS8mlmkLDtxh0coyIYzA/Ia7vq0GzVAgU2Gw5Jbc7Xs8jDUekz63QN90h\n" +
"+28pDtcCQQCOC+VIKOmtqdzNeh3NMv2zAaKpYgTieze8+qk2sbdyKpG5CY5+LKwq\n" +
"z8/m/hCEHrunElDFl1/hXwNrMB3I5sFlAkAPpG7Ml0BntiI983L1WVbWyGH6s+FT\n" +
"kP1GTZWta6DzH6l5Q1VyjWuOVOtqHGgcirMHFHUmHwl+bljyw5XeobiJAkEAh+bd\n" +
"sRJjsGGp/XVuedrlW5Se+gvrvHxDMa1opAmYB8SusyhvikxXVIaK1OgTCTUWOJyP\n" +
"ZtyTQV7UOINKm+Ia+QJADxxw7+BoN4/IAMld7/NhItkNRwE8/sQTes12IlZdvikM\n" +
"l+n5UgpXWz+ZJnX5WhAHytf3oIRU2Jd7Ix3I8gwDTg==\n" +
"-----END RSA PRIVATE KEY-----";
let comment = 'ajhsadjkfalsjkdfjklasdjf asdfasdfasdf';
const encrypt = new NodeRSA(pk);
const encryptedData = encrypt.encrypt(comment, 'base64');
console.log(encryptedData)
//使用私钥解密
const decrypt = new NodeRSA(priK);
const decryptedData = decrypt.decrypt(encryptedData, 'utf8');
console.log('Decrypted Data:', decryptedData);