如何对关键字段进行脱敏(一)在使用Mybatis-plus执行查询

为了在读取 用户 表中的 mobile 字段时进行脱敏处理,并实现一个通用的方法以便将来对其他字段例如:邮箱、身份证、姓名等进行脱敏处理,可以采用以下步骤:

1. 添加依赖

首先,在 pom.xml 文件中添加必要的依赖,包括 Spring Boot、MyBatis-Plus 和 Hutool 工具库:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.2</version>
    </dependency>
    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.8.16</version>
    </dependency>
</dependencies>

2. 创建脱敏注解

定义一个自定义注解 @Sensitive,用于标识需要脱敏的字段:

package com.example.demo.annotation;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface Sensitive {
    SensitiveType type();
}

enum SensitiveType {
    MOBILE,
    EMAIL,
    ID_CARD
}

3. 创建脱敏拦截器

实现一个通用的脱敏拦截器 DesensitizationInterceptor,用于处理不同类型的脱敏逻辑:

package com.example.demo.handler;

package com.central.db.sensitive;

import cn.hutool.core.util.DesensitizedUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.List;

@Slf4j
@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})})
public class DesensitizationInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        if (result instanceof List) {
            for (Object obj : (List) result) {
                desensitize(obj);
            }
        } else {
            desensitize(result);
        }
        return result;
    }

    private void desensitize(Object obj) {
        if (obj == null) {
            return;
        }
        // 使用反射获取字段并进行脱敏处理
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Sensitive.class)) {
                Sensitive sensitive = field.getAnnotation(Sensitive.class);
                field.setAccessible(true);
                try {
                    String value = (String) field.get(obj);
                    if (value != null) {
                        field.set(obj, desensitizeValue(value, sensitive.type()));
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String desensitizeValue(String value, SensitiveType type) {
        switch (type) {
            case MOBILE:
                return DesensitizedUtil.mobilePhone(value);
            case EMAIL:
                return DesensitizedUtil.email(value);
            case ID_CARD:
                return DesensitizedUtil.idCardNum(value, 1, 2);
            default:
                return value;
        }
    }
}

4. 配置 MyBatis-Plus

在 MyBatis-Plus 配置中注册自定义的类型处理器:

package com.example.demo.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.example.demo.annotation.SensitiveType;
import com.example.demo.handler.SensitiveTypeHandler;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfig {
    @Bean
    public Interceptor desensitizationInterceptor() {
        return new DesensitizationInterceptor();
    }
    //其他配置省略....
    
}

5. 修改实体类

Employee 实体类中使用自定义注解标识需要脱敏的字段:

package com.example.demo.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.example.demo.annotation.Sensitive;
import com.example.demo.annotation.SensitiveType;
import lombok.Data;

@Data
@TableName("employee")
public class Employee {
    @TableId
    private Long id;

    @Sensitive(type = SensitiveType.MOBILE)
    private String mobile;

    // 其他字段...
}

6. 测试

编写测试代码,验证脱敏功能是否正常工作:

package com.example.demo;

import com.example.demo.entity.Employee;
import com.example.demo.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class TestRunner implements CommandLineRunner {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void run(String... args) throws Exception {
        Employee employee = employeeMapper.selectById(1L);
        System.out.println("脱敏后的手机号: " + employee.getMobile());
    }
}

通过以上步骤,你可以实现一个通用的数据脱敏方法,适用于不同字段和表的关键字段。这样可以有效保护敏感数据,确保数据隐私和安全。

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值