Spring Boot 配置文件加密

方式一:Spring Cloud Config

一、建立config server

1. build.gradle 文件中添加:

yaml 复制代码
plugins {
	id 'java'
	id 'org.springframework.boot' version '2.7.0'
	id 'io.spring.dependency-management' version '1.0.11.RELEASE'
}

ext {
	set('springCloudVersion', "2021.0.8")
}

dependencies {
	implementation 'org.springframework.cloud:spring-cloud-config-server'
	// 不加该依赖无法调用 /encrypt 和 /decrypt 接口:
	implementation 'org.springframework.cloud:spring-cloud-starter-config'
}

dependencyManagement {
	imports {
		mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
	}
}

2. application.yaml 文件中添加:

  • 存放配置文件的git仓库。可以是git remote repo,也可以是local repo(file://...)
yaml 复制代码
spring:
  cloud:
    config:
      server:
        git:
          uri: https://gitlab.some.domain/somerepo.git
  • 加解密的密钥
yaml 复制代码
encrypt:
  key: key_instance

3. Application 启动类添加 @EnableConfigServer 注解:

(不加该注解也可实现加解密功能)

java 复制代码
@EnableConfigServer
@SpringBootApplication
public class DemoApplication {
	...
}

二、获得加密后的密文

获得加密后的密文:

bash 复制代码
$ curl http://localhost:8080/encrypt -d id111
7b04915ff83caae96116140fe180be4b9a217fbdaf4c3d38263c2479819d5202

获得解密后的明文:

bash 复制代码
$ curl http://localhost:8080/decrypt -d 7b04915ff83caae96116140fe180be4b9a217fbdaf4c3d38263c2479819d5202
id111

三、将加密后的密文添加进配置文件

application.yaml 文件中添加:

  • 加密后的密文

    yaml 复制代码
    id: '{cipher}7b04915ff83caae96116140fe180be4b9a217fbdaf4c3d38263c2479819d5202'

启动后项目中的id属性会自动解密为"id111"。

Spring Cloud Config 配置的加密解密
分布式配置中心Spring Cloud Config初窥
Spring Cloud Config

SpringCloud与SpringBoot的版本适配

建立 config client:

Spring Cloud Config(统一配置中心服务端和客户端)

方式二:jasypt

【开发经验】springboot配置文件加密详解
SpringBoot 配置文件这样加密,才足够安全!

相关推荐
huipeng9264 小时前
企业级微服务开发实战(二):微服务基础设施搭建与中间件部署
java·redis·mysql·spring cloud·微服务·nacos·rabbitmq
RuoyiOffice5 小时前
2026 企业定制开发选型:从零开发、低代码、SaaS 与 RuoYi Office 怎么选?
spring boot·uni-app·开源·saas·oa·定制化·ruoyioffice
可乐ea5 小时前
【知识获取与分享社区项目 | 项目日记第 24 天】终章总结:从认证、发布、计数、Feed、搜索到 RAG:完整复盘一个知识社区后端系统
java·spring boot·redis·mysql·elasticsearch·ai·kafka
Jabes.yang5 小时前
Java面试实录:AIGC场景下的Stream、微服务、Redis、Kafka与安全实战
java·spring boot·redis·微服务·面试·kafka·aigc
cheems95275 小时前
[开发日记]Spring Boot + MyBatis-Plus 抽奖系统开发复盘:从奖品创建、活动校验到前端圈选人员失效的一次完整排障
前端·spring boot·mybatis
砍材农夫6 小时前
物联网实战:Spring Boot MQTT | 客户端框架比对
spring boot·后端·物联网
>no problem<15 小时前
基于cola5.0的基础设施层的多数据库切换方案思路
数据库·spring boot·mybatisplus·cola5.0·数据库迁移适配
心之伊始16 小时前
Java 后端接入大模型:从 Token、并发到推理成本的完整估算方法
java·spring boot·性能优化·大模型·llm
Dr_eamboat18 小时前
SpringBoot策略模式+工厂模式实战解析
linux·spring boot·策略模式
☆cwlulu18 小时前
Linux系统调用与C库I/O的底层奥秘
java·spring boot·spring