注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DataProtect {
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Decrypt {
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Encrpty {
}
逻辑切面
@Aspect
@Component("dataProtectAspect")
public class DataProtectAspect {
@Resource
private AksRpc aksRpc;
@Around("@annotation(xxx.service.aspect.annotation.DataProtect)")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
Assert.notEmpty(pjp.getArgs(), "args can not be null.");
Stream.of(pjp.getArgs()).forEach(arg -> {
if (arg instanceof Collection) {
Collection collection = (Collection) arg;
collection.forEach(x -> handleObject(x));
} else {
handleObject(arg);
}
});
Object result = pjp.proceed();
if (result instanceof Collection) {
Collection collection = (Collection) result;
collection.forEach(x -> {
handleObject(x);
});
} else {
handleObject(result);
}
return result;
}
private void handleObject(Object arg) {
Optional.ofNullable(arg)
.map(Object::getClass)
.map(Class::getDeclaredFields)
.ifPresent(fields ->
Stream.of(fields)
.forEach(field -> {
try {
if (!field.isAnnotationPresent(Encrpty.class) && !field.isAnnotationPresent(Decrypt.class)) return;
field.setAccessible(true);
Object value = field.get(arg);
if (Objects.isNull(value)) return;
if (isParseByObject(value.getClass())) {
handleObject(value);
}
else {
handleField(field, arg);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}));
}
private void handleField(Field field, Object arg) {
if (field.getType() != String.class) return;
if (field.isAnnotationPresent(Encrpty.class)) {
try {
field.setAccessible(true);
Object value = field.get(arg);
if (StringUtils.isBlank((CharSequence) value)) return;
String ciphertext = aksRpc.encryptString(String.valueOf(value));
field.set(arg, ciphertext);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
if (field.isAnnotationPresent(Decrypt.class)) {
try {
field.setAccessible(true);
Object value = field.get(arg);
if (StringUtils.isBlank((CharSequence) value)) return;
String ciphertext = aksRpc.decryptString(String.valueOf(value));
field.set(arg, ciphertext);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
private boolean isParseByObject(Class clz) {
try {
return !clz.isPrimitive()
&& clz != Date.class
&& clz != BigDecimal.class
&& clz != BigInteger.class
&& !isWrapClass(clz)
&& clz != String.class;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private static boolean isWrapClass(Class clz) {
try {
return ((Class) clz.getField("TYPE").get(null)).isPrimitive();
} catch (Exception e) {
return false;
}
}
}