SpringBoot 配置加密与安全——数据库密码、API 密钥加密

发布时间:2026/7/24 8:38:10
SpringBoot 配置加密与安全——数据库密码、API 密钥加密 生产环境的配置文件里不能明文写密码。Jasypt 可以对数据库密码、API密钥等敏感信息加密启动时自动解密。一、Jasypt 集成dependencygroupIdcom.github.ulisesbocchio/groupIdartifactIdjasypt-spring-boot-starter/artifactIdversion3.0.5/version/dependency二、加密# 命令行加密java-cpjasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI\input123456\passwordmySecretKey\algorithmPBEWithMD5AndDES# 输出O7v7T4H6zXkZp8V3YwA9Bwspring: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){PooledPBEStringEncryptorencryptornewPooledPBEStringEncryptor();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 实战干货不让你白来。