SpringBoot集成Jasypt加密yml配置文件

SpringBoot集成Jasypt对yml配置文件进行加密和解密

在 Spring Boot 中集成 Jasypt

  1. 添加 Jasypt 依赖
    在 pom.xml 文件中添加 Jasypt 依赖:
    下面展示一些 内联代码片
<!--jasypt 数据库加密-->
<dependency>
	 <groupId>com.github.ulisesbocchio</groupId>
	 <artifactId>jasypt-spring-boot-starter</artifactId>
	 <version>3.0.3</version>
</dependency>
  1. 生成密文代码工具类
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig;

/**
 * JasyptUtil类用于提供字符串的加密和解密功能
 */
public class JasyptUtil {
    // 定义加密秘钥
    private final static String SECRECT = "KghwgKzLvucm";
    // 定义加密算法
    private final static String ALGORITHM = "PBEWithMD5AndDES";

    /**
     * 加密给定的字符串
     * 
     * @param text 需要加密的字符串
     * @return 加密后的字符串
     */
    public static String encrypt(String text){
        // 创建加密器实例
        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        // 创建配置实例
        EnvironmentPBEConfig config = new EnvironmentPBEConfig();
        // 设置加密算法
        config.setAlgorithm(ALGORITHM);
        // 设置秘钥
        config.setPassword(SECRECT);
        // 应用配置到加密器
        standardPBEStringEncryptor.setConfig(config);
        // 执行加密操作并返回结果
        return standardPBEStringEncryptor.encrypt(text);
    }

    /**
     * 解密给定的字符串
     * 
     * @param text 需要解密的字符串
     * @return 解密后的字符串
     */
    public static String decrypt(String text) {
        // 创建解密器实例
        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        // 创建配置实例
        EnvironmentPBEConfig config = new EnvironmentPBEConfig();
        // 设置解密算法
        config.setAlgorithm(ALGORITHM);
        // 设置秘钥
        config.setPassword(SECRECT);
        // 应用配置到解密器
        standardPBEStringEncryptor.setConfig(config);
        // 执行解密操作并返回结果
        return standardPBEStringEncryptor.decrypt(text);
    }
}
  1. yml加密配置(jasypt配置一定要放最上面)
# jasypt 密码加密配置
jasypt:
  encryptor:
    # 加密盐值(用于加密和解密的密码,需妥善保管,确保安全性)	
    
    password: 
    # 加密算法设置 3.0.0 以后
    algorithm: PBEWithMD5AndDES
    iv-generator-classname: org.jasypt.iv.NoIvGenerator
    
#用官方提供的保留字 ENC,将加密的密码包裹即可    
spring:
  datasource:
    url: ENC(加密后 xxx)
    username: ENC(加密后 xxx)
    password: ENC(加密后 xxx)
    driver-class-name: com.mysql.cj.jdbc.Driver
  1. 运行项目
    在idea中运行,需要通过VM options设置
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值