Spring Boot中配置文件中关于数据库访问密码参数属性使用jasypt进行加密

原文地址:http://www.glxxw2018.com/study/blog/detail/XFMHwObsii.html

strive基础开发框架-一个基于SpringBoot2的配置学习框架,码云开源地址:https://gitee.com/zxstrive/strive

strive框架是使用c3p0连接池的,所以数据访问参数是配置在c3p0,properties文件中的。c3p0配置文件中的数据库的用户名与密码使用了密文形式,使用的是jasypt加密方式。

c3p0配置文件如下:

#数据库连接
c3p0.jdbcUrl=jdbc:h2:~/strive
c3p0.user=ENC(uL9MVZj9gBYd2G55orntDg==)
c3p0.password=ENC(FAGTEX6gL3MycWYtpoRd8A==)
c3p0.driverClass=org.h2.Driver
c3p0.minPoolSize=2
c3p0.maxPoolSize=10
c3p0.maxIdleTime=1800000
c3p0.acquireIncrement=3
c3p0.maxStatements=1000
c3p0.initialPoolSize=3
c3p0.idleConnectionTestPeriod=60
c3p0.acquireRetryAttempts=30
c3p0.acquireRetryDelay=1000
c3p0.breakAfterAcquireFailure=false
c3p0.testConnectionOnCheckout=false

这里可以看到user与password使用了密文形式。

在Spring Boot的Maven或Gradle文件中加入jasypt相关jar引用,Strive框架使用Gradle如下:

implementation('com.github.ulisesbocchio:jasypt-spring-boot-starter:2.1.0')

在application.yml中加入以下配置:

# jasypt 数据库用户名与密码加密
jasypt:
  encryptor:
    password: EbfYkitulv73I2p0mXI50JMXoaxZTKJ7

上面的password可以写一个32位随机串。

这些配置完成后,可以写一个测试计算明文的密文,并写在c3p0.properties中,注意密文要加上ENC(),这样Spring Boot在构建数据源时,就会自动进行解密,这样就能保护数据库的密码不被他人看到。

生成密文的测试代码如下:

package com.fight.strive.sys.test;


import org.jasypt.encryption.StringEncryptor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class StringEncryptorTests {

    @Autowired
    private StringEncryptor encryptor;

    /**
     * 测试获取配置文件中加密后的用户名与密码的密文
     */
    @Test
    public void testGetEncryptorInfo() {
        String username = encryptor.encrypt("sa");
        String password = encryptor.encrypt("");
        System.out.println("username: " + username);
        System.out.println("password: " + password);
    }

}

c3p0连接池的配置参见:http://www.glxxw2018.com/study/blog/detail/3X64chp8mC.html

更多IT技术资源:http://www.glxxw2018.com

猜你喜欢

转载自blog.csdn.net/zxstrive/article/details/87854838