Spring Boot 配置文件加密

方式一:Spring Cloud Config

一、建立config server

1. build.gradle 文件中添加:
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://…)
spring:
  cloud:
    config:
      server:
        git:
          uri: https://gitlab.some.domain/somerepo.git
  • 加解密的密钥
encrypt:
  key: key_instance
3. Application 启动类添加 @EnableConfigServer 注解:

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

@EnableConfigServer
@SpringBootApplication
public class DemoApplication {
	...
}

二、获得加密后的密文

获得加密后的密文:

$ curl http://localhost:8080/encrypt -d id111
7b04915ff83caae96116140fe180be4b9a217fbdaf4c3d38263c2479819d5202

获得解密后的明文:

$ curl http://localhost:8080/decrypt -d 7b04915ff83caae96116140fe180be4b9a217fbdaf4c3d38263c2479819d5202
id111

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

application.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 配置文件这样加密,才足够安全!
jasypt对springboot配置文件加密解密及在测试加密解密中遇到的坑
云服务器运行报错Value for key ‘PROMPT_COMMAND‘ could not be loaded using ‘com.ulisesbocchio.jasyptspringboot
JASYPT with Spring Boot problem encrypt strong password and using it in the app

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,可以使用加密算法来加密配置文件,以保护敏感信息的安全性。以下是一种常见的加密配置文件的方法: 1. 导入依赖:在`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-crypto</artifactId> </dependency> ``` 2. 创建一个加密/解密工具类:可以使用`TextEncryptor`接口提供的实现类来进行加密和解密操作。例如,可以使用`Jasypt`库提供的实现。 3. 配置加密密钥:在`application.properties`或`application.yml`配置文件中,添加一个密钥属性。例如: ```properties jasypt.encryptor.password=mySecretKey ``` 4. 加密配置信息:可以使用上一步中配置的密钥来加密敏感信息。例如,可以在配置文件中使用`ENC(encryptedValue)`的形式来表示加密后的值。例如: ```properties my.property=ENC(encryptedValue) ``` 5. 解密配置信息:在需要访问敏感信息的地方,可以使用加密/解密工具类来解密配置值。例如,在Spring Boot应用程序中,可以使用`@Value`注解将解密后的值注入到属性中。 ```java @Value("${my.property}") private String myProperty; ``` 这样,敏感信息就会在配置文件中以加密形式存储,并且在应用程序中自动解密以供使用。 请注意,为了确保密钥的安全性,建议将密钥存储在安全的位置,并且不要将明文密钥直接硬编码在代码中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值