spring + jasypt对明文密码加密
在 Spring 项目中,你可以使用 Jasypt(Java Simplified Encryption)来加密和解密配置文件中的敏感信息(如数据库密码、API 密钥等)。这样做能在代码库中保护这些敏感数据,即使有人无意中查看了配置文件,也无法直接获得明文密码。
背景
由于严格的安全要求,配置文件中不得包含明文密码。这是为了防止敏感数据暴露,确保系统的安全性和数据的完整性。应使用加密技术或安全的外部化配置管理工具来保护这些敏感信息,防止未经授权的访问。
添加依赖修改pom文件
需要在你的项目中添加 Jasypt 的依赖。在 Maven 项目中,你可以在 pom.xml
中添加以下依赖:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
使 Jasypt 自动解密
代码主类APP加上注解自动解析,确保你添加了注解配置,使 Jasypt 自动解密注入的密码: @EnableEncryptableProperties
@SpringBootApplication
@EnableEncryptableProperties
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
修改配置文件配置 Jasypt 属性加密器
在 application.yml
或 application.properties
中添加 Jasypt 的配置:
jasypt:
encryptor:
password: datakey
algorithm: PBEWithMD5AndTripleDES
iv-generator-classname: org.jasypt.iv.NoIvGenerator
property:
prefix:ENC(
suffix:)
spring: #springboot的配置
datasource: #定义数据源
username: data
password: ENC(bktvhR3fBvYQsFT9Tj5O9w==)
url: jdbc:mysql://10.1.251.126:3306/data_pro?useSSL=false&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.jdbc.Driver
加密敏感数据
使用 Jasypt 提供的命令行工具或在代码中加密你的敏感数据。
#添加jasypt加密 input是加密的内容 password是秘钥 algorithm是salt 也可使用在线https://new.lxc1314.xyz/public/json
#加密libs下java -cp ./jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI password=datakey algorithm=PBEWITHMD5ANDDES input=1qazQAZ
#解密 java -cp ./jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI password=dataoskey algorithm=PBEWITHMD5ANDDES input=L2KQxWEKa/pT6AxH5Vm9mQ==
jasypt.encryptor.algorithm=PBEWITHMD5ANDDES
jasypt.encryptor.password=datakey
jasypt.encryptor.iv-generator-classname=org.jasypt.iv.NoIvGenerator
jasypt.encryptor.property.prefix=ENC(
jasypt.encryptor.property.suffix=)
获取加密密码
#加密libs下java -cp ./jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI password=datakey algorithm=PBEWITHMD5ANDDES input=1qazQAZ
#解密 java -cp ./jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI password=dataoskey algorithm=PBEWITHMD5ANDDES input=L2KQxWEKa/pT6AxH5Vm9mQ==
或者从在线网页获取
进阶配置
你可以进一步定制你的 Jasypt 配置,例如自定义加密器等:
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JasyptConfig {
@Bean("jasyptStringEncryptor")
public StringEncryptor stringEncryptor() {
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("secret-password"); // 使用环境变量或者更安全的方式
encryptor.setAlgorithm("PBEWithMD5AndDES");
return encryptor;
}
}
总结
通过在 Spring 项目中使用 Jasypt,可以有效地保护配置文件中的敏感数据。配置步骤包括添加依赖、设置加密参数、加密敏感数据和自动解密敏感数据。在生产环境中,一定要使用安全的方式管理和存储主密码(如使用环境变量或密钥管理服务)。