当前位置:   article > 正文

Jasypt对配置文件加密_jasypt加密配置文件

jasypt加密配置文件

Jasypt(Java Simplified Encryption)是一个用于加密配置文件中敏感数据的库,特别适用于Spring应用。它提供了简单易用的API来加密和解密配置属性。

1. 添加Jasypt依赖

在Maven项目中,您需要在pom.xml文件中添加Jasypt的依赖

  1. <dependency>
  2. <groupId>com.github.ulisesbocchio</groupId>
  3. <artifactId>jasypt-spring-boot-starter</artifactId>
  4. <version>3.0.4</version>
  5. </dependency>

2. 配置Jasypt加密密码

application.propertiesapplication.yml文件中,添加用于解密的密码

jasypt.encryptor.password=your_secret_password

3. 加密敏感数据

使用Jasypt命令行工具或Java程序加密敏感数据。以下是使用Jasypt命令行工具加密字符串。

 java -cp jasypt-spring-boot-3.0.4.jar com.ulisesbocchio.jasyptspringboot.cli.JasyptEncryptorCLI input="your_sensitive_data" password="your_secret_password"

命令行工具会输出加密后的数据。

ENC(YOUR_ENCRYPTED_DATA)

 4. 在配置文件中使用加密数据

将加密后的数据放入配置文件中,并用ENC(...)格式包裹,如:

  1. spring.datasource.username=ENC(YOUR_ENCRYPTED_USERNAME)
  2. spring.datasource.password=ENC(YOUR_ENCRYPTED_PASSWORD)

5. 配置解密器

在Spring Boot应用的启动类或配置类中,配置Jasypt加密器:

  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.jasypt.encryption.StringEncryptor;
  4. import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
  5. import org.jasypt.spring31.properties.EncryptablePropertySourcesPlaceholderConfigurer;
  6. @Configuration
  7. public class JasyptConfig {
  8. @Bean("jasyptStringEncryptor")
  9. public StringEncryptor stringEncryptor() {
  10. StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
  11. encryptor.setPassword("your_secret_password"); // 设置加密密码
  12. return encryptor;
  13. }
  14. @Bean
  15. public static EncryptablePropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
  16. return new EncryptablePropertySourcesPlaceholderConfigurer();
  17. }
  18. }

6. 启动应用

启动Spring Boot应用时,Jasypt将自动解密application.propertiesapplication.yml文件中使用ENC(...)格式包裹的加密数据。

总结

通过上述步骤,您可以在Spring Boot项目中使用Jasypt对配置文件中的敏感数据进行加密和解密。这样可以有效保护敏感信息,如数据库用户名和密码等,防止这些信息被直接暴露在配置文件中。

具体可参考官网Jasypt: Java simplified encryption - Jasypt: Java simplified encryption - Main

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/酷酷是懒虫/article/detail/984695
推荐阅读
相关标签
  

闽ICP备14008679号