springboot整合ENC加密解密

以redis为例,连数据库、连mq操作也一样

步骤 1: 添加Jasypt依赖

在Maven项目的pom.xml中添加如下依赖:

xml 复制代码
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>3.0.4</version> <!-- 版本自己挑 -->
</dependency>

步骤 2: 加密Redis密码

创建个配置类,设置一下加密信息,这里我使用 PooledPBEStringEncryptor类演示:

java 复制代码
@Bean(name = "jasyptStringEncryptor")
public StringEncryptor getStringEncryptor() {
    PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
    SimpleStringPBEConfig config = new SimpleStringPBEConfig();
    config.setPassword("woshimiyao");	// 配置秘钥
    config.setPoolSize("1");
    encryptor.setConfig(config);

    System.out.println("加密后:" + encryptor.encrypt("redismima"));
    
    return encryptor;
}

步骤 3: 在Redis配置中使用加密密码

假如上面控制台输出的结果是:encryptedRedisPwd

然后,在你的Spring Boot应用的配置文件中,像这样配置Redis,使用ENC()包裹加密后的密码:

yml 复制代码
spring:
  redis:
    host: localhost
    port: 6379
    password: ENC(encryptedRedisPwd)

步骤 4: 启动Spring Boot应用

重点:Spring Boot应用启动时,Jasypt的自动配置会自动检测并解密配置中使用ENC()标记的值,因此你不需要在代码中手动解密Redis密码。

注意:加密密钥(上面的config.setPassword())的安全至关重要,不要将其暴露在不安全的环境中。

相关推荐
SXJR1 天前
Spring前置准备(八)——ConfigurableApplicationContext和DefaultListableBeanFactory的区别
java·后端·spring
G探险者1 天前
深入理解 KeepAlive:从 TCP 到连接池再到线程池的多层语义解析
后端
Takklin1 天前
Java 面试笔记:深入理解接口
后端·面试
右子1 天前
理解响应式设计—理念、实践与常见误解
前端·后端·响应式设计
濑户川1 天前
深入理解Django 视图与 URL 路由:从基础到实战
后端·python·django
武子康1 天前
大数据-120 - Flink滑动窗口(Sliding Window)详解:原理、应用场景与实现示例 基于时间驱动&基于事件驱动
大数据·后端·flink
IccBoY1 天前
Java采用easyexcel组件进行excel表格单元格的自动合并
java·开发语言·excel
用户281113022211 天前
分布式事务总结
后端
Hello.Reader1 天前
Flink 广播状态(Broadcast State)实战从原理到落地
java·大数据·flink
xuejianxinokok1 天前
新版本 python 3.14 性能到底如何?
后端·python