Jasypt(Java Simplified Encryption) 是一个用于在 Java 应用程序中简化加密和解密操作的库。它主要用于保护敏感信息,如数据库密码、API 密钥等。
Jasypt主要功能
-
加密与解密:提供简单的 API 进行数据加密和解密。
-
集成方便:可以轻松集成到 Spring 和 Spring Boot 应用中。
-
支持多种加密算法:包括对称加密(如 AES)、哈希算法等。
-
属性加密:允许在配置文件(如
application.properties或application.yml)中加密敏感属性。
如何在 Spring Boot 项目中集成 Jasypt?
添加依赖
使用 Maven:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot</artifactId>
<version>3.0.4</version>
</dependency>
加密敏感信息
使用 Jasypt 提供的命令行工具或在线工具加密敏感信息。例如,加密数据库密码:
encrypt.bat input="mysecretpassword" password="encryptionkey" algorithm=PBEWithMD5AndDES
配置Jasypt
在 application.properties 或 application.yml 中配置 Jasypt 的加密密钥:
jasypt.encryptor.password=encryptionkey
示例
以下是一个简单的示例,展示如何在 Spring Boot 项目中使用 Jasypt 加密数据库密码。 application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=ENC(wB1V1aKz3Yj...)
jasypt.encryptor.password=mysupersecretkey
不在application.properties中设置jaspyt.encryptor.password
在application.properties或者application.yml中设置password, 仍然不够安全,可在Springboot中配置
@Configuration
@EnableEncryptableProperties
public class JasyptConfig {
@Bean("jasyptStringEncryptor")
public StringEncryptor stringEncryptor() {
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("123456");
encryptor.setAlgorithm("PBEWithMD5AndDES");
return encryptor;
}
}