Spring .properties配置檔案加密
阿新 • • 發佈:2018-12-23
對於儲存在.properties檔案中的敏感資訊,支援採用加密的方式儲存。然後在程式中解密使用。
實現方案
採用自定義PropertySourceLoader的方式,在.properties配置檔案載入期,遍歷值,遇到指定格式的值,則執行解密操作。具體程式碼如下:
/**
* @author li.hzh
* @date 2017-04-10 13:46
*/
@Slf4j
public class EncryptPropertySourceLoader implements PropertySourceLoader, PriorityOrdered {
private static final String ENC_PREFIX = "[email protected][";
private static final String ENC_POSTFIX = "]";
@Override
public String[] getFileExtensions() {
return new String[]{"properties"};
}
@Override
public PropertySource<?> load(String name, Resource resource , String profile) throws IOException {
if (profile == null) {
Properties properties = PropertiesLoaderUtils
.loadProperties(new EncodedResource(resource, "UTF-8"));
if (!properties.isEmpty()) {
decryptValue(properties );
return new EncryptPropertiesSource(name, properties);
}
}
return null;
}
private void decryptValue(Properties properties) {
Set<Object> keys = properties.keySet();
for (Object key : keys) {
String value = (String) properties.get(key);
if (isMatchEncrypt(value)) {
String finalValue = value;
try {
finalValue = decrypt(value);
} catch (Exception e) {
log.error("Decrypt value [" + value + "] error", e);
}
properties.put(key, finalValue);
}
}
}
private boolean isMatchEncrypt(String value) {
return value.startsWith(ENC_PREFIX) && value.endsWith(ENC_POSTFIX);
}
private String decrypt(String input) throws Exception {
String encryptData = getEncryptData(input);
return CodecUtil.decrypt(encryptData);
}
private String getEncryptData(String input) {
return input.substring(ENC_PREFIX.length(), input.length() - ENC_POSTFIX.length());
}
@Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
}
CodecUtil即加解密工具類,這裡實現自己的即可。EncryptPropertiesSource為複寫的PropertiesSource類。
在META-INF/spring.factory中指定使用該類
org.springframework.boot.env.PropertySourceLoader=xxx.xxx.EncryptPropertySourceLoader
使用方法
將需要加密的值,加密後放在[email protected][密文],即可。其餘值不會被處理。