springboot项目中实现 RSA 加密/解密工具

前提说明:计划放置密钥的位置是resources下

<!-- hutool工具包 -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.16</version>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-crypto</artifactId>
            <version>5.7.16</version>
        </dependency>

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.ruoyi.common.core.exception.ServiceException;
import sun.misc.BASE64Encoder;

import javax.validation.constraints.NotNull;
import java.io.*;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;


/**
 * RSA 加密/解密工具
 *
 * @author qs.zhang
 * @date 2023-07-26 10:02:08
 */
public class RSAUtils {

    /**
     * 公钥文件名称
     */
    private final static String PUBLIC_KEY_FILE_NAME = "publicKey.pem";
    /**
     * 私钥文件名称
     */
    private final static String PRIVATE_KEY_FILE_NAME = "privateKey.pem";

    /**
     * 类型
     */
    public static final String ENCRYPT_TYPE = "RSA";

    //获取公钥(Base64编码)
    public static String getPublicKey() throws Exception {
        String publicKeyPath =
                RSAUtils.class.getClassLoader().getResource(PUBLIC_KEY_FILE_NAME).getFile();//路径中不能有中文
        return readFile(publicKeyPath);
    }

    //获取私钥(Base64编码)
    public static String getPrivateKey() throws Exception {
        String privateKeyPath =
                RSAUtils.class.getClassLoader().getResource(PRIVATE_KEY_FILE_NAME).getFile();//路径中不能有中文
        return readFile(privateKeyPath);
    }

    /**
     * 公钥加密
     *
     * @param content 内容
     * @return {@link String }
     * @author qs.zhang
     * @date 2023-07-26 16:09:28
     */
    public static String encrypt(String content) throws Exception {
        try {
            RSA rsa = new RSA(null, getPublicKey());
            return rsa.encryptBase64(content, KeyType.PublicKey);
        } catch (Exception e) {
            throw new ServiceException("加密失败") ;
        }
    }

    /**
     * 私钥解密
     *
     * @param content 内容
     * @return {@link String }
     * @author qs.zhang
     * @date 2023-07-26 16:09:12
     */
    public static String decrypt(String content) throws Exception {
        try {
            RSA rsa = new RSA(getPrivateKey(), null);
            return rsa.decryptStr(content, KeyType.PrivateKey);
        } catch (Exception e) {
            throw new ServiceException("解密失败") ;
        }
    }

    /**
     * 根据文件路径读取文件内容
     *
     * @param fileInPath
     * @throws IOException
     */
    public static String readFile(@NotNull Object fileInPath) throws IOException {
        BufferedReader br = null;
        if (fileInPath == null) {
            return null;
        }
        if (fileInPath instanceof String) {
            br = new BufferedReader(new FileReader(new File((String) fileInPath)));
        } else if (fileInPath instanceof InputStream) {
            br = new BufferedReader(new InputStreamReader((InputStream) fileInPath));
        }
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            buffer.append(line);
        }
        br.close();
        return buffer.toString();
    }



    /**
     * 获取公私钥-请获取一次后保存公私钥使用
     *
     * @param publicKeyFilename  公钥生成的路径
     * @param privateKeyFilename 私钥生成的路径
     */
    public static void generateKeyPair(String publicKeyFilename, String privateKeyFilename) {
        try {
            String path = RSAUtils.class.getClassLoader().getResource("").getPath();

            KeyPair pair = SecureUtil.generateKeyPair(ENCRYPT_TYPE);
            PrivateKey privateKey = pair.getPrivate();
            PublicKey publicKey = pair.getPublic();
            // 获取 公钥和私钥 的 编码格式(通过该 编码格式 可以反过来 生成公钥和私钥对象)
            byte[] pubEncBytes = publicKey.getEncoded();
            byte[] priEncBytes = privateKey.getEncoded();

            // 把 公钥和私钥 的 编码格式 转换为 Base64文本 方便保存
            String pubEncBase64 = new BASE64Encoder().encode(pubEncBytes);
            String priEncBase64 = new BASE64Encoder().encode(priEncBytes);

            FileWriter pub = new FileWriter(path + "/" + publicKeyFilename);
            FileWriter pri = new FileWriter(path + "/" + privateKeyFilename);

            pub.write(pubEncBase64);
            pri.write(priEncBase64);

            pub.flush();
            pub.close();

            pri.flush();
            pri.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

调用一次generateKeyPair生成公钥和私钥,pem文件保存在target中的resources中,而不是原码的目录下,不影响使用,可以自己复制过来,之后就不要在调用这个方法,否则密钥将被更新;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot使用RSA加密的步骤如下: 1. 首先,生成私钥和公钥。可以使用Java内置的KeyPairGenerator类来生成RSA密钥对,分别得到私钥和公钥。 2. 将生成的密钥放到application.properties文件,可以使用spring-boot-starter-security等相关框架来管理密钥。 3. 前端发送请求时,向后端请求公钥。后端会随机获取公钥并将其返回给前端。 4. 前端使用开源的jsencrypt.js库来对需要加密的数据(例如密码)进行加密加密完成后,将加密后的数据传输到后端。 5. 后端接收到加密的数据后,使用私钥进行解密操作。 所以,使用RSA加密Spring Boot的步骤主要包括生成密钥、传输公钥至前端、前端加密数据传输至后端、后端使用私钥解密。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Springboot项目报文加密(采用AES、RSA动态加密策略)](https://download.csdn.net/download/qq_38254635/87620796)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Spring-boot如何使用RSA加密](https://blog.csdn.net/qq_39150049/article/details/109191120)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [SpringBoot通过RSA实现用户名和密码的加密解密](https://blog.csdn.net/qq_36735969/article/details/124842616)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

起风了小猪仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值