node-rsa使用

版权声明:转载请注明文章出处 https://blog.csdn.net/zhj_fly/article/details/80076541

简单介绍使用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

猜你喜欢

转载自blog.csdn.net/zhj_fly/article/details/80076541
RSA