背景:
目前项目中,密码用户名都采用明文保存,为了安全考虑需要进行脱敏。
通过在 BeanFactoryPostProcessor 中,对属性进行解密。
遇到的困难:
在 BeanFactoryPostProcessor 中需要用到其他bean
解决办法:
通过 beanFactory中获取bean
@Slf4j
public class EncryptBeanFactoryPostProcessor implements BeanFactoryPostProcessor, Ordered {
private ConfigurableEnvironment env;
public EncryptBeanFactoryPostProcessor(ConfigurableEnvironment env) {
this.env = env;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
ResourceLoader resourceLoader = new DefaultResourceLoader();
MutablePropertySources propertySources = env.getPropertySources();
EncryptionUtils encryption = beanFactory.getBean(EncryptionUtils.class);
Map<String, Object> map = new HashMap<>();
for (PropertySource<?> propertySource : propertySources) {
if (propertySource instanceof MapPropertySource) {
MapPropertySource source = (MapPropertySource) propertySource;
//遍历所有的配置信息
for (String name : source.getPropertyNames()) {
Object value = source.getProperty(name);
if (value instanceof String) {
String str = (String) value;
//包含加密前缀,截取去掉统一的加密前缀后的信息
if (str.startsWith("mpw:")) {
String st = encryption.encrypt(str.substring(5));
map.put(name, st);
log.info("Encrypt key:{},value:{}", name, st);
} else {
log.info("Encrypt key:{},value:{}", name, value);
}
}
}
}
}
if (!map.isEmpty()) {
propertySources.addFirst(new MapPropertySource("custom-encrypt", map));
}
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
786

被折叠的 条评论
为什么被折叠?



