赞
踩
Jasypt(Java Simplified Encryption)是一个用于加密配置文件中敏感数据的库,特别适用于Spring应用。它提供了简单易用的API来加密和解密配置属性。
在Maven项目中,您需要在pom.xml
文件中添加Jasypt的依赖
- <dependency>
- <groupId>com.github.ulisesbocchio</groupId>
- <artifactId>jasypt-spring-boot-starter</artifactId>
- <version>3.0.4</version>
- </dependency>
在application.properties
或application.yml
文件中,添加用于解密的密码
jasypt.encryptor.password=your_secret_password
使用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)
将加密后的数据放入配置文件中,并用ENC(...)
格式包裹,如:
- spring.datasource.username=ENC(YOUR_ENCRYPTED_USERNAME)
- spring.datasource.password=ENC(YOUR_ENCRYPTED_PASSWORD)
在Spring Boot应用的启动类或配置类中,配置Jasypt加密器:
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.jasypt.encryption.StringEncryptor;
- import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
- import org.jasypt.spring31.properties.EncryptablePropertySourcesPlaceholderConfigurer;
-
- @Configuration
- public class JasyptConfig {
-
- @Bean("jasyptStringEncryptor")
- public StringEncryptor stringEncryptor() {
- StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
- encryptor.setPassword("your_secret_password"); // 设置加密密码
- return encryptor;
- }
-
- @Bean
- public static EncryptablePropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
- return new EncryptablePropertySourcesPlaceholderConfigurer();
- }
- }

启动Spring Boot应用时,Jasypt将自动解密application.properties
或application.yml
文件中使用ENC(...)
格式包裹的加密数据。
通过上述步骤,您可以在Spring Boot项目中使用Jasypt对配置文件中的敏感数据进行加密和解密。这样可以有效保护敏感信息,如数据库用户名和密码等,防止这些信息被直接暴露在配置文件中。
具体可参考官网Jasypt: Java simplified encryption - Jasypt: Java simplified encryption - Main
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。