开发 一月 15, 2020

node-rsa 生成私钥/公钥 加密/解密 签名/验证

文章字数 2k 阅读约需 2 mins. 阅读次数 0

前言

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

具体方法见API

首先导入模块

npm install 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');//导入私钥

加密解密

公钥加密(返回密文):

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

私钥解密(返回明文):

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

签名验证

私钥签名(返回签名):

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