欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot配置文件加密

程序员文章站 2022-05-12 17:13:45
...

springboot配置文件加密

maven配置

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

重写解密处理类

@Component("encryptablePropertyResolver")
public class BasicEncryptablePropertyResolver implements EncryptablePropertyResolver {
    private final PooledPBEStringEncryptor encryptor;
    /**
     * 标识配置文件中需要解密的值前缀
     */
    private final String prefix = "ENC[";
    /**
     * 标识配置文件中需要解密的值后缀
     */
    private final String suffix = "]";

    public BasicEncryptablePropertyResolver(){
        encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        //加密盐
        config.setPassword("mioto-project");
        config.setAlgorithm("PBEWithMD5AndDES");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
    }

    @Override
    public String resolvePropertyValue(String value) {
        if (value != null && value.startsWith(prefix) && value.endsWith(suffix)) {
            return encryptor.decrypt(value.substring(prefix.length() - 1));
        }
        return value;
    }
}

加解密测试

 

 public static void main(String[] args) {
        BasicEncryptablePropertyResolver encryptablePropertyResolver = new BasicEncryptablePropertyResolver();
        System.out.println(encryptablePropertyResolver.encryptor.encrypt("mioto88888"));
        System.out.println(encryptablePropertyResolver.resolvePropertyValue("mioto[gzhFpmXjYXyITMDOZsCZylyBZuQkylidN/d4BfBu860=]"));
    }

 

编写配置文件需加密属性值

 

spring.datasource.password=ENC[gYwKmL6bj7TSqondKvfnWhC9DYT9IsKvVkpsl+ve6Gw=]

 备注

  1. jasypt每次加密的结果都不相同,但是解密的结果是一致的
  2. 配置需加密的属性值时,将加密后的值放入到prefix和suffix中
  3. 重写的处理类必须为encryptablePropertyResolver