前言
在SpringBoot的配置文件中,有些配置是比较敏感的,例如密码等信息,因此,对这些配置文件加密是很有必要的,下面介绍一种配置加解密的集成方式。
详细操作
Jasypt是SpringBoot项目中常用的配置加解密工具,我们引入asypt-spring-boot-starter依赖
yaml
<!--配置文件加密值自动解密-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
<dependency>
<groupId>org.gm</groupId>
<artifactId>crypto</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
然后定义一个名为jasyptStringEncryptor的bean即可
yaml
package com.example.rocketmq.rocketmq.config;
import com.crypto.sm.SMHelper;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
/**
* 配置解密
*/
@Component("jasyptStringEncryptor")
@ConditionalOnProperty(prefix = "property.encry.enable",name = "enable",havingValue = "true", matchIfMissing = true)
public class PropertyEncryptor implements StringEncryptor {
private final String KEY = "xxxxxxxxx";
@Override
public String encrypt(String s) {
if(s != null) {
return SMHelper.sm4Encrypt(KEY, s);
}
return s;
}
@Override
public String decrypt(String s) {
if(s != null) {
return SMHelper.sm4Decrypt(KEY, s);
}
return s;
}
public static void main(String[] args) {
System.out.println(SMHelper.sm4Encrypt("mHApUC5BL6AEzAr3", "root123"));
}
}
这样,我们使用sm4加密密钥对配置值加密,得到加密串,在配置文件配置xxx=ENC(加密值)即可
工作原理
在Spring Boot启动时,会加载各种PropertySource(包括application.yml、Nacos配置等)。Jasypt会通过一个Bean后置处理器(BeanFactoryPostProcessor)来拦截PropertySource的加载,并将其包装成可解密的PropertySource。当Spring从Environment中获取属性时,如果遇到以ENC(开头和)结尾的属性值,就会调用配置的StringEncryptor的decrypt方法进行解密
