SpringBoot 配置加密与安全——数据库密码、API 密钥加密
📅 2026/7/24 8:52:54
👁️ 阅读次数
📝 编程学习
生产环境的配置文件里不能明文写密码。Jasypt 可以对数据库密码、API密钥等敏感信息加密,启动时自动解密。
一、Jasypt 集成
<dependency><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-spring-boot-starter</artifactId><version>3.0.5</version></dependency>二、加密
# 命令行加密java-cpjasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI\input="123456"\password=mySecretKey\algorithm=PBEWithMD5AndDES# 输出:O7v7T4H6zXkZp8V3YwA9Bw==spring:datasource:password:ENC(O7v7T4H6zXkZp8V3YwA9Bw==)三、启动
# 密钥通过环境变量传入,不写在配置里java-jarapp.jar--jasypt.encryptor.password=${JASYPT_PASSWORD}四、多环境配置
# application-dev.yml(开发环境不用加密)spring:datasource:password:123456# application-prod.yml(生产环境加密)spring:datasource:password:ENC(O7v7T4H6zXkZp8V3YwA9Bw==)五、自定义加密器
@ConfigurationpublicclassJasyptConfig{@Bean("jasyptStringEncryptor")publicStringEncryptorstringEncryptor(@Value("${jasypt.encryptor.password}")Stringpassword){PooledPBEStringEncryptorencryptor=newPooledPBEStringEncryptor();encryptor.setPassword(password);encryptor.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");encryptor.setKeyObtentionIterations(1000);encryptor.setPoolSize(4);returnencryptor;}}六、注意事项
# 1. 加密密钥不要写进配置文件# 通过环境变量传入:${JASYPT_PASSWORD}# 2. 生产环境建议使用专门的密钥管理服务# HashiCorp Vault、阿里云 KMS 等# 3. 定期更换加密密钥# 更换后要重新生成所有密文💡 觉得有用的话,点赞 + 关注【张老师技术栈】吧!每周更新 Java/Python/MySQL 实战干货,不让你白来。
编程学习
技术分享
实战经验