注解方式,数据库的数据自动解密,拦截基于数据库实体类
数据库中加密数据
新建注解类:
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface EncryptField {
String value() default “”;
}
根据执行的sql包含update和query拦截到有注解的字段,通过反射机制获取指定参数的值:
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface EncryptField {
String value() default "";
}
```java
// 解密密拦截
@Intercepts({
@Signature(type=Executor.class,method="update",args={MappedStatement.class,Object.class}),
@Signature(type=Executor.class,method="query",args={MappedStatement.class,Object.class,RowBounds.class,ResultHandler.class})
})
public class ParameterInterceptor implements Interceptor {
protected final Logger log = Logger.getLogger(getClass());
public static final String KEY = "BDA52970EFA896C18A5D37C0";
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
String methodName = invocation.getMethod().getName();
Object parameter = invocation.getArgs()[1];
BoundSql sql = statement.getBoundSql(parameter);
log.error(sql.getSql());
Object returnValue = invocation.proceed();
if(returnValue instanceof ArrayList<?>){
List<?> list = (ArrayList<?>)returnValue;
for(Object val:list){
//通过反射获取修改参数
Field[] fields = val.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
fields[i].setAccessible(true);
if(fields[i].isAnnotationPresent(EncryptField.class) && fields[i].getType().toString().endsWith("String"))
{
String data = "";
String par = (String) getFieldValueByName(fields[i].getName(),val);
try {
//AppDESUtil解密的方法,根据你自己需求定义
data = AppDESUtil.decrypt(par, KEY);
if (null == data || "".equals(data)){
data = par;
}
} catch (Exception e){
// 如果之前没有加密数据直接用直接前的
data = par;
}
fields[i].set(val,data);
}
}
}
}
return returnValue;
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// TODO Auto-generated method stub
}
/* 根据属性名获取属性值
* */
private static Object getFieldValueByName(String fieldName, Object o) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[] {});
Object value = method.invoke(o, new Object[] {});
return value;
} catch (Exception e) {
return null;
}
}
}