基于node简单实现RSA加解密

5次阅读

共计 1859 个字符,预计需要花费 5 分钟才能阅读完成。

起因是项目中用了 rsa 加密,趁着空余时间,琢磨了下在 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’;
原文地址:基于 node 简单实现 RSA 加解密欢迎关注微信公众号“我不会前端”,二维码如下:

谢谢!

正文完
 0