SpringBoot项目中使用jasypt对配置文件用户名和密码进行加密

一、介绍

在我们项目中不可避免需要配置一些密钥,如:数据库、Redies、邮箱等

为了让配置文件中的账号密码不被别人看到,在开发环境和真实环境中对项目进行配置,我们可以使用jasypt进行加解密库

二、开始使用

1.创建好SpringBoot项目后我们在Maven中添加jasypt的环境依赖

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

2.我们在application.properties或者application.yml中配置加密所需的salt(盐)

# 配置文件项加解密密码,实际使用放在代码中更为安全
jasypt.encryptor.password=you salt

3.我们对密钥进行加密,我创建个测试类,添加测试方法

@Autowired
StringEncryptor stringEncryptor;

@Test
public void encrypt() {
        String username = stringEncryptor.encrypt("root");
        String password = stringEncryptor.encrypt("123");
        System.out.println("username:"+username);
        System.out.println("password:"+password);
}

或者

public static void main(String[] args) {
        
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        //加密所需的salt(盐)
        textEncryptor.setPassword("you salt");

        //要加密的数据(数据库的用户名或密码)
        String username = textEncryptor.encrypt("root");
        String password = textEncryptor.encrypt("123");
        System.out.println("username:"+username);
        System.out.println("password:"+password);
    }

控制台中生成我们加密后的用户名和密码

username:EZCBfKTMb84iOdG32xyz5g==
password:ciciYDDTB0fyIofgZHbvLQ==

4.我们将控制台生成的密钥拷贝到配置文件中,我们加密后的密码需要使用ENC('加密后的密钥')进行包裹起来

# mysql数据库文件进行配置
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    password: ENC(EZCBfKTMb84iOdG32xyz5g==)
    username: ENC(ciciYDDTB0fyIofgZHbvLQ==)

我们启动项目,查询数据库正常,说明我们配置完成了

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值