springboot配置jasypt实现对配置文件敏感信息加密全流程详解

1、引入依赖
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>3.0.4</version>
</dependency>
2、对信息加密 —以mysql数据库密码为例

写一个main方法或者测试方法:

  1. 设置随机盐及加密算法
  2. 对mysql数据库密码加密
  3. 得到加密后的密文,并记录
public static void main(String[] args) {
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        // 设置密钥/随机盐
        config.setPassword("123456");
        // 设置加密方法
        config.setAlgorithm("PBEWithMD5AndDES");
        encryptor.setConfig(config);
        // 加密数据
        String encryptStr = encryptor.encrypt("mysql数据库密码");
        //每次执行得到加密结果不同,但解密结果都一样
        System.out.println(encryptStr);
        // 解密
        System.out.println(encryptor.decrypt(encryptStr));
    }

在这里插入图片描述

3、修改配置文件

spring.datasource.password以密文形式进行配置:ENC(密文数据)

spring:
  datasource:
    username: root
    password: ENC(OS40I92MLgDJy3d4A7905wyzrFPI5v4Vt5Zr7RwxsvQ=)  //上一步得到的密文密码
    url: jdbc:mysql://127.0.0.1:3306/table?serverTimezone=GMT%2B8
jasypt:
  encryptor:
    algorithm: PBEWithMD5AndDES  //上一步用的加密算法
    password: 123456             //上一步用的随机盐,这里(自测时)先写上,项目正式部署时去掉
4、启动项目查看数据库是否正常访问

上来一个ERROR。。。

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to bind properties under 'spring.datasource.password' to java.lang.String:

    Reason: Failed to bind properties under 'spring.datasource.password' to java.lang.String

Action:

Update your application's configuration

原因是:引入的jasypt依赖3.0.4版本问题,新版本加密算法升级,需加入iv-generator-classname: org.jasypt.iv.NoIvGenerator,或者退回3.0.0以下版本
在这里插入图片描述
重新启动正常运行,数据库正常访问

5、启动传参形式加入随机盐

经过上述测试后,就可以把jasypt.encryptor.password: 123456配置项去掉了。因为随机盐是不能暴露在配置文件中的,否则加密就无意义了。注释掉该项配置,然后项目启动时传入相应参数。
在这里插入图片描述
mvn命令启动项目时加入jasypt.encryptor.password=123456随机盐配置:mvn spring-boot:run -Dspring-boot.run.arguments=--jasypt.encryptor.password=123456 (pom中需spring-boot-maven-plugin插件)
在这里插入图片描述
启动成功,数据库正常访问!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值