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

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

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 总结

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

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值