springboot 配置文件明文加解密

先引入jar依赖

    com.github.ulisesbocchio
    jasypt-spring-boot-starter
    1.14


    com.github.ulisesbocchio
    jasypt-spring-boot
    1.14

application.yml文件配置如下参数
jasypt:
  encryptor:
    password: 123456

编写测试类生成加密文件
 
  

import com.fasterxml.jackson.databind.deser.Deserializers;
import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties;
import org.jasypt.encryption.StringEncryptor;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@EnableEncryptableProperties
@SpringBootTest(classes=Deserializers.Base.class)
@RunWith(SpringRunner.class)
public class Test {
    @Autowired
    StringEncryptor stringEncryptor;//密码解码器注入

    @org.junit.Test
    public void test() {
        System.out.println("生成加密后的数据库用户名:"+stringEncryptor.encrypt("root"));
        System.out.println("生成加密后的数据库密码:"+stringEncryptor.encrypt("root"));
    }
}

启动项目后控制台输出:


之后将
数据库密码参数spring.datasource.username=root
配置为生成后的spring.datasource.username=ENC(jAddU0hDWFmN0V+9T6g65g)
数据库密码参数spring.datasource.password=root
配置为生成后的  spring.datasource.password=ENC( jquUppb2TyAUvIPUKLmkHw )
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/Test?useUnicode=true&characterEncoding=UTF-8
    username: ENC(jAddU0hDWFmN0V+9T6g65g==)
    password: ENC(jquUppb2TyAUvIPUKLmkHw==)
    driver-class-name: com.mysql.jdbc.Driver
 
  

@Value(“$(参数名)”)获取到的内容就是我们解密之后的内容。
使用jasypt框架处理配置文件参数加密的功能就OK啦


import com.fasterxml.jackson.databind.deser.Deserializers ;
import com.ulisesbocchio.jasyptspringboot.annotation. EnableEncryptableProperties ;
import org.jasypt.encryption.StringEncryptor ;
import org.junit.runner. RunWith ;
import org.springframework.beans.factory.annotation. Autowired ;
import org.springframework.beans.factory.annotation. Value ;
import org.springframework.boot.test.context. SpringBootTest ;
import org.springframework.test.context.junit4.SpringRunner ;

@EnableEncryptableProperties
@SpringBootTest( classes=Deserializers.Base. class)
@RunWith(SpringRunner. class)
public class Test {
    @Autowired
    StringEncryptor  stringEncryptor ; //密码解码器注入

    @Value( "${spring.datasource.password}")
    private String  password ;

    @Value( "${spring.datasource.username}")
    private String  username ;

    @org.junit.Test
    public void  test() {
        System. out.println( "解密后的数据库用户名:" username) ;
        System. out.println( "解密后的数据库密码:" password) ;
    }
}

你可能感兴趣的:(springboot,配置文件明文加解密,springboot)