在线生成生成RSA密钥对: http://web.chacuo.net/netrsakeypair

RSA公钥加密解密:http://tool.chacuo.net/cryptrsapubkey 

下载jsencrypt

cnpm i -S jsencrypt

引入jsencrypt

import { JSEncrypt } from "jsencrypt";

基本使用:

注意:要加密的数据必须是字符串!!

提示:给公钥直接用双引号“”引起来后可能要手动删掉每行末尾多余的空格,有点麻烦,此时可以直接用``来引 。只是这样可能排版显示不太好看

    testRSA() {
      let publicKey =
        "-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4aWAgASppilGGGPv6wdCp4AqTRbQPEMxU1mNwBXmP6v0hp2eHo8LMhjjM4IwzdzOnwyTR6v5YlznBb90cWKsr/DP1IdSI9ox7M7FCHGfURfLp/mGRvNLnJ5ds7YD+35rP0wLMZhNbkXHs3HMYOY96XnSE7bfcWkLiRrwiCrqLdQIDAQAB-----END PUBLIC KEY-----"; // 从后台获取公钥
      let data = JSON.stringify({ username: "zhangsan", password: 123 });
      // let data = "hello world";
      // let data = 123 + "";//必须传字符串

      console.log("加密前:", data);
      let encryptor = new JSEncrypt(); 
      encryptor.setPublicKey(publicKey); 
      let data_encrypted = encryptor.encrypt(data);
      console.log("加密后:", data_encrypted);

      let privateKey =
        "-----BEGIN PRIVATE KEY-----MIICeQIBADANBgkqhkiG9w0BAQEFAASCAmMwggJfAgEAAoGBALhpYCABKmmKUYYY+/rB0KngCpNFtA8QzFTWY3AFeY/q/SGnZ4ejwsyGOMzgjDN3M6fDJNHq/liXOcFv3RxYqyv8M/Uh1Ij2jHszsUIcZ9RF8un+YZG80ucnl2ztgP7fms/TAsxmE1uRcezccxg5j3pedITtt9xaQuJGvCIKuot1AgMBAAECgYEAti7cWSHtrZCJk6oRHhzlsT12FSKSjSOyScn3OM8f1i933gyNOjJtmzKq4LShraKAtKcUNBItLoZP96s0zPFIQCGjON0d3XyRxoGK2h3nEZT8NTqEcQVI2sbOy5PvJHAKT/Vrcqdkt/U9YteLWAKGZ5A8Ie8NZEjh0botUwIrOIECQQDd+Qv8IYiDSugZcOPEz/ijCR4Jg011X9/bqXVIEiqkIZ+8QToKCBuGt0EejhAzs0acni1XLPwBeDmAsmg8MmpVAkEA1K5NL3ZwuLjz4vs8EfF3BfscPTQZ9PRBhzGC9iqP7TyzMRyZjGpWfycOjki8isRzR3iNoFPIyLZfe5Wf4vL8oQJBALHia6BanzPYS7hXp7CJmg/NtqyY9PIjKxq16q8fH9z4tTIAc6qmZKjJIv6Biqpj+Sp5+IvsGOh0mGBymOXk4SECQQDDxSYbeGTORMGKwERNJ/2trbYSyHDUQDpJXdP1ELynXeZ8YJ0e2YuBQ8xsQJv9CFQtB9UmLbl2uBkwQ0yHta/BAkEAoKN1vdqkDTwAkSRpvFUOHkc7E6nEYdXwM+hhKnmQLCQb2aP8zW9GI2Q7EWPDEwN92TK30k1VSzpquSU7SUA32g==-----END PRIVATE KEY-----";
      let decryptor = new JSEncrypt();
      decryptor.setPrivateKey(privateKey);
      console.log("解密后:", decryptor.decrypt(data_encrypted));
    }

通常公钥由服务端提供,这里以koa2作为服务端来测试

首先koa2中安装node-rsa:

cnpm i -S node-rsa

服务端

const router = require('koa-router')()

router.prefix('/test')

router.get('/', (ctx, next) => {
    ctx.body = 'this is a users response!'
})

const NodeRSA = require('node-rsa');
const key = new NodeRSA({ b: 1024 });//密钥长度1024位
key.setOptions({ encryptionScheme: 'pkcs1' });//指定加密格式.不改格式得话可能会报错
router.get('/publicKey', async (ctx, next) => {
    let publicKey = key.exportKey('public');//生成公钥
    // let privateKey = key.exportKey('private');//生成私钥
    ctx.body = publicKey;
});
router.post('/decryption', async (ctx, next) => {
    let { value } = ctx.request.body;
    const decrypted = key.decrypt(value, 'utf8');
    console.log('服务端解密: ', decrypted);
    ctx.body = { message: "服务端获取到加密数据" };

});

module.exports = router

  客户端:

<!--main-->
<template>
  <div>
    <el-button @click="rsaEncryptData()">rsaEncryptData</el-button>
  </div>
</template>
<script>
import { JSEncrypt } from "jsencrypt";
import axios from "axios";
export default {
  methods: {
    async rsaEncryptData() {
      //获取公钥
      let { data: publicKey } = await axios.get("/api/test/publicKey");
      console.log("公钥:", publicKey);
      // 加密内容。目前测试出来嵌套对象超过3层rsa就加密不了了
      const formData = {
        username: "李疆",
        password: 123,
      };
      let encryptor = new JSEncrypt();
      encryptor.setPublicKey(publicKey);
      let encrypted = encryptor.encrypt(JSON.stringify(formData));
      console.log("rsa加密后:", encrypted);

      let result = await axios.post("/api/test/decryption", {
        value: encrypted,
      });
      console.log("result:", result);
    },
  },
};
</script>

 结果:

Logo

前往低代码交流专区

更多推荐