网站构架怎么做,桂林漓江阳朔,手机网站制作服务机构,wordpress动画插件下载springboot 的yaml配置文件加密 一、采用yaml 插件加密添加依赖创建启动类配置加密密钥加密需要加密的内容用过测试类编写加密的YAML配置解密配置可选#xff1a;自定义配置扩展#xff1a;修改ENC() 一、采用yaml 插件加密
使用Jasypt对Spring Boot的YAML配置文件进行加密是… springboot 的yaml配置文件加密 一、采用yaml 插件加密添加依赖创建启动类配置加密密钥加密需要加密的内容用过测试类编写加密的YAML配置解密配置可选自定义配置扩展修改ENC() 一、采用yaml 插件加密
使用Jasypt对Spring Boot的YAML配置文件进行加密是一种保护敏感信息如数据库密码、API密钥等的有效方法。JasyptJava Simplified Encryption是一个Java加密工具库它提供了一种简单的方式来实现文本的加密和解密。下面是如何在Spring Boot项目中集成Jasypt并加密YAML配置的步骤
添加依赖
首先在你的pom.xml或build.gradle文件中添加Jasypt Spring Boot Starter的依赖。 !-- jasypt加密依赖--dependencygroupIdcom.github.ulisesbocchio/groupIdartifactIdjasypt-spring-boot-starter/artifactIdversion3.0.5/version/dependencyimplementation 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_PASSWORDmySuperSecretKey# 或者作为Java启动参数
-Djasypt.encryptor.passwordmySuperSecretKey或者 直接配置到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应用中的敏感配置信息确保即使配置文件被不当访问关键数据也是加密的提高了应用的安全性。记得妥善保管加密密钥并遵循安全最佳实践。