node-rsa使用

简单介绍使用node-rsa模块生成/导出秘钥,加密/解密,签名/验证

具体方法见API

1.首先导入模块:

npm install node-rsa

2.生成,导入导出秘钥

var NodeRSA = require('node-rsa');

var key = new NodeRSA({b: 512});//生成512位秘钥
var pubkey = key.exportKey('pkcs8-public');//导出公钥
var prikey = key.exportKey('pkcs8-private');//导出私钥
var pubKey = new NodeRSA(pubKey,'pkcs8-public');//导入公钥
var priKey = new NodeRSA(priKey,'pkcs8-private');//导入私钥

3.加密解密

公钥加密(返回密文):

pubKey = new NodeRSA(publicKey,'pkcs8-public');
var encrypted = pubKey.encrypt(buffer, 'base64');

私钥解密(返回明文):

priKey = new NodeRSA(privateKey,'pkcs8-private');
var decrypted = priKey.decrypt(buffer, 'utf8');

4.签名验证

私钥签名(返回签名):

priKey = new NodeRSA(privateKey,'pkcs8-private');
var signature = priKey.sign(buffer);

公钥验证(返回true或false):

pubKey = new NodeRSA(publicKey,'pkcs8-public');
var flag = pubKey.verify(buffer, signature);
上面只是一种实现方法,其中这些方法中可能还有一些其他参数选项,详细参考官方的api
`node-rsa`是一个在Node.js环境中常用的RSA加密库,它的使用相对直观。下面是一个简单的例子,展示了如何创建一个RSA密钥对,加密数据以及解密数据: ```javascript // 引入node-rsa库 const RSA = require('node-rsa'); // 创建一个新的RSA对象 const rsa = new RSA(); // 生成私钥和公钥对 async function generateKeys() { try { await rsa.generateKeyPair(2048); // 2048位密钥长度是个常见选择 const privateKey = rsa.exportKey('pkcs8'); // 导出私钥(PKCS#8格式) const publicKey = rsa.exportKey('public'); // 导出公钥(PEM格式) console.log('Private key:', privateKey); console.log('Public key:', publicKey); } catch (error) { console.error('Error generating keys:', error); } } // 加密数据 function encryptData(plaintext, publicKey) { return rsa.encrypt(plaintext.toString(), publicKey).toString(); } // 解密数据 function decryptData(ciphertext, privateKey) { try { const decryptedData = rsa.decrypt(Buffer.from(ciphertext, 'hex'), privateKey); // 注意输入是Buffer对象 return decryptedData.toString(); } catch (error) { console.error('Error decrypting:', error); } } generateKeys().then(() => { // 示例:加密和解密消息 const message = 'Hello, world!'; const encryptedMessage = encryptData(message, publicKey); const decryptedMessage = decryptData(encryptedMessage, privateKey); console.log('Encrypted:', encryptedMessage); console.log('Decrypted:', decryptedMessage); }); ``` 以上代码首先生成一个2048位的RSA密钥对,然后展示如何使用它们进行数据的加密和解密。记得在实际项目中妥善管理私钥,避免泄露。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值