Spring Boot: 加密应用配置文件敏感信息

背景

  1. 咱们的应用以前使用的是Druid数据库链接池,因为需求咱们迁移到HikariCP链接池,druid 数据源加密提供了多种方式:
  • 能够在配置文件my.properties中指定config.decrypt=true
  • 也能够在DruidDataSource的ConnectionProperties中指定config.decrypt=true
  • 也能够在jvm启动参数中指定-Ddruid.config.decrypt=true

可是HikariCP 默认没有提供实现数据源加解密的方法html

  1. 应用中会存在多个须要配置敏感信息(好比stfp等),都须要加密,相似于druid加解密方式依赖于工具类的实现,没有统一的加解密标准,麻烦、并且很差维护。

Spring Cloud Config 的解决方案

  1. Config Server 加解密依赖JDK的JCE。

JDK8的下载地址java

  1. 配置config serve encrypt.key=foo
  2. 使用config server 提供的加解密接口生成密文
curl localhost:4001/encrypt -d lengleng
密文
  1. 配置文件使用密文
spring:
  datasource:
    password: '{ciper}密文'

xxx: '{ciper}密文'
  1. 其余的非对称加密等高级配置,参考官方文档。注意一个bug (No key was installed for encryption service

jasypt 的解决方案

  1. Maven依赖
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>1.16</version>
</dependency>
  1. 配置
jasypt:
  encryptor:
    password: foo #根密码
  1. 调用JAVA API 生成密文
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = PigAdminApplication.class)
public class PigAdminApplicationTest {
    @Autowired
    private StringEncryptor stringEncryptor;

    @Test
    public void testEnvironmentProperties() {
        System.out.println(stringEncryptor.encrypt("lengleng"));
    }

}
  1. 配置文件中使用密文
spring:
  datasource:
    password: ENC(密文)

xxx: ENC(密文)
  1. 其余非对称等高级配置参考git

    Key Required
    jasypt.encryptor.password True 根密码
    jasypt.encryptor.algorithm False PBEWithMD5AndDES
    jasypt.encryptor.keyObtentionIterations False 1000
    jasypt.encryptor.poolSize False 1
    jasypt.encryptor.providerName False SunJCE
    jasypt.encryptor.saltGeneratorClassname False org.jasypt.salt.RandomSaltGenerator
    jasypt.encryptor.stringOutputType False base64
    jasypt.encryptor.proxyPropertySources False false

总结

  1. Spring Cloud Config 提供了统一的加解密方式,方便使用,可是若是应用配置没有走配置中心,那么加解密过滤是无效的;依赖JCE 对于低版本spring cloud的兼容性很差。
  2. jasypt 功能更为强大,支持的加密方式更多,可是若是多个微服务,须要每一个服务模块引入依赖配置,较为麻烦;可是功能强大 、灵活。
  3. 我的选择 jasypt
  4. 源码参考: 基于Spring Cloud、JWT 的微服务权限系统设计
相关文章
相关标签/搜索