spring boot + vue3 实现RSA加密解密

一、前端部分

1、安装依赖

bash 复制代码
npm i jsencrypt

2、定义函数,进行数据加密

javascript 复制代码
import JSEncrypt from 'jsencrypt';
import { getLoginPublicKey } from '@/api/common';//获取后端公钥接口

//RSA加密
export const rsaEncryption = async (data) => {
  let res = await getLoginPublicKey();//获取公钥
  const { publicKey } = res;
  const encryptor = new JSEncrypt();
  encryptor.setPublicKey(`-----BEGIN PUBLIC KEY-----\n${publicKey}\n-----END PUBLIC KEY-----`);
  return encryptor.encrypt(data + '|timestamp|' + Date.parse(new Date()));
};

二、后端

1、maven依赖

bash 复制代码
<dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.44</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>

2、执行命令生成公钥和私钥(可在windows电脑中的cmd命令窗口中执行)

获取私钥:openssl genrsa -out rsa_private.key 2048

获取公钥:openssl rsa -in rsa_private.key -pubout -out rsa_public.key

3、将秘钥文件放到resources中

4、封装工具类RsaUtil

java 复制代码
package com.example.system_manage.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.KeyUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.PublicKey;

public class RsaUtil {
    /**
     * 获取私钥
     */
    public static PrivateKey getPrivateKey() throws Exception {
        ClassPathResource classPathResource = new ClassPathResource("rsakey/rsa_private.key");
        try(InputStream inputStream = classPathResource.getInputStream()){
            String privateKeyStr=IOUtils.toString(inputStream, StandardCharsets.UTF_8)
                    .replace("-----BEGIN RSA PRIVATE KEY-----", "")
                    .replace("-----END RSA PRIVATE KEY-----", "")
                    .replaceAll("\\s", "");
            byte[] keyBytes = Base64.decode(privateKeyStr);
            return KeyUtil.generateRSAPrivateKey(keyBytes);
        }

    }

    //获取公钥
    public static String getPublicKey() {
        ClassPathResource classPathResource = new ClassPathResource("rsakey/rsa_public.key");
        try(InputStream inputStream = classPathResource.getInputStream()) {
            String result= IOUtils.toString(inputStream, StandardCharsets.UTF_8)
                    .replace("-----BEGIN PUBLIC KEY-----", "")
                    .replace("-----END PUBLIC KEY-----", "")
                    .replaceAll("\\s+", "");
            return result;
        }catch (Exception ex){
            throw new BusinessException(ex.getMessage());
        }
    }

    //解密
    public static String decrypt(String encryptedBase64) {
        try {
            //私钥
            PrivateKey privateKey = getPrivateKey();
            //公钥
            PublicKey publicKey=KeyUtil.getRSAPublicKey(privateKey);
            String content=new RSA(privateKey,publicKey).decryptStr(encryptedBase64, KeyType.PrivateKey);
            String[] contents=content.split("\\|timestamp\\|");
            if(contents.length!=2){
                throw new BusinessException("解密失败");
            }
            if(System.currentTimeMillis()-Long.valueOf(contents[1]).longValue()>3000){
                throw new BusinessException("当前无效报文");
            }
            return contents[0];
        }catch (Exception ex){
            throw new BusinessException(ex.getMessage());
        }
    }
}

5、然后就可以愉快的在代码中执行了

相关推荐
huaweichenai9 分钟前
spring boot对接阿里短信
java·spring boot
KING-WU51210 分钟前
Linux 工具之Make 与 Makefile
java·linux·服务器
马剑威(威哥爱编程)29 分钟前
【AI全栈后端12-08】Spring Boot 用 MCP 统一接入内部系统:让 AI 接一次,全公司复用
java·人工智能·spring boot
顽疲36 分钟前
从零用 Java 实现小红书 SpringBoot Vue UniApp(23)笔记话题多对多:一条笔记进多个话题池
java·vue.js·spring boot
打工仔折腾 AI1 小时前
FaceFusion本地换脸实战:Windows整合包、模型选择与遮罩调参记录
人工智能·windows·后端·python·深度学习·性能优化·ai agent 实战
做个文艺程序员1 小时前
MQ第02篇:RabbitMQ快速上手教程:AMQP模型详解+Spring Boot整合实战(附完整代码)
spring boot·消息队列·rabbitmq·java-rabbitmq·amqp
木井巳1 小时前
【BFS 解决拓扑排序】课程表
java·算法·leetcode·广度优先·宽度优先·推荐算法·图搜索算法
RuoyiOffice1 小时前
SpringBoot3 企业定时结算架构:考勤日结、合同到期、库存预警与财务结转如何可靠执行
spring boot·xxl-job·定时任务·分布式任务·spring boot 3·幂等设计·ruoyi office
Crazy________1 小时前
05Linux内存管理核心原理与运维实战
java·开发语言
Nebula_g1 小时前
JavaSE拓展:工具类Executors
java·开发语言·后端·spring·基础·javase