目录

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

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

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

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

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 启动项目,访问忌口

https://i-blog.csdnimg.cn/blog_migrate/f4f5b1aa79f285164c23ee4ce6c6d8c7.png

6 将密钥放到启动命令中

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

https://i-blog.csdnimg.cn/blog_migrate/cb2b9a1238c56113100cefe528c3daba.png

测试效果:

https://i-blog.csdnimg.cn/blog_migrate/3dec9249b56c1f843f04225c71334e53.png

3 总结

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