SpringBoot配置文件加密之Jasypt

在一个springboot项目之,经常会看到application.properties文件中的这样一段:

username=ENC(dflea9KKz/RYb148NaXoi0zM3Og+fi8FtDYPkajVYC+jfrEN6LMkzdKSHbnAGkXX)
password=ENC(XwE1EPLZ9plVqQKXvgVROmJSiTcONzs9hnOVJjsW4iBntTsj+HXLmXy+WzqCo+Wf)

这就是使用Jasypt加密算法进行加密了,具体操作如下
1、引入依赖

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

2、编写一个单元测试,用于获取加密后的账号和密码
StringEncryptor是jasypt-spring-boot-starter自动配置的加密工具,加密算法我们选择PBEWithHmacSHA512AndAES_128,password为123abc

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    private StringEncryptor stringEncryptor;

    @Test
    void contextLoads() {
        String user = stringEncryptor.encrypt("caojia");
        String pass = stringEncryptor.encrypt("123456@a");
        System.out.println(user);
        System.out.println(pass);
        System.out.println(stringEncryptor.decrypt("daNEGV5NmQNIsZ3+RRlcK5ivSdn8Oc82P9sb7r34ilzixjfaFYCSZbDXvXmCveXl"));
    }
}

3、在application.properties文件中配置

jasypt.encryptor.password=123456@a
jasypt.encryptor.algorithm=PBEWithHmacSHA512AndAES_128
username=ENC(QrIizhjBIOEppZJmgoCOsD3z1N34nt45rmNSh0ZcR7/O7+dAbrONvyan4R2w/T1q)
password=ENC(daNEGV5NmQNIsZ3+RRlcK5ivSdn8Oc82P9sb7r34ilzixjfaFYCSZbDXvXmCveXl)

你可能感兴趣的:(spring,boot,java)