关于项目中数据库密码加密的使用

306 阅读1分钟

这是我参与8月更文挑战的第15天,活动详情查看:8月更文挑战

因博主最近遇到项目需要将数据库密码使用密文配置,故记录使用过程

1 使用需求

在SpringBoot项目中,数据库的连接信息,都放在application.yml等配置文件中,如直接使用明文密码,数据库信息就可能暴露,所以生产环境的数据库信息需要加密.

2 使用步骤

1 准备一个SpringBoot项目环境

2 添加jasypt的jar包

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

3 创建一个测试类

public class JasyptTest {

	// 加密
    @Test
    public void testEncrypt() throws Exception {
        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        EnvironmentPBEConfig config = new EnvironmentPBEConfig();

        // 加密的算法,这个算法是默认的
        config.setAlgorithm("PBEWithMD5AndDES");
        // 加密的密钥
        config.setPassword("123456");
        standardPBEStringEncryptor.setConfig(config);
        String plainText = "root";
        String encryptedText = standardPBEStringEncryptor.encrypt(plainText);
        System.out.println(encryptedText);
    }

	// 解密
    @Test
    public void testDe() throws Exception {
        StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor();
        EnvironmentPBEConfig config = new EnvironmentPBEConfig();

        // 加密的算法,这个算法是默认的
        config.setAlgorithm("PBEWithMD5AndDES");
        // 加密的密钥
        config.setPassword("123456");
        standardPBEStringEncryptor.setConfig(config);
        String encryptedText = "fWnmlHboGH/GONZXg+84WQ==";
        String plainText = standardPBEStringEncryptor.decrypt(encryptedText);
        System.out.println(plainText);
    }

}

4 修改配置文件

# mysql
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    #MySQL配置
    driverClassName: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: ENC(fWnmlHboGH/GONZXg+84WQ==)
jasypt:
  encryptor:
    password: 123456

5 启动项目,访问忌口

image-20210815221654302

6 将密钥放到启动命令中

注释掉application.yml配置文件中的密钥. 在启动命令行添加-Djasypt.encryptor.password=密钥.

image-20210815222126233

测试效果:

image-20210815222157940

3 总结

关于数据库密码加密功能,在平常开发中,使用较少,但是在生产环境,给数据库密码加密,确实很有必要的.因为项目中最重要的就是数据,所以数据安全,也就成了重中之重.