springboot 的yaml配置文件加密
- 一、采用yaml 插件加密
- 添加依赖
- 创建启动类
- 配置加密密钥
- 加密需要加密的内容用过测试类
- 编写加密的YAML配置
- 解密配置
- 可选:自定义配置
- 扩展:修改ENC()
一、采用yaml 插件加密
使用Jasypt对Spring Boot的YAML配置文件进行加密是一种保护敏感信息(如数据库密码、API密钥等)的有效方法。Jasypt(Java Simplified Encryption)是一个Java加密工具库,它提供了一种简单的方式来实现文本的加密和解密。下面是如何在Spring Boot项目中集成Jasypt并加密YAML配置的步骤:
添加依赖
首先,在你的pom.xml或build.gradle文件中添加Jasypt Spring Boot Starter的依赖。
<!-- jasypt加密依赖--><dependency><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-spring-boot-starter</artifactId><version>3.0.5</version></dependency>
implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.5' // 请检查最新版本
创建启动类
我们需要在启动类上加上一个@EnableEncryptableProperties开启jasypt配置
@SpringBootApplication
@EnableEncryptableProperties
public class FileServerApplication {public static void main(String[] args) {SpringApplication.run(FileServerApplication.class, args);}}
配置加密密钥
你需要设置一个加密密钥(在配置文件中配置jasypt的相关信息,这里我们设置了盐值,这个盐值可以随便写),这个密钥将用于加密和解密配置中的值。可以在环境变量或系统属性中设置jasypt.encryptor.password; 或者配置到application.yml或application.properties中
# 作为环境变量
export JASYPT_ENCRYPTOR_PASSWORD=mySuperSecretKey# 或者作为Java启动参数
-Djasypt.encryptor.password=mySuperSecretKey
或者 直接配置到yaml
jasypt:encryptor:password: 123456 #设置盐值
# property:
# prefix: WWTY( #设置语法前缀 ,默认ENC()
# suffix: ).Z #设置语法后缀
加密需要加密的内容用过测试类
import jakarta.annotation.Resource;
import org.jasypt.encryption.StringEncryptor;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;@SpringBootTest
@RunWith(SpringRunner.class)
class SxxcFileServerApplicationTests {@Resourceprivate StringEncryptor stringEncryptor;@Testpublic void testJasypt(){String encrypt = stringEncryptor.encrypt("myPlainPassword");System.out.println(encrypt);//ZW1wZXJTcGVjUHdhcmQ=}
}
编写加密的YAML配置
在你的application.yml或application.properties中,使用ENC()包裹你想要加密的值。例如,如果你原本有:
spring:datasource:password: myPlainPassword
现在更新为:(替换)
spring:datasource:password: ENC(ZW1wZXJTcGVjUHdhcmQ=) # 这里是加密后的密码
注意:你需要先使用Jasypt提供的命令行工具或API对myPlainPassword进行加密,得到ZW1wZXJTcGVjUHdhcmQ=这样的密文。
解密配置
Jasypt Spring Boot Starter会自动处理加密的配置值,你无需在代码中手动解密。Spring框架会在应用启动时自动将这些加密的值解密为明文,然后注入到相应的bean中。
可选:自定义配置
如果你需要更高级的配置,比如改变加密算法,你可以在application.yml中添加jasypt配置节:
jasypt:encryptor:algorithm: PBEWithMD5AndTripleDES # 默认算法,可根据需要更改iv-generator-classname: org.jasypt.iv.RandomIvGenerator # 初始化向量生成器,默认即可
扩展:修改ENC()
jasypt:encryptor:password: 123123 #设置盐值property:prefix: WWTY( #设置语法前缀suffix: ).Z #设置语法后缀
这样修改后我们用于加密的语法也需要改变,把ENC(加密内容)改为WWTY(加密内容).Z
spring:datasource:url: jdbc://mysql://localhost:3306/springbootdriver-class-name: com.mysql.cj.jdbc.Driverusername: WWTY(BFl1Bpk/BjnLwzrBXWnomw==).Zpassword: WWTY(BFl1Bpk/BjnLwzrBXWnomw==).Z
总结
通过以上步骤,你可以有效地保护Spring Boot应用中的敏感配置信息,确保即使配置文件被不当访问,关键数据也是加密的,提高了应用的安全性。记得妥善保管加密密钥,并遵循安全最佳实践。