package com.webmanage.config;
|
|
import com.webmanage.util.AESUtil;
|
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.env.EnvironmentPostProcessor;
|
import org.springframework.core.Ordered;
|
import org.springframework.core.env.ConfigurableEnvironment;
|
import org.springframework.core.env.EnumerablePropertySource;
|
import org.springframework.core.env.MapPropertySource;
|
import org.springframework.core.env.MutablePropertySources;
|
import org.springframework.util.StringUtils;
|
|
import java.util.HashMap;
|
import java.util.Map;
|
|
/**
|
* 在应用启动早期对敏感配置进行解密
|
*/
|
public class EncryptedPropertyEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
|
|
@Override
|
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
|
Map<String, Object> overrides = new HashMap<>();
|
// 扫描所有可枚举属性源,收集以 AES: 开头的属性值并解密,放入最高优先级覆盖源
|
for (org.springframework.core.env.PropertySource<?> ps : environment.getPropertySources()) {
|
if (ps instanceof EnumerablePropertySource) {
|
EnumerablePropertySource<?> eps = (EnumerablePropertySource<?>) ps;
|
for (String name : eps.getPropertyNames()) {
|
Object raw = eps.getProperty(name);
|
if (raw instanceof String) {
|
String value = (String) raw;
|
if (EncryptedPropertyDetector.isEncrypted(value)) {
|
String cipher = EncryptedPropertyDetector.stripPrefix(value);
|
String plain = AESUtil.decryptWithDefaultKey(cipher);
|
overrides.put(name, plain);
|
}
|
}
|
}
|
}
|
}
|
if (!overrides.isEmpty()) {
|
MutablePropertySources sources = environment.getPropertySources();
|
sources.addFirst(new MapPropertySource("decryptedSensitiveProperties", overrides));
|
}
|
}
|
|
// 确保尽早执行
|
@Override
|
public int getOrder() {
|
// 在配置文件加载完成后执行,避免拿不到值
|
return Ordered.LOWEST_PRECEDENCE;
|
}
|
}
|