|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+package com.huimv.employment.config;
|
|
|
2
|
+
|
|
|
3
|
+import com.alibaba.druid.filter.config.ConfigTools;
|
|
|
4
|
+import org.springframework.boot.SpringApplication;
|
|
|
5
|
+import org.springframework.boot.env.EnvironmentPostProcessor;
|
|
|
6
|
+import org.springframework.core.Ordered;
|
|
|
7
|
+import org.springframework.core.env.ConfigurableEnvironment;
|
|
|
8
|
+import org.springframework.core.env.MapPropertySource;
|
|
|
9
|
+import org.springframework.util.StringUtils;
|
|
|
10
|
+
|
|
|
11
|
+import java.util.HashMap;
|
|
|
12
|
+import java.util.Map;
|
|
|
13
|
+
|
|
|
14
|
+/**
|
|
|
15
|
+ * 使用 Druid {@link ConfigTools} 与 {@code spring.datasource.druid.public-key} 解密 Redis 密码。
|
|
|
16
|
+ * <p>MySQL 密码由 Druid ConfigFilter 在连接池层解密;Redis 需在此提前写入明文到 Environment。</p>
|
|
|
17
|
+ */
|
|
|
18
|
+public class DecryptRedisPasswordEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
|
|
|
19
|
+
|
|
|
20
|
+ private static final String PUBLIC_KEY = "spring.datasource.druid.public-key";
|
|
|
21
|
+ private static final String PUBLIC_KEY_ALT = "spring.datasource.druid.publickey";
|
|
|
22
|
+ private static final String REDIS_PASSWORD = "spring.redis.password";
|
|
|
23
|
+
|
|
|
24
|
+ @Override
|
|
|
25
|
+ public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
|
|
|
26
|
+ String publicKey = resolvePublicKey(environment);
|
|
|
27
|
+ if (!StringUtils.hasText(publicKey)) {
|
|
|
28
|
+ return;
|
|
|
29
|
+ }
|
|
|
30
|
+
|
|
|
31
|
+ Map<String, Object> properties = new HashMap<>(4);
|
|
|
32
|
+ properties.put(PUBLIC_KEY, publicKey);
|
|
|
33
|
+ properties.put(PUBLIC_KEY_ALT, publicKey);
|
|
|
34
|
+
|
|
|
35
|
+ String encryptedPassword = environment.getProperty(REDIS_PASSWORD);
|
|
|
36
|
+ if (StringUtils.hasText(encryptedPassword)) {
|
|
|
37
|
+ try {
|
|
|
38
|
+ properties.put(REDIS_PASSWORD, ConfigTools.decrypt(publicKey, encryptedPassword));
|
|
|
39
|
+ } catch (Exception ex) {
|
|
|
40
|
+ throw new IllegalStateException("Redis 密码解密失败,请检查 public-key 与密文是否匹配", ex);
|
|
|
41
|
+ }
|
|
|
42
|
+ }
|
|
|
43
|
+
|
|
|
44
|
+ environment.getPropertySources().addFirst(
|
|
|
45
|
+ new MapPropertySource("decryptedDruidAndRedisPassword", properties));
|
|
|
46
|
+ }
|
|
|
47
|
+
|
|
|
48
|
+ private static String resolvePublicKey(ConfigurableEnvironment environment) {
|
|
|
49
|
+ String publicKey = environment.getProperty(PUBLIC_KEY);
|
|
|
50
|
+ if (StringUtils.hasText(publicKey)) {
|
|
|
51
|
+ return publicKey;
|
|
|
52
|
+ }
|
|
|
53
|
+ return environment.getProperty(PUBLIC_KEY_ALT);
|
|
|
54
|
+ }
|
|
|
55
|
+
|
|
|
56
|
+ @Override
|
|
|
57
|
+ public int getOrder() {
|
|
|
58
|
+ // 须在 ConfigDataEnvironmentPostProcessor 加载完 application-{profile}.yml 之后再解密
|
|
|
59
|
+ return Ordered.LOWEST_PRECEDENCE;
|
|
|
60
|
+ }
|
|
|
61
|
+}
|