Springboot配置文件内容加密

 
使用的是jasypt-spring-boot-starter,具体介绍可以参考 https://gitee.com/yangziyi2017/Jasypt-Spring-Boot
 

引入依赖

<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>2.1.0</version>
</dependency>

创建加密工具类

需要创建一个工具类,用于对明文进行加密,获取密文,然后把密文写入到application.yml这样的配置文件中
package com.hikvision.seclab.common.util.encrypt;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
/**
* 使用jasypt对配置文件进行加密的工具
* @author: 2019/11/7 16:47
* @since: 0.0.1-SNAPSHOT
* @modified By:
*/
public class JasyptTool {
    public static void main(String[] a){
        StandardPBEStringEncryptor se = new StandardPBEStringEncryptor();
        se.setPassword("xxx");
        String postgres = se.encrypt("abc123");
        System.out.println(postgres);
    }
}
 
其中有一个设定密码的动作,是设定加密使用的salt,时jasypt组件必选的配置,有些文章中在配置文件中使用jasypt.encryptor.password设置,这样不安全,别人拿到salt,使用jasypt可以直接解密配置文件中的密文。
 

修改配置文件

 
获取密文后,修改配置文件
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql:
spring.datasource.username=pg_name
spring.datasource.password=ENC(t78dKQb1viAT2QKDxxeerdaNm6wyDCJ)
spring.datasource.initialization-mode=always

设置jasypt.encryptor.password

开发环境

可以通过配置jvm启动参数来指定jasypt.encryptor.password的值
 

生产环境

可以在启动时,设定在启动参数中
  java -Dfile.encoding=UTF8 -Djasypt.encryptor.password=e9fbdb2d3b21 -jar -Xmx512m xxxDemo.jar 
在docker容器中密文的密码可以设置成环境变量(如:JASYPT_PASSWORD ),上述命令可以修改为:
   java -Dfile.encoding=UTF8 -Djasypt.encryptor.password=${JASYPT_PASSWORD} -jar -Xmx512m settlement.jar 

相关文章

Spring Boot 配置项加密 ( https://www.jianshu.com/p/0cd357faf004)
 
 

猜你喜欢

转载自www.cnblogs.com/donfaquir/p/11814127.html