原由是項目中用了rsa加密,趁着空餘時間,琢磨了下在node下的實現。javascript
前端是利用jsencrypt.js去加密,後端利用node-rsa去生成公私鑰並解密。html
我是使用koa2初始化的項目。首先,須要前端頁面顯示和處理加密數據,因此直接在views中新建了index.html,用html爲了避免在學習模板上花時間。前端
修改index中的路由,vue
router.get('/', async (ctx, next) => { await ctx.render('index.html'); });
在html中引入jsencrypt.js,界面內容僅爲一個輸入框和發送命令的按鈕:java
<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必須得加上,否者會有報錯問題。node
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; });
公鑰傳出給前端加密用,後端使用私鑰解密,react
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進行解密,前端控制檯就能輸出對應的值了。git
說這麼多,直接查看代碼最直觀啦,詳細代碼查看:demo。
npm i & npm run start
訪問3000端口就能夠了。github
在使用npm安裝方式(vue或react)的項目中,能夠這麼使用:npm
npm i jsencrypt // 實際使用 import { JSEncrypt } from 'jsencrypt';
原文地址:基於node簡單實現RSA加解密
歡迎關注微信公衆號 「 我不會前端 」,二維碼以下:
謝謝!