修改:配置加密&解密密钥初始化方式优化
This commit is contained in:
@@ -1,49 +0,0 @@
|
||||
package com.sdm.performance.config;
|
||||
|
||||
import com.sdm.common.utils.AESUtil;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.env.EnvironmentPostProcessor;
|
||||
import org.springframework.core.env.*;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
@Component
|
||||
public class DecryptEnvironmentPostProcessor implements EnvironmentPostProcessor {
|
||||
@Override
|
||||
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
|
||||
Properties props = new Properties(); // 临时存储需要替换的配置
|
||||
// 假设加密密码前缀为 "ENC(",后缀为 ")"
|
||||
MutablePropertySources propertySources = environment.getPropertySources();
|
||||
for (PropertySource<?> propertySource : propertySources) {
|
||||
if (propertySource instanceof EnumerablePropertySource) {
|
||||
EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource<?>) propertySource;
|
||||
String[] propertyNames = enumerablePropertySource.getPropertyNames();
|
||||
// 遍历所有配置key:value
|
||||
for (String propertyName : propertyNames) {
|
||||
String propertyVal = environment.getProperty(propertyName);
|
||||
// 根据自己写的规则来解析那些配置是需要解密的
|
||||
if (propertyVal != null && propertyVal.startsWith("ENC(") && propertyVal.endsWith(")")) {
|
||||
// 解析得到加密的数据
|
||||
String encryptedValue = propertyVal.substring(4, propertyVal.length() - 1);
|
||||
// 调用自定义工具类解密
|
||||
String decryptedValue = null;
|
||||
try {
|
||||
decryptedValue = AESUtil.decode(encryptedValue);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
// 保存需要替换的配置
|
||||
props.put(propertyName, decryptedValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 添加解密后的属性到环境中
|
||||
if (!props.isEmpty()) {
|
||||
PropertiesPropertySource pps = new PropertiesPropertySource("decryptedProperties", props);
|
||||
environment.getPropertySources().addFirst(pps);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
org.springframework.boot.env.EnvironmentPostProcessor=com.sdm.performance.config.DecryptEnvironmentPostProcessor
|
||||
Reference in New Issue
Block a user