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. Excel和CSV格式文件的不同之处

    来源:https://blog.csdn.net/weixin_39198406/article/details/78705016 1.个人理解:为何选择使用csv来存储接口测试用例相关字段数据,而不 ...

  2. sklearn中的pipeline实际应用

    前面提到,应用sklearn中的pipeline机制的高效性:本文重点讨论pipeline与网格搜索在机器学习实践中的结合运用: 结合管道和网格搜索以调整预处理步骤以及模型参数 一般地,sklearn ...

  3. Python 装饰器原理剖析

    以下内容仅用于帮助个人理解装饰器这个概念,案例可能并不准确. 什么是装饰器? 我们知道iPhone 应用商店中有成千上万的APP,我们也知道苹果系统每年都会大版本更新增加很多新功能.这些功能要想发挥出 ...

  4. Python 股票市场分析实战

    目标: 1.股票数据获取 2.历史趋势分析及可视化 3.风险分析 实验数据:来源于Yahoo Finance / Stooq,该网站提供了很多API接口,本文用的工具是pandas-datareade ...

  5. C语言:贪心算法之装箱问题

    #include <stdio.h> #include <stdlib.h> #define N 6 #define V 100 typedef struct box // 使 ...

  6. Django模型层2

    目录 一.聚合查询 聚合函数 二.分组查询 利用group by进行分组查询 三.F与Q查询 1. F类 2. Q类 四.orm字段及参数 五.自定义char字段 六.orm中的事务操作 1. 什么是 ...

  7. 第47天打卡学习(单例模式 深入了解CAS 原子引用 各种锁的理解)

    18彻底玩转 单例模式 饿汉式 DCL懒汉模式 探究! 饿汉式  package com.kuang.single; //饿汉式单例 //单例模式重要思想是构造器私有 public class Hun ...

  8. 力扣208. 实现 Trie (前缀树)

    原题 以下是我的代码,就是简单的字符串操作,可以ac但背离了题意,我之前没接触过Trie 1 class Trie: 2 3 def __init__(self): 4 ""&qu ...

  9. sqlyog如何增删改查?

    转: sqlyog如何增删改查? 下面是一道完整的 sqlyog 增删改查的练习, 顺着做下去,可以迅速掌握. 1. 创建部门表dept,并插入数据: 2. 创建emp员工表,并插入数据: sql 代 ...

  10. 解决springboot项目打成jar包部署到linux服务器后上传图片无法访问的问题

    前言:目前大三,自己也在学习和摸索的阶段.在和学校的同学一起做前后端分离项目的时候,我们发现将后端打包成jar,然后部署到服务器中通过java -jar xxx.jar运行项目以后,项目中存在文件上传 ...