2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > node 加密解密模块_NodeJS加密解密及node-rsa加密解密用法详解

node 加密解密模块_NodeJS加密解密及node-rsa加密解密用法详解

时间:2022-12-24 18:03:54

相关推荐

node 加密解密模块_NodeJS加密解密及node-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 了

参考

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

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

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

/**

* created by linli on /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加密解密用法详解,希望对大家有所帮助

希望与广大网友互动??

点此进行留言吧!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。