JavaScript

超轻量级php框架startmvc

基于node简单实现RSA加解密的方法步骤

更新时间:2020-08-18 10:06 作者:startmvc
因项目登录密码字段没有加密引起安全问题,琢磨了下如何基于RSA加密,进行前后端通信(

因项目登录密码字段没有加密引起安全问题,琢磨了下如何基于RSA加密,进行前后端通信(Java项目)。空余时间,看了下在node下的实现。

一、准备

前端是利用jsencrypt.js去加密,后端利用node-rsa去生成公私钥并解密。

二、实现

我是使用koa2初始化的项目。首先,需要前端页面显示和处理加密数据,所以直接在views中新建了index.html,用html为了不在学习模板上花时间。

修改index中的路由,


router.get('/', async (ctx, next) => {
 await ctx.render('index.html');
});

在html中引入jsencrypt.js,界面内容仅为一个输入框和发送命令的按钮:


<body>
 <input type="text" id="content"/>
 <button id="start">gogogog</button>
</body>
<script src="/javascripts/jsencrypt.js"></script>
<script>
document.getElementById('start').onclick = function() {
 // 获取公钥
 fetch('/publicKey').then(function(res){
 return res.text();
 }).then(function(publicKey) {
 // 设置公钥并加密
 var encrypt = new JSEncrypt();
 encrypt.setPublicKey(publicKey);
 var encrypted = encrypt.encrypt(document.getElementById('content').value);
 // 发送私钥去解密
 fetch('/decryption', {
 method: 'POST',
 body: JSON.stringify({value:encrypted})
 }).then(function(data) {
 return data.text();
 }).then(function(value) {
 console.log(value);
 });
 });
};
</script>

点击按钮,将输入框中的值先加密,再发送给服务器解密并打印该值。

前端用到了,publicKey和decryption接口,来看下服务端的实现。

首先引入node-rsa包,并创建实例,再输出公私钥,其中,setOptions必须得加上,否者会有报错问题。


const NodeRSA = require('node-rsa');
const key = new NodeRSA({b: 1024});
// 查看 https://github.com/rzcoder/node-rsa/issues/91
key.setOptions({encryptionScheme: 'pkcs1'}); // 必须加上,加密方式问题。

publicKey(GET),用于获取公钥,只需要调用下内置的方法就行了,


router.get('/publicKey', async (ctx, next) => {
 var publicDer = key.exportKey('public');
 var privateDer = key.exportKey('private');
 console.log('公钥:', publicDer);
 console.log('私钥:', privateDer);
 ctx.body = publicDer;
});

公钥传出给前端加密用,后端使用私钥解密,


router.post('/decryption', async (ctx, next) => {
 var keyValue = JSON.parse(ctx.request.body).value;
 const decrypted = key.decrypt(keyValue, 'utf8');
 console.log('decrypted: ', decrypted);
 ctx.body = decrypted;
});

解密时调用decrypt进行解密,前端控制台就能输出对应的值了。

三、demo详细代码

说这么多,直接查看代码最直观啦,详细代码查看:demo。


npm i & npm run start

访问3000端口就可以了。

四、实际项目

在使用npm安装方式(vue或react)的项目中,可以这么使用:


npm i jsencrypt
// 实际使用
import { JSEncrypt } from 'jsencrypt';

项目地址可以查看:https://github.com/2fps/blooog。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。