Spring Boot整合Jasypt实现敏感信息加密

精心整理了最新的面试资料和简历模板,有需要的可以自行获取

点击前往百度网盘获取
点击前往夸克网盘获取


Spring Boot整合Jasypt实现敏感信息加密

一、什么是Jasypt?

Jasypt(Java Simplified Encryption)是一个Java加密库,支持对配置文件中的敏感信息(如数据库密码、API密钥等)进行加密/解密。与Spring Boot整合后,可通过注解自动解密配置信息。


二、整合步骤

1. 添加依赖

pom.xml中添加:

<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>3.0.5</version>
</dependency>

2. 配置加密密钥

application.properties中添加:

# 加密密钥(生产环境建议通过环境变量传入)
jasypt.encryptor.password=mySecretKey
# 使用默认的PBEWithMD5AndDES算法
jasypt.encryptor.algorithm=PBEWithMD5AndDES

3. 生成加密值

方式1:使用Java代码
@Autowired
private StringEncryptor encryptor;

public void encrypt() {
    String rawPassword = "your_password";
    String encrypted = encryptor.encrypt(rawPassword);
    System.out.println("Encrypted: " + encrypted);
}
方式2:命令行生成(需先安装Jasypt)
java -cp jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI \
  input="your_password" \
  password=mySecretKey \
  algorithm=PBEWithMD5AndDES

4. 在配置中使用加密值

加密后的值需用ENC()包裹:

spring.datasource.password=ENC(4W2fZVwB5EOQM8h5mu0TDw==)

三、高级配置

1. 自定义加密器

@Bean("jasyptStringEncryptor")
public StringEncryptor stringEncryptor() {
    PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
    SimpleStringPBEConfig config = new SimpleStringPBEConfig();
    config.setPassword("mySecretKey");
    config.setAlgorithm("PBEWithMD5AndTripleDES");
    config.setPoolSize("4");
    encryptor.setConfig(config);
    return encryptor;
}

2. 环境变量传密钥(安全推荐)

启动命令:

java -jar your-app.jar --jasypt.encryptor.password=${JASYPT_PASSWORD}

3. 多环境配置

在不同环境的配置文件中使用不同加密密钥:

# application-prod.properties
jasypt.encryptor.password=prodSecretKey

# application-dev.properties
jasypt.encryptor.password=devSecretKey

四、注意事项

  1. 密钥安全:不要将密钥提交到版本库,建议通过环境变量传递
  2. 加密前缀:默认使用ENC(...),可通过jasypt.encryptor.property.prefix自定义
  3. 算法选择:生产环境建议使用更安全的算法如PBEWITHHMACSHA512ANDAES_256

五、验证配置

启动应用时添加调试参数:

-Djasypt.debug=true

控制台将输出解密后的原始值


总结

通过Jasypt整合Spring Boot,可以:

  • ✅ 实现敏感信息加密存储
  • ✅ 保持原有配置方式的简洁性
  • ✅ 支持多环境不同密钥策略
  • ✅ 无缝集成Spring生态

提示:生产环境建议结合Vault或KMS等专业密钥管理服务,实现更安全的密钥轮换机制。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

嘵奇

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

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

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

打赏作者

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

抵扣说明:

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

余额充值