上代码
@Service
public class DesensitizationServiceImpl implements DesensitizationService {
//传入实体列表脱敏敏感字段
@Override
public void desensitizationList(List list) {
boolean b = false;
if (!b) {
for (Object o : list) {
desensitization(o);
}
}
}
// 传入实体脱敏敏感字段
@Override
public void desensitizationObject(Object o) {
boolean b =false;
if (!b) {
desensitization(o);
}
}
private void desensitization(Object o) {
Field f1 = null;
try {
//获取敏感字段属性idCardNo
f1 = o.getClass().getDeclaredField("idCardNo");
f1.setAccessible(true);
String str = "";
String idCardNo = (String) f1.get(o);
if (idCardNo.length() >= 10) {
String pre = idCardNo.substring(0, 3);
str += pre;
String tail = idCardNo.substring(idCardNo.length() - 4, idCardNo.length());
for (int i = 3; i < idCardNo.length() - 4; i++) {
str += "*";
}
str += tail;
} else {
String pre = idCardNo.substring(0, 1);
str += pre;
String tail = idCardNo.substring(idCardNo.length() - 1, idCardNo.length());
for (int i = 1; i < idCardNo.length() - 1; i++) {
str += "*";
}
str += tail;
}
f1.set(o, str);
} catch (Exception e) {
}
try {
desensitizationPhone(o,"contactInfo");
} catch (Exception e) {
//e.printStackTrace();
}
try {
desensitizationPhone(o,"contactInfoOld");
} catch (Exception e) {
// e.printStackTrace();
}
}
private void desensitizationPhone(Object o,String str) throws NoSuchFieldException, IllegalAccessException {
Field f2 = o.getClass().getDeclaredField(str);
//尝试获取字段中的值
f2.setAccessible(true);
String contactInfo = (String) f2.get(o);
String newContactInfo = contactInfo.substring(0, 3);
for (int j = 3; j < contactInfo.length(); j++) {
newContactInfo += "*";
}
f2.set(o, newContactInfo);
//查看这个字段的值
}
}