rsa加密解密用法详解

要用nodejs开发接口,实现远程调用,如果裸奔太危险了,就在网上找了一下nodejs的加密,感觉node-rsa挺不错的,下面来总结一下简单的rsa加密解密用法

初始化环境

新建一个文件夹 node-rsa-demo , 终端进入,运行下面命令初始化

cd node-rsa-demo npm init # 一路回车即可 npm install --save node-rsa

生成公钥私钥

在 node-rsa-demo 下新建一个文件 index.js 写上如下代码

var NodeRSA = require('node-rsa') var fs = require('fs') function generator() { var key = new NodeRSA({ b: 512 }) key.setOptions({ encryptionScheme: 'pkcs1' }) var privatePem = key.exportKey('pkcs1-private-pem') var publicPem = key.exportKey('pkcs1-public-pem') fs.writeFile('./pem/public.pem', publicPem, (err) => { if (err) throw err console.log('公钥已保存!') }) fs.writeFile('./pem/private.pem', privatePem, (err) => { if (err) throw err console.log('私钥已保存!') }) } generator();

先在 node-rsa-demo 文件夹下新建一个文件夹 pem 用来存放密钥的,然后执行 node index.js ,会发现在 pem 文件夹下生成了两个文件

private.pem

public.pem

加密

加密 hello world 这个字符串

function encrypt() { fs.readFile('./pem/private.pem', function (err, data) { var key = new NodeRSA(data); let cipherText = key.encryptPrivate('hello world', 'base64'); console.log(cipherText); }); } //generator(); encrypt();

然后执行 node index.js 终端里会输出一串类似

fH1aVCUceJYVvt1tZ7WYc1Dh5dVCd952GY5CX283V/wK2229FLgT9WfRNAPMjbTtwL9ghVeYD4Lsi6yM1t4OqA== 的base64字符串,这就是用私钥加密后的密文了

解密

把上一步加密获得的密文复制粘贴到下面要解密的方法内

function decrypt() { fs.readFile('./pem/public.pem', function (err, data) { var key = new NodeRSA(data); let rawText = key.decryptPublic('fH1aVCUceJYVvt1tZ7WYc1Dh5dVCd952GY5CX283V/wK2229FLgT9WfRNAPMjbTtwL9ghVeYD4Lsi6yM1t4OqA==', 'utf8'); console.log(rawText); }); } //generator(); //encrypt(); decrypt();

执行 node index.js 会发现又拿到 hello world 了

参考

https://github.com/rzcoder/node-rsa

PS:下面通过一段代码看下nodejs加密解密

nodejs是通集成在内核中的crypto模块来完成加密解密。

常用加密解密模块化代码:

/** * Created by linli on 2015/8/25. */ var crypto = require('crypto'); //加密 exports.cipher = function(algorithm, key, buf) { var encrypted = ""; var cip = crypto.createCipher(algorithm, key); encrypted += cip.update(buf, 'binary', 'hex'); encrypted += cip.final('hex'); return encrypted }; //解密 exports.decipher = function(algorithm, key, encrypted) { var decrypted = ""; var decipher = crypto.createDecipher(algorithm, key); decrypted += decipher.update(encrypted, 'hex', 'binary'); decrypted += decipher.final('binary'); return decrypted };

此处,只针对可逆加密。

总结

以上所述是小编给大家介绍的NodeJS加密解密及node-rsa加密解密用法详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/cf357c2a75c2ff28d2b0f3350e7c79c8.html