添加类
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;
decryptedValue = AESUtil.decryptFromString(encryptedValue, Mode.CBC, Padding.ZeroPadding);
// 保存需要替换的配置
props.put(propertyName, decryptedValue);
}
}
}
}
// 添加解密后的属性到环境中
if (!props.isEmpty()) {
PropertiesPropertySource pps = new PropertiesPropertySource("decryptedProperties", props);
environment.getPropertySources().addFirst(pps);
}
}
}
自定义加密工具类
public class AESUtil {
/**
* 16字节
*/
private static final String ENCODE_KEY = "1234567812133211";
private static final String IV_KEY = "0000000000088888";
public static void main(String[] args) {
String encryptData = encryptFromString("http://10.243.36.160", Mode.CBC, Padding.ZeroPadding);
System.out.println("加密:" + encryptData);
String decryptData = decryptFromString(encryptData, Mode.CBC, Padding.ZeroPadding);
System.out.println("解密:" + decryptData);
}
public static String encryptFromString(String data, Mode mode, Padding padding) {
AES aes;
if (Mode.CBC == mode) {
aes = new AES(mode, padding,
new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"),
new IvParameterSpec(IV_KEY.getBytes()));
} else {
aes = new AES(mode, padding,
new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"));
}
return aes.encryptBase64(data, StandardCharsets.UTF_8);
}
public static String decryptFromString(String data, Mode mode, Padding padding) {
AES aes;
if (Mode.CBC == mode) {
aes = new AES(mode, padding,
new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"),
new IvParameterSpec(IV_KEY.getBytes()));
} else {
aes = new AES(mode, padding,
new SecretKeySpec(ENCODE_KEY.getBytes(), "AES"));
}
byte[] decryptDataBase64 = aes.decrypt(data);
return new String(decryptDataBase64, StandardCharsets.UTF_8);
}
}
在resources/META-INF下新建文件spring.factories添加配置
org.springframework.boot.env.EnvironmentPostProcessor=\
包路径.DecryptEnvironmentPostProcessor
然后yml中需要加密的配置使用工具类加密后使用
需要加密的参数: ENC(加密后的值)