Spring Boot 实现配置文件加解密原理
作者:冷冷 发布时间:2023-11-23 17:48:46
背景
接上文《失踪人口回归,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
来源:https://segmentfault.com/a/1190000022809536


猜你喜欢
- 微服务开发中经常有这样的需求,公司自定义了通用的请求头,需要在微服务的调用链中转发,比如在请求头中加入了token,或者某个自定义的信息un
- cookie和session的比较一、对于cookie:①cookie是创建于服务器端②cookie保存在浏览器端③cookie的生命周期可
- 前言在这一节为大家继续带来 Kotlin 中的一些高级的内容:Kotlin 中的 Kotlin 扩 展(Extensions)。Kotlin
- 本文为大家分享了一个满足在线网页交流需求的实例,由于java Socket实现的网页版在线聊天功能,供大家参考,具体内容如下实现步骤:1、使
- 配置文件概述:应用程序配置文件是标准的 XML 文件,XML 标记和属性是区分大小写的。它是可以按需要更改的,开发人员可以使用配置文件来更改
- 前言在之前我们分析 Tomcat catalina.bat 原理解析 时候,我们发现在启动tomcat的参数中存在 -Djava.
- 1. eclipse的git插件安装与配置1.1 git插件安装新版本的eclipse已经自带了GIt了,就不用安装了。老版本的eclips
- 介绍Java状态模式(State Pattern)是一种面向对象的设计模式,它将对象的状态封装成独立的状态对象,并将对象的行为与状态对象解耦
- 学会了技术就要使用,否则很容易忘记,因为自然界压根就不存在什么代码、变量之类的玩意,这都是一些和生活常识格格不入的东西。只能多用多练,形成肌
- 延伸:以后除了可以为实体类注入属性,还可以为配置类注入相关的配置信息1.编写实体类@Component@ConfigurationPrope
- 一.HashMap 和Hashtable 的区别我们先看2个类的定义 public class Hashtable exten
- 这里说是框架,说的大了点,其实没有那么复杂,只是一个容易扩展的基类而已。不过至少算是框架类的代码。package arui; i
- 本文介绍了Spring Boot Admin监控服务上下线邮件通知,分享给大家,具体如下:微服务架构下,服务的数量少则几十,多则上百,对服务
- 之前学习oracle,简单的认为数据库只存在服务器端,学习安卓之后才发现原来android和Ios本身是“携带”数据库的——SQ
- Java.lang 中自带的注解@Override:表示当前的方法定义将覆盖基类的方法。如果你不小心拼写错误,或者方法签名被错误拼写的时候,
- BroadcastReceiver静态注册案例演示,供大家参考,具体内容如下静态注册与动态注册的区别:动态注册:广播 * 可以自由的控制注册
- 一、背景TC 集群具有高可用架构,应用到集群是这样一个间接的关系:应用 -》事务分组 -》TC 集群,应用启动后所指定的事务分组不能变,可通
- 需要注意的一点是,feign好像是无法传递list集合类型的,但是你可以通过传递对象类型,然后在接收方再次将对象装在集合中达到集合传递的效果
- 前言最近在开发项目的时候涉及到复杂的动态条件查询,但是mybaits本身不支持if elseif类似的判断但是我们可以间接通过 chose
- Navigator 的 push 和 pop方法Navigator 导航器的 push 和 pop 方法可以携带参数在页面间传递,其他变形的