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、然后就可以愉快的在代码中执行了

相关推荐
卷无止境1 小时前
Python能做嵌入式开发吗?一份写给动手派的生态与硬件全景图
后端·python
疯狂打码的少年5 小时前
【数据库技术】关系模型基本概念(关系/属性/元组/键)
java·服务器·数据库·笔记
Sherotree7 小时前
Google Antigravity——Agent 被提到主界面
前端·ide·后端·edge浏览器
Mr数据杨7 小时前
【Codex】用学生入学评估模块建立新生能力画像
android·java·javascript·django·codex·项目开发
2601_962056237 小时前
Spring Boot 入门 与 无法解析符号 springframework 的解决
java·spring boot·后端
Thomas21438 小时前
Java scala 数组 链表
java·链表·scala
亚历克斯神8 小时前
低代码与 AI 的融合趋势——从可视化搭建到自然语言生成应用
java·spring·微服务
你驴我8 小时前
WhatsApp 多账号场景下的会话归档与历史消息检索优化实践
后端·python
学长毕业设计8 小时前
基于SpringBoot的瑜伽馆网站的设计与实现(源码+文档+讲解视频)
java·spring boot·后端
一嘴一个橘子8 小时前
nginx 常用命令(在 nginx 目录下执行)
java