亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

基于node簡(jiǎn)單實(shí)現(xiàn)RSA加解密的方法步驟

 更新時(shí)間:2019年03月21日 09:56:47   作者:前端驛站  
這篇文章主要介紹了基于node簡(jiǎn)單實(shí)現(xiàn)RSA加解密的方法步驟,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

因項(xiàng)目登錄密碼字段沒(méi)有加密引起安全問(wèn)題,琢磨了下如何基于RSA加密,進(jìn)行前后端通信(Java項(xiàng)目)。空余時(shí)間,看了下在node下的實(shí)現(xiàn)。

一、準(zhǔn)備

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

二、實(shí)現(xiàn)

我是使用koa2初始化的項(xiàng)目。首先,需要前端頁(yè)面顯示和處理加密數(shù)據(jù),所以直接在views中新建了index.html,用html為了不在學(xué)習(xí)模板上花時(shí)間。

修改index中的路由,

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

在html中引入jsencrypt.js,界面內(nèi)容僅為一個(gè)輸入框和發(fā)送命令的按鈕:

<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) {
    // 設(shè)置公鑰并加密
    var encrypt = new JSEncrypt();
    encrypt.setPublicKey(publicKey);
    var encrypted = encrypt.encrypt(document.getElementById('content').value);
    // 發(fā)送私鑰去解密
    fetch('/decryption', {
      method: 'POST',
      body: JSON.stringify({value:encrypted})
    }).then(function(data) {
      return data.text();
    }).then(function(value) {
      console.log(value);
    });
  });
};
</script>

點(diǎn)擊按鈕,將輸入框中的值先加密,再發(fā)送給服務(wù)器解密并打印該值。

前端用到了,publicKey和decryption接口,來(lái)看下服務(wù)端的實(shí)現(xiàn)。

首先引入node-rsa包,并創(chuàng)建實(shí)例,再輸出公私鑰,其中,setOptions必須得加上,否者會(huì)有報(bào)錯(cuò)問(wèn)題。

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

publicKey(GET),用于獲取公鑰,只需要調(diào)用下內(nèi)置的方法就行了,

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;
});

解密時(shí)調(diào)用decrypt進(jìn)行解密,前端控制臺(tái)就能輸出對(duì)應(yīng)的值了。

三、demo詳細(xì)代碼

說(shuō)這么多,直接查看代碼最直觀啦,詳細(xì)代碼查看:demo。

npm i & npm run start

訪問(wèn)3000端口就可以了。

四、實(shí)際項(xiàng)目

在使用npm安裝方式(vue或react)的項(xiàng)目中,可以這么使用:

npm i jsencrypt
// 實(shí)際使用
import { JSEncrypt } from 'jsencrypt';

項(xiàng)目地址可以查看:https://github.com/2fps/blooog。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論