nest

import * as NodeRSA from 'node-rsa';

let priKey = new NodeRSA({ b: 1024 });
priKey.setOptions({ encryptionScheme: 'pkcs1' });

// 解密
export function decrypt(txt: string) {
  return priKey.decrypt(txt, 'utf8');
}
// 获取公钥
export function getPubKey() {
  return priKey.exportKey('public');
}

// 重置key
export function resetPriKey() {
  priKey = new NodeRSA({ b: 1024 });
  priKey.setOptions({ encryptionScheme: 'pkcs1' });
}

公钥做接口前端可调用
重置是用来配合定时任务做定期更新

前端

<script setup lang="ts">
import axios from "axios";
 import JSEncrypt from "jsencrypt";

let pubKey   ;
const fetPubKey = async () => {
    const res = await axios({
        method: "GET",
        url: "http://127.0.0.1:3000/auth/getPubKey",
        headers: {
            'Content-Type': 'application/json;charset=UTF-8'
        }
    })
    pubKey  = res.data.data
}
const fetchLogin = async () => {
    await fetPubKey()
    const encryptor = new JSEncrypt()
    encryptor.setPublicKey(pubKey)
    const pwd = encryptor.encrypt('pwd-wm')
    axios({
        method: "POST",
        url: "http://127.0.0.1:3000/auth/login",
        data: {"name": "wm", "pwd": pwd},
        headers: {
            'Content-Type': 'application/json;charset=UTF-8'
        }
    }).then(response => {
        console.log(response);
    })
}
</script>

<template>
    <button @click="fetchLogin">登录</button>
</template>

更多推荐