p-honggang.li
7 天以前 baac505052a5d9e63536eb7de32ba346d7e98ca7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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;
    }
}