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 Cloud 、Spring Security OAuth2的RBAC权限管理系统 欢迎关注

Spring Boot 实现配置文件加解密原理的更多相关文章

  1. spring boot 多数据源加载原理

    git代码:https://gitee.com/wwj912790488/multiple-data-sources DynamicDataSourceAspect切面 必须定义@Order(-10) ...

  2. Spring Boot源码分析-配置文件加载原理

    在Spring Boot源码分析-启动过程中我们进行了启动源码的分析,大致了解了整个Spring Boot的启动过程,具体细节这里不再赘述,感兴趣的同学可以自行阅读.今天让我们继续阅读源码,了解配置文 ...

  3. 峰哥说技术:06-手撸Spring Boot自定义启动器,解密Spring Boot自动化配置原理

    Spring Boot深度课程系列 峰哥说技术—2020庚子年重磅推出.战胜病毒.我们在行动 06  峰哥说技术:手撸Spring Boot自定义启动器,解密Spring Boot自动化配置原理 Sp ...

  4. Spring Boot面试杀手锏————自动配置原理

    转:https://blog.csdn.net/u014745069/article/details/83820511 引言不论在工作中,亦或是求职面试,Spring Boot已经成为我们必知必会的技 ...

  5. Spring Boot 核心配置文件 bootstrap & application

    Spring Boot 核心配置文件 bootstrap & application 1.SpringBoot bootstrap配置文件不生效问题 2.bootstrap/ applicat ...

  6. Spring Boot的属性加载顺序

        伴随着团队的不断壮大,往往不需要开发人员知道测试或者生产环境的全部配置细节,比如数据库密码,帐号信息等.而是希望由运维或者指定的人员去维护配置信息,那么如果要修改某项配置信息,就不得不去修改项 ...

  7. Spring Boot之配置文件值注入(@ConfigurationProperties)

    前言:Spring Boot配置文件值的注入有两种方式,分别是 @ConfigurationProperties @Value 这里我们使用第一种 首先我们创建一个application.yml文件, ...

  8. Spring cloud config配置文件加密解密

    Spring cloud config配置文件加密解密 学习了:http://blog.csdn.net/u010475041/article/details/78110349 学习了:<Spr ...

  9. Spring Boot 2.x教程-Thymeleaf 原理是什么

    layout: post title: Spring Boot 2.x教程-Thymeleaf 原理是什么 categories: SpringBoot description: Spring Boo ...

随机推荐

  1. PHP反序列化字符串逃逸

    通过CTF比赛了解PHP反序列化,记录自己的学习. 借用哈大佬们的名言 任何具有一定结构的数据,如果经过了某些处理而把结构体本身的结构给打乱了,则有可能会产生漏洞. 0CTF 2016piapiapi ...

  2. redis五种数据类型的应用

    redis的五种数据类型和使用场景 string类型 string类型多用于缓存 set key value(value可以为json字符串) setnx多用于分布式锁(后面详细整理) 计数器 inc ...

  3. 微信小程序:post请求参数放在请求体中还是拼接到URL中需要看后台是如何接收的

    前端发送post请求时,请求参数可以放在请求中,代码如下: function post(url, data, callback) { wx.request({ method: 'POST', url: ...

  4. 错误信息:...\output\project.axf: error: l6218e: undefined symbol usart1_confing (referred from main.o).

    说明:此文档知识用来记录,顺便给大家作为参考,如有错误的地方请大家多多指正,在下内心定会感激不尽. 前言:关于这个问题,我曾花了一个下午在网上寻找,网上的说法五花八门,我办法试尽,但遍寻无果.由此我认 ...

  5. 采用lua脚本获取mysql、redis数据以及jwt的校验

    一.安装配置Openresty 1,安装 wget https://openresty.org/download/ngx_openresty-1.9.7.1.tar.gz # 下载 tar xzvf ...

  6. RabbitMQ-RPC版主机管理程序

    一.作业需求 1.可以对指定机器异步的执行多个命令 例子: 请输入操作指令>>>:run ipconfig --host 127.0.0.0 in the call     tack ...

  7. C# 应用 - 使用 HttpWebRequest 发起 Http 请求

    helper 类封装 调用 1. 引用的库类 \Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6\System.dll Syste ...

  8. php-fpm的慢执行日志

    通过慢执行日志,我们可以清晰地了解PHP脚本在哪里执行时间长,可以定位到行 下面介绍如何开启和查看慢执行日志 #vim /usr/local/php-fpm/etc/php-fpm.d/www.con ...

  9. 对话对话每日互动CEO方毅:数据智能应用的过去、现在和未来每日互动CEO方毅:数据智能应用的过去、现在和未来

    2008年,大数据的概念被首次提出,麦肯锡全球研究所给出的定义是:大数据是在一种获取.存储.管理.分析方面大大超出了传统数据库软件工具能力范围的数据集合. 2014年,"数据智能" ...

  10. 题解 洛谷P1990 覆盖墙壁

    DP康复训练题 原题:洛谷P1990 核心:递推/DP 题源应该是铺地砖,所以采用一摸一样的思路,只是有两种不同的方块 我们先用最最简单的方式尝试一下枚举当最后一行被填满的情况: 1.如果我们只用第一 ...