SpringBoot使用除了Jasypt对YML文件配置内容进行加密方式
作者:℡才知道
文章介绍了如何在Java项目中使用Jasypt进行加密和解密,包括在pom.xml中添加依赖、在application.yml中配置信息、创建解密Bean以及确保秘钥和算法的一致性
1. 在pom.xml中添加Jasypt依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>>
2. 加密算法
// 1. 创建对象
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
// 2. 加密配置
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
// 秘钥
config.setPassword("your-secret-key");
// 3. 加密算法,需要与解密算法一致
config.setAlgorithm("PBEWithMD5AndDES");
// 为减少配置文件的书写,以下都是 Jasyp 3.x 版本,配置文件默认配置
config.setKeyObtentionIterations( "1000");
config.setPoolSize("1");
config.setProviderName("JC");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setIvGeneratorClassName("org.jasypt.iv.NoIvGenerator");
config.setStringOutputType("base64");
encryptor.setConfig(config);
//需要加密的字符串
System.out.println( encryptor.encrypt("需加密的字符串"));
加密后的字符串

3. 在application.yml中配置加密相关信息
使用ENC(加密字符串)
url: jdbc:mysql://ip:port/test username: root password: ENC(w8bH76qYHSgDuxbwK0HsgPbmWZZMoxyVo0DvkOPSiY4=)
4. 配置的两种方式
配置解密Bean并注入(硬编码) 或 在Yml配置Jasypt(推荐)
4.1.1 配置Bean
@Configuration
@EnableEncryptableProperties
public class CustomEncryptConfig {
@Bean(name = "customStringEncryptor")
public static StringEncryptor stringEncryptor() {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
// 2. 加解密配置
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword("your-secret-key");
// 3. 解密算法,必须与加密算法一致
config.setAlgorithm("PBEWithMD5AndDES");
// 为减少配置文件的书写,以下都是 Jasyp 3.x 版本,配置文件默认配置
config.setKeyObtentionIterations( "1000");
config.setPoolSize("1");
config.setProviderName("JC");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setIvGeneratorClassName("org.jasypt.iv.NoIvGenerator");
config.setStringOutputType("base64");
encryptor.setConfig(config);
return encryptor;
}
}
4.1.2 启动类中配置 jasypt.encryptor.bean
customStringEncryptor为上一步配置的Bean
@SpringBootApplication
public class SpringBootTestApplication
{
public static void main(String[] args)
{
System.setProperty("jasypt.encryptor.bean", "customStringEncryptor");
SpringApplication.run(SnSkApplication.class, args);
}
}
4.2.1 启动类中配置 jasypt.encryptor.bean
customStringEncryptor为上一步配置的Bean
jasypt:
encryptor:
algorithm: PBEWithMD5AndDES //PBEWITHHMACSHA512ANDAES_256更安全
iv-generator-classname: org.jasypt.iv.NoIvGenerator
password: your-secret-key
4.2.2 配置服务器运行参数
java -Xms256M -Xmx256M -jar / java/app.jar --jasypt.encryptor.password=xxxxx
但是如果我们配置了password值,就需要在启动类加上@EnableEncryptableProperties这个注解,用于自动解密。
5. 注意
代码加密时的秘钥和算法必须和配置的相同
1. 必须和在Bean中配置的秘钥和算法 一致对应
2. 必需在Yml中的jasypt.encryptor.password 和 jasypt.encryptor.algorithm 一致对应
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
