针对表的修改和查询,分别采取不同的脱敏方法:
一、配置依赖
pom.xml
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.9.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.20</version>
</dependency>
二、编写代码
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EncryptTable {
/**
* 加密的表名
* @return
*/
String tableName();
/**
* 开关标记
* @return
*/
EncryptType type() default EncryptType.All;
/**
* 是否执行批量
* @return
*/
boolean batch() default false;
}
@Component
public class EncryptTableSwitchConfig {
private static String writeTables;
private static String readTables;
public static boolean getWriteSW(String tableName){
if (writeTables.contains(","+tableName+",")){
return true;
}
return false;
}
public static boolean getReadSW(String tableName){
if (readTables.contains(","+tableName+",")) {
return true;
}
return false;
}
@Value("${encrypt.table.switch.writeTables:}")
public void setWriteTables(String writeTables){
EncryptTableSwitchConfig.writeTables = writeTables;
}
@Value("${encrypt.table.switch.readTables:}")
public void setReadTables(){
EncryptTableSwitchConfig.readTables = readTables;
}
}
@Component
@Aspect
public class EncryptTableAspect {
@Value("${encrypt.table:N}")
private String sw;
@Before("@annotation(encryptTable)")
public void before(JoinPoint joinPoint, EncryptTable encryptTable){
if (!"Y".equals(sw)) {
return;
}
final String tableName = encryptTable.tableName();
final EncryptType type = encryptTable.type();
final boolean batch = encryptTable.batch();
switch (type) {
case WRITE:
if (!EncryptTableSwitchConfig.getWriteSW(tableName)){
return;
}
break;
case READ:
if (!EncryptTableSwitchConfig.getReadSW(tableName)) {
return;
}
break;
default:
if (!EncryptTableSwitchConfig.getReadSW(tableName)
&& !EncryptTableSwitchConfig.getWriteSW(tableName)) {
return;
}
}
if (batch) {
Switch.batch();
} else {
Switch.selected();
}
}
@Value("${encrypt.table.method:,updateUser,insertUser,}")
private String netsMethod;
@Pointcut("target(com.xxx.mapper.UserMapper)")
private void netsUser(){
}
/**
* 使用Aop做脱敏开关
* @param jp
*/
@Before("netsUser()")
public void before(JoinPoint jp){
MethodSignature signature = (MethodSignature)jp.getSignature();
final Method method = signature.getMethod();
if (netsMethod.contains(","+method+",") && EncryptTableSwitchConfig.getWriteSW("tab_user")){
Switc.selected();
}
}
}
/**
* 操作表的动作
*/
public enum EncryptType {
WRITE, READ, All;
}
xxxMapper.java
@EncryptTable(tableName="tab_user", type=EncryptType.READ, batch=false)
List<User> getUsersByIds(@param(ids) List<String> ids);