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

相关推荐
希望永不加班21 分钟前
SpringBoot 整合 RabbitMQ 入门
java·spring boot·后端·rabbitmq·java-rabbitmq
我登哥MVP1 小时前
【SpringMVC笔记】 - 12 - 全注解开发
java·spring boot·笔记·spring·tomcat·intellij-idea
阿丰资源1 小时前
基于SpringBoot的高校心理教育辅导系统(附源码+数据库+文档)
数据库·spring boot·后端
卷毛的技术笔记1 小时前
告别“盲猜式”排障:分布式链路追踪方案选型与Spring Boot 3实战
java·spring boot·分布式·后端·spring·面试·系统架构
huipeng9262 小时前
分布式服务部署详解
java·开发语言·spring cloud·微服务
皮皮林55112 小时前
SpringBoot + Disruptor 实现特快高并发处理,支撑每秒 600 万订单无压力!
spring boot
阿丰资源13 小时前
基于SpringBoot的在线视频教育平台的设计与实现(附源码+数据库+文档,一键运行)
数据库·spring boot·后端
苍煜13 小时前
ThreadPoolExecutor线程池终极全解:同步异步判定+SpringBoot生产实战
java·开发语言·spring boot
阿丰资源20 小时前
基于SpringBoot的房产销售系统设计与实现(附源码+数据库+文档,一键运行)
数据库·spring boot·后端