栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

1、引入依赖

    com.github.ulisesbocchio
    jasypt-spring-boot-starter
    3.0.4

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插件)

启动成功,数据库正常访问!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/351185.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号