因項目登錄密碼字段沒有加密引起安全問題,琢磨了下如何基于RSA加密,進行前后端通信(Java項目)??沼鄷r間,看了下在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/91key.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。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答