Spring Boot 实现配置文件加解密原理
Spring Boot 配置文件加解密原理就这么简单
背景
接上文《失踪人口回归,mybatis-plus 3.3.2 发布》[1] ,提供了一个非常实用的功能 「数据安全保护」 功能,不仅支持数据源的配置加密,对于 spring boot 全局的 yml /properties 文件均可实现敏感信息加密功能,在一定的程度上控制开发人员流动导致敏感信息泄露。
// 数据源敏感信息加密
spring:
datasource:
url: mpw:qRhvCwF4GOqjessEB3G+a5okP+uXXr96wcucn2Pev6BfaoEMZ1gVpPPhdDmjQqoM
password: mpw:Hzy5iliJbwDHhjLs1L0j6w==
username: mpw:Xb+EgsyuYRXw7U7sBJjBpA==
// 数据源敏感信息加密
spring:
redis:
password: mpw:Hzy5iliJbwDHhjLs1L0j6w==
实现原理
我们翻开 spring boot 官方文档,翻到 4.2.6 章节 Spring Boot 不提供对加密属性值的任何内置支持,但是提供修改 Spring 环境中包含的值所必需的扩展点 EnvironmentPostProcessor 允许在应用程序之前操作环境属性值
mybatis-plus 的实现
public class SafetyEncryptProcessor implements EnvironmentPostProcessor {
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
//命令行中获取密钥
String mpwKey = null;
// 返回全部形式的配置源(环境变量、命令行参数、配置文件 ...)
for (PropertySource<?> ps : environment.getPropertySources()) {
// 判断是否需要含有加密密码,没有就直接跳过
if (ps instanceof SimpleCommandLinePropertySource) {
SimpleCommandLinePropertySource source = (SimpleCommandLinePropertySource) ps;
mpwKey = source.getProperty("mpw.key");
break;
}
}
//处理加密内容(获取到原有配置,然后解密放到新的map 里面(key是原有key))
HashMap<String, Object> map = new HashMap<>();
for (PropertySource<?> ps : environment.getPropertySources()) {
if (ps instanceof OriginTrackedMapPropertySource) {
OriginTrackedMapPropertySource source = (OriginTrackedMapPropertySource) ps;
for (String name : source.getPropertyNames()) {
Object value = source.getProperty(name);
if (value instanceof String) {
String str = (String) value;
if (str.startsWith("mpw:")) {
map.put(name, AES.decrypt(str.substring(4), mpwKey));
}
}
}
}
}
// 将解密的数据放入环境变量,并处于第一优先级上 (这里一定要注意,覆盖其他配置)
if (!map.isEmpty()) {
environment.getPropertySources().addFirst(new MapPropertySource("custom-encrypt", map));
}
}
}
如何加载生效
resources/META-INF/spring.factories 配置 SPI
org.springframework.boot.env.EnvironmentPostProcessor=\
com.baomidou.mybatisplus.autoconfigure.SafetyEncryptProcessor
扩展
mybatis-plus 默认是读取启动参数,可以在此处可以根据自己需求修改为更安全的根密钥存储。
读取环境变量
System.getProperty("mpw.key")
远程加载密码服务
// 此处思路,参考 druid ConfigFilter
public Properties loadConfig(String filePath) {
Properties properties = new Properties();
InputStream inStream = null;
try {
boolean xml = false;
if (filePath.startsWith("file://")) {
filePath = filePath.substring("file://".length());
inStream = getFileAsStream(filePath);
xml = filePath.endsWith(".xml");
} else if (filePath.startsWith("http://") || filePath.startsWith("https://")) {
URL url = new URL(filePath);
inStream = url.openStream();
xml = url.getPath().endsWith(".xml");
} else if (filePath.startsWith("classpath:")) {
String resourcePath = filePath.substring("classpath:".length());
inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcePath);
// 在classpath下应该也可以配置xml文件吧?
xml = resourcePath.endsWith(".xml");
} else {
inStream = getFileAsStream(filePath);
xml = filePath.endsWith(".xml");
}
if (inStream == null) {
LOG.error("load config file error, file : " + filePath);
return null;
}
if (xml) {
properties.loadFromXML(inStream);
} else {
properties.load(inStream);
}
return properties;
} catch (Exception ex) {
LOG.error("load config file error, file : " + filePath, ex);
return null;
} finally {
JdbcUtils.close(inStream);
}
}
总结
- 配置文件加解密,是通过自定义扩展 EnvironmentPostProcessor 实现
- 若项目中没有使用最新版本 mybatis-plus ,可以参考如上自己实现,不过我推荐 jasypt-spring-boot-starter[2] ,原理类似实现了一个 EnableEncryptablePropertySourcesPostProcessor ,但是支持的加密方式更多更成熟
- 关于 jasypt 使用可以参考源码: https://gitee.com/log4j/pig
Spring Boot 实现配置文件加解密原理的更多相关文章
- spring boot 多数据源加载原理
git代码:https://gitee.com/wwj912790488/multiple-data-sources DynamicDataSourceAspect切面 必须定义@Order(-10) ...
- Spring Boot源码分析-配置文件加载原理
在Spring Boot源码分析-启动过程中我们进行了启动源码的分析,大致了解了整个Spring Boot的启动过程,具体细节这里不再赘述,感兴趣的同学可以自行阅读.今天让我们继续阅读源码,了解配置文 ...
- 峰哥说技术:06-手撸Spring Boot自定义启动器,解密Spring Boot自动化配置原理
Spring Boot深度课程系列 峰哥说技术—2020庚子年重磅推出.战胜病毒.我们在行动 06 峰哥说技术:手撸Spring Boot自定义启动器,解密Spring Boot自动化配置原理 Sp ...
- Spring Boot面试杀手锏————自动配置原理
转:https://blog.csdn.net/u014745069/article/details/83820511 引言不论在工作中,亦或是求职面试,Spring Boot已经成为我们必知必会的技 ...
- Spring Boot 核心配置文件 bootstrap & application
Spring Boot 核心配置文件 bootstrap & application 1.SpringBoot bootstrap配置文件不生效问题 2.bootstrap/ applicat ...
- Spring Boot的属性加载顺序
伴随着团队的不断壮大,往往不需要开发人员知道测试或者生产环境的全部配置细节,比如数据库密码,帐号信息等.而是希望由运维或者指定的人员去维护配置信息,那么如果要修改某项配置信息,就不得不去修改项 ...
- Spring Boot之配置文件值注入(@ConfigurationProperties)
前言:Spring Boot配置文件值的注入有两种方式,分别是 @ConfigurationProperties @Value 这里我们使用第一种 首先我们创建一个application.yml文件, ...
- Spring cloud config配置文件加密解密
Spring cloud config配置文件加密解密 学习了:http://blog.csdn.net/u010475041/article/details/78110349 学习了:<Spr ...
- Spring Boot 2.x教程-Thymeleaf 原理是什么
layout: post title: Spring Boot 2.x教程-Thymeleaf 原理是什么 categories: SpringBoot description: Spring Boo ...
随机推荐
- 08.手写KNN算法测试
导入库 import numpy as np from sklearn import datasets import matplotlib.pyplot as plt 导入数据 iris = data ...
- JVM Attach实现原理剖析
本文转载自JVM Attach实现原理剖析 前言 本文旨在从理论上分析JVM 在 Linux 环境下 Attach 操作的前因后果,以及 JVM 为此而设计并实现的解决方案,通过本文,我希望能够讲述清 ...
- 关于Java中的对象、类、抽象类、接口、继承之间的联系
关于Java中的对象.类.抽象类.接口.继承之间的联系: 导读: 寒假学习JavaSE基础,其中的概念属实比较多,关联性也比较大,再次将相关的知识点复习一些,并理顺其中的关系. 正文: 举个例子:如果 ...
- CVer想知道的都在这里了,一起分析下《中国计算机视觉人才调研报告》吧!
最近闲来无事,老潘以一名普通算法工程师的角度,结合自身以及周围人的情况,理性也感性地分析一下极市平台前些天发布的2020年度中国计算机视觉人才调研报告. 以下的"计算机视觉人才"简 ...
- vue-axios插件、django-cors插件、及vue如何使用第三方前端样式库:element/jQuery/bootstrap
目录 一.vue的ajax插件:axios 1.安装axios 2.axios参数 二.CORS跨域问题(同源策略) 1.Django解决CORS跨域问题方法 三.前端请求携带参数及Django后台如 ...
- CTS camera的基础操作和debug
手机端 设置永久不锁屏 1 CTS 进入cts目录tools 运行以下命令 ./cts-tradefed adb devices找设备数串 整跑 run cts -m CtsCameraTestCas ...
- 后端程序员之路 4、一种monitor的做法
record_t包含_sum._count._time_stamp._max._min最基础的一条记录,可以用来记录最大值.最小值.计数.总和metric_t含有RECORD_NUM(6)份recor ...
- Lua C++交互 应用实例步骤(UserData使用)
一.配置Lua C++交互环境 1.下载Lua 包环境 地址: https://www.lua.org/download.html ,我们这里用的是5.4.2版本. 2.新建C++ 控制台应用程序 3 ...
- POJ-2516(最小费用最大流+MCMF算法)
Minimum Cost POJ-2516 题意就是有n个商家,有m个供货商,然后有k种商品,题目求的是满足商家的最小花费供货方式. 对于每个种类的商品k,建立一个超级源点和一个超级汇点.每个商家和源 ...
- HDOJ-4081(次小生成树+Prim算法)
Qin Shi Huang's National Road System HDOJ-4081 本题考查的是次小生成树的问题,这里的解决方法就是先使用Prim算法求解最小生成树. 在求解最小生成树的时候 ...