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())的安全至关重要,不要将其暴露在不安全的环境中。

相关推荐
難釋懷17 小时前
初识Caffeine
java·缓存
big_rabbit050217 小时前
java面试题整理
java·开发语言
Darren24517 小时前
JUnit 5 + Mockito 终极实战笔记
后端
刺客xs17 小时前
c++模板
java·开发语言·c++
苏三说技术17 小时前
AI中四种向量数据库
后端
C+-C资深大佬18 小时前
C++ 性能优化 专业详解
java·c++·性能优化
程序员老乔18 小时前
Java 新纪元 — JDK 25 + Spring Boot 4 全栈实战(三):虚拟线程2.0,电商秒杀场景下的并发革命
java·开发语言·spring boot
weixin_4041576818 小时前
Java高级面试与工程实践问题集(四)
java·开发语言·面试
cyforkk18 小时前
Spring AOP 核心揭秘:ProceedingJoinPoint 与反射机制详解
java·python·spring
无限进步_18 小时前
【C++】单词反转算法详解:原地操作与边界处理
java·开发语言·c++·git·算法·github·visual studio