Created
July 10, 2023 07:30
-
-
Save gengxiankun/eba3026828818b094bc425c77d856897 to your computer and use it in GitHub Desktop.
代码脱敏 demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 信息脱敏逻辑类 | |
* @author xiankun.geng | |
*/ | |
@Service | |
public class DesensitizedService { | |
/** | |
* 信息脱敏 | |
* @param result 出参 | |
*/ | |
public void desensitized(Object result) throws IllegalAccessException { | |
if (result == null) { | |
return; | |
} | |
if (result instanceof String) { | |
if (!result.getClass().isAnnotationPresent(DesensitizedField.class)) { | |
return; | |
} | |
result = this.desensitized( | |
result.getClass().getAnnotation(DesensitizedField.class).filedType(), String.valueOf(result)); | |
} else { | |
if (Objects.isNull(result)) { | |
return; | |
} | |
if (result instanceof Page<?>) { | |
this.desensitizedList(((Page<?>) result).getContent()); | |
} else if (result instanceof ArrayList) { | |
this.desensitizedList(result); | |
} else { | |
this.desensitizedObj(result); | |
} | |
result = result; | |
} | |
} | |
/** | |
* 针对数组结构处理信息脱敏 | |
* @param obj 出参 | |
*/ | |
private void desensitizedList(Object obj) throws IllegalAccessException { | |
List<Object> result = new ArrayList<>(); | |
if (obj instanceof List<?>) { | |
for (Object o : (List<?>) obj) { | |
result.add(o); | |
} | |
} | |
for (Object object : result) { | |
this.desensitizedObj(object); | |
} | |
} | |
/** | |
* 针对对象结构处理信息脱敏 | |
* @param obj 出参 | |
*/ | |
private void desensitizedObj(Object obj) throws IllegalAccessException { | |
Field[] fields = obj.getClass().getDeclaredFields(); | |
for (Field field : fields) { | |
if (field.isAnnotationPresent(DesensitizedField.class)) { | |
field.setAccessible(true); | |
if (field.get(obj) == null || StrUtil.isBlank(String.valueOf(field.get(obj)))) { | |
continue; | |
} | |
String value = this.desensitized( | |
field.getAnnotation(DesensitizedField.class).filedType(), String.valueOf(field.get(obj))); | |
field.set(obj, value); | |
} | |
} | |
} | |
/** | |
* 针对不同类型进行信息脱敏 | |
* @param fieldType 类型 | |
* @param value 数据 | |
* @return 脱敏后的数据 | |
*/ | |
private String desensitized(FieldType fieldType, String value) { | |
switch (fieldType) { | |
case PHONE: | |
return DesensitizedUtil.mobilePhone(value); | |
case EMAIL: | |
return DesensitizedUtil.email(value); | |
case PASSWORD: | |
return DesensitizedUtil.password(value); | |
case CARD_NUM: | |
return DesensitizedUtil.idCardNum(value, 1, 2); | |
default: | |
return value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment