The original post address

Refer to the article

  • npm node-rsa
  • npm jsencrypt
  • node-rsa errors when trying to decrypt message with private key
  • Nodejs RSA and JsENCRYPT for front-end encryption and back-end decryption (asymmetric)

Say first demand

Front-end login logic: Encrypts user accounts and passwords before sending them. The back-end interface decrypts the ciphertext and processes other services. The backend uses NodeJS.

The following two parts are the front-end and back-end to illustrate the specific process.

The back-end (nodejs/koa2)

Use the scaffolding KOA-Generator or create your own KOA2 project (skipped here).

Install dependencies:

  1. koa
  2. koa-routerrouting
  3. koa-bodyparserProcess the parameters carried by the POST request
  4. node-rsaThe node side implements RSA, which is not requiredOpenSSL
  5. koa2-corsOptional, mainly to solve cross-domain problems, if the front end uses proxy mode requests, do not install

Add main file

/index.js

const Koa = require("koa");
const cors = require("koa2-cors");
const bodyParser = require("koa-bodyparser");
const KoaRouter = require("koa-router");
const NodeRSA = require("node-rsa");

// app
const app = new Koa();

// CORS front-end uses XHR request (AXIos), fetch request will be invalid
app.use(cors());

// Handle the POST argument
app.use(bodyParser());

// Add a route
const router = new KoaRouter();

Rsa encryption/decryption module
const RSA = new NodeRSA({ b: 512 });
/ / note:
// The front end will use 'jsencrypt' as an encryption tool whose default encryption type is 'pkcs1'
// Therefore, we need to configure the same here
RSA.setOptions({ encryptionScheme: "pkcs1" });

// Get the public key
router.get("/api/get-publick-key".async (ctx) => {
  const publicKey = RSA.exportKey(); // Generate a public key
  ctx.body = { publicKey };
});

// User login
router.post("/api/user/login".async (ctx) => {
  const { username, password } = ctx.request.body;
  // The 'password' passed by the front end is ciphertext, which is decrypted here
  const decryptedPassword = RSA.decrypt(password, "utf8");

  ctx.body = {
    username,
    password: decryptedPassword, // return the decrypted 'password' to check whether the password is the same
  };
});

// Register the route
app.use(router.routes());

/ / start
app.listen(8000);
Copy the code

The front (react)

The React framework is used, or you can use no framework at all.

  1. usecreate-react-appcreatereactproject
  2. Install dependencies:axios.jsencrypt
  3. Modify the/src/App.jsx
import React, { useCallback } from "react";
import axios from "axios";
import JSEncrypt from "jsencrypt";

// Address of the back-end interface
const SERVER_ORIGIN = "http://localhost:8000";
const encryptor = new JSEncrypt();

const App = () = > {
  const login = useCallback(() = > {
    const f = async() = > {try {
        const res1 = await axios.get(`${SERVER_ORIGIN}/api/get-publick-key`);
        console.log("publicKey", res1.data.publicKey);

        // Set the public key
        encryptor.setPublicKey(res1.data.publicKey);

        const res2 = await axios.post(`${SERVER_ORIGIN}/api/user/login`, {
          username: "my-name".// Encrypt the password
          password: encryptor.encrypt("my-password")});console.log("user", res2.data);
      } catch (err) {
        console.error(err); }}; f(); } []);return (
    <>
      <h1>rsa encrypt</h1>
      <button onClick={login}>login</button>
    </>
  );
};

export default App;
Copy the code