如何对html文件加密,node代码如何加密?

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

b63df2a47405d21d85e88ac6613bfcfe.png

node代码加密方法如下:

1、初始化环境

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

npm init # 一路回车即可

npm install --save node-rsa

2、生成公钥私钥

在 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

3、加密:

加密 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字符串,这就是用私钥加密后的密文了

4、解密:

把上一步加密获得的密文复制粘贴到下面要解密的方法内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 了

下面通过一段代码看下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

};

此处,只针对可逆加密。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值