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 配置文件这样加密,才足够安全!

相关推荐
Lyyaoo.10 小时前
Spring Boot Validation 声明式参数校验
spring boot·后端·mysql
Rain的Java大神之路10 小时前
介绍一下分布式事务
java·分布式·后端·spring·spring cloud·架构·springcloud
南城以南溫暖如初14711 小时前
外卖CPS实战指南:从技术选型到运营落地全流程解析
java·spring boot·mysql·架构·vue
paopaokaka_luck19 小时前
基于springboot3+vue3的文山民族文化资源展示与推广平台(协同过滤算法、Echarts 图形化分析)
java·前端·spring boot·学习·echarts
wno70419 小时前
使用Spring Boot发送邮件
数据库·spring boot·后端
刀锋000120 小时前
Java 工程师转 AI Agent 最短路径:用 Spring 的思维理解 Spring AI 2.0(附 LangChain4j 对照)
java·人工智能·spring boot·spring·ai agent
尚可签20 小时前
基于 Spring Boot + Vue 的 AI 智能在线订餐系统
vue.js·人工智能·spring boot
软件开发JR21 小时前
基于Web的足球青训俱乐部管理后台系统的设计与开发
java·前端·spring boot·毕业设计
凤山老林21 小时前
基于 Spring Batch 的海量数据迁移与批处理架构:分片、容错与断点续跑
java·spring boot·spring·架构·spring batch
gis开发之家1 天前
Spring Boot 4 深度解析——参数接收大全:@RequestParam、@PathVariable、@RequestBody
java·spring boot·后端·spring