Java数据脱敏常用方法(3种)

 更新时间:2023年07月14日 15:08:30   作者:y小恒  
数据脱敏常用在电话号码和身份证号,本文主要介绍了Java数据脱敏常用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1.SQL数据脱敏实现

MYSQL(电话号码,身份证)数据脱敏的实现

-- CONCAT()、LEFT()和RIGHT()字符串函数组合使用,请看下面具体实现
-- CONCAT(str1,str2,…):返回结果为连接参数产生的字符串
-- LEFT(str,len):返回从字符串str 开始的len 最左字符
-- RIGHT(str,len):从字符串str 开始,返回最右len 字符
-- 电话号码脱敏sql:
SELECT mobilePhone AS 脱敏前电话号码,CONCAT(LEFT(mobilePhone,3), '********' ) AS 脱敏后电话号码 FROM t_s_user
-- 身份证号码脱敏sql:
SELECT idcard AS 未脱敏身份证, CONCAT(LEFT(idcard,3), '****' ,RIGHT(idcard,4)) AS 脱敏后身份证号 FROM t_s_user

2.JAVA数据脱敏实现

可参考:海强 / sensitive-plus

数据脱敏插件,目前支持地址脱敏、银行卡号脱敏、中文姓名脱敏、固话脱敏、身份证号脱敏、手机号脱敏、密码脱敏 一个是正则脱敏、另外一个根据显示长度脱敏,默认是正则脱敏,可以根据自己的需要配置自己的规则。

3 mybatis-mate-sensitive-jackson

mybatis-mate-sensitive-jackson

mybatisplus 的新作,可以测试使用,生产需要收费。

根据定义的策略类型,对数据进行脱敏,当然策略可以自定义。

# 目前已有
package mybatis.mate.strategy;
public interface SensitiveType {
    String chineseName = "chineseName";
    String idCard = "idCard";
    String phone = "phone";
    String mobile = "mobile";
    String address = "address";
    String email = "email";
    String bankCard = "bankCard";
    String password = "password";
    String carNumber = "carNumber";
}

Demo 代码目录

 1、pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-mate-examples</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>mybatis-mate-sensitive-jackson</artifactId>
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>
</project>

2、appliation.yml

# DataSource Config
spring:
  datasource:
#    driver-class-name: org.h2.Driver
#    schema: classpath:db/schema-h2.sql
#    data: classpath:db/data-h2.sql
#    url: jdbc:h2:mem:test
#    username: root
#    password: test
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis_mate?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: 123456
# Mybatis Mate 配置
mybatis-mate:
  cert:
    # 请添加微信wx153666购买授权,不白嫖从我做起! 测试证书会失效,请勿正式环境使用
    grant: thisIsTestLicense
    license: as/bsBaSVrsA9FfjC/N77ruEt2/QZDrW+MHETNuEuZBra5mlaXZU+DE1ZvF8UjzlLCpH3TFVH3WPV+Ya7Ugiz1Rx4wSh/FK6Ug9lhos7rnsNaRB/+mR30aXqtlLt4dAmLAOCT56r9mikW+t1DDJY8TVhERWMjEipbqGO9oe1fqYCegCEX8tVCpToKr5J1g1V86mNsNnEGXujnLlEw9jBTrGxAyQroD7Ns1Dhwz1K4Y188mvmRQp9t7OYrpgsC7N9CXq1s1c2GtvfItHArkqHE4oDrhaPjpbMjFWLI5/XqZDtW3D+AVcH7pTcYZn6vzFfDZEmfDFV5fQlT3Rc+GENEg==
# Logger Config
logging:
  level:
    mybatis.mate: debug

3、Appliation启动类

package mybatis.mate.sensitive.jackson;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SensitiveJacksonApplication {
    // 测试访问 http://localhost:8080/info ,http://localhost:8080/list
    public static void main(String[] args) {
        SpringApplication.run(SensitiveJacksonApplication.class, args);
    }
}
 

4、配置类,自定义脱敏策略

package mybatis.mate.sensitive.jackson.config;
import mybatis.mate.databind.ISensitiveStrategy;
import mybatis.mate.strategy.SensitiveStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SensitiveStrategyConfig {
    /**
     * 注入脱敏策略
     */
    @Bean
    public ISensitiveStrategy sensitiveStrategy() {
        // 自定义 testStrategy 类型脱敏处理
        return new SensitiveStrategy().addStrategy("testStrategy", t -> t + "***test***");
    }
}

5、业务类

User,注解标识脱敏字段,及选用脱敏策略

package mybatis.mate.sensitive.jackson.entity;
import lombok.Getter;
import lombok.Setter;
import mybatis.mate.annotation.FieldSensitive;
import mybatis.mate.sensitive.jackson.config.SensitiveStrategyConfig;
import mybatis.mate.strategy.SensitiveType;
@Getter
@Setter
public class User {
    private Long id;
    /**
     * 这里是一个自定义的策略 {@link SensitiveStrategyConfig} 初始化注入
     */
    @FieldSensitive("testStrategy")
    private String username;
    /**
     * 默认支持策略 {@link SensitiveType }
     */
    @FieldSensitive(SensitiveType.mobile)
    private String mobile;
    @FieldSensitive(SensitiveType.email)
    private String email;
}

UserController

package mybatis.mate.sensitive.jackson.controller;
import mybatis.mate.databind.ISensitiveStrategy;
import mybatis.mate.databind.RequestDataTransfer;
import mybatis.mate.sensitive.jackson.entity.User;
import mybatis.mate.sensitive.jackson.mapper.UserMapper;
import mybatis.mate.strategy.SensitiveType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ISensitiveStrategy sensitiveStrategy;
    // 测试访问 http://localhost:8080/info
    @GetMapping("/info")
    public User info() {
        return userMapper.selectById(1L);
    }
    // 测试返回 map 访问 http://localhost:8080/map
    @GetMapping("/map")
    public Map<String, Object> map() {
        // 测试嵌套对象脱敏
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("user", userMapper.selectById(1L));
        userMap.put("test", 123);
        userMap.put("userMap", new HashMap<String, Object>() {{
            put("user2", userMapper.selectById(2L));
            put("test2", "hi china");
        }});
        // 手动调用策略脱敏
        userMap.put("mobile", sensitiveStrategy.getStrategyFunctionMap()
                .get(SensitiveType.mobile).apply("15315388888"));
        return userMap;
    }
    // 测试访问 http://localhost:8080/list
    // 不脱敏 http://localhost:8080/list?skip=1
    @GetMapping("/list")
    public List<User> list(HttpServletRequest request) {
        if ("1".equals(request.getParameter("skip"))) {
            // 跳过脱密处理
            RequestDataTransfer.skipSensitive();
        }
        return userMapper.selectList(null);
    }
}

UserMapper

package mybatis.mate.sensitive.jackson.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import mybatis.mate.sensitive.jackson.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper extends BaseMapper<User> {
}

6、测试

GET http://localhost:8080/list
[
  {
    "id": 1,
    "username": "Jone***test***",
    "mobile": "153******81",
    "email": "t****@baomidou.com"
  },
  {
    "id": 2,
    "username": "Jack***test***",
    "mobile": "153******82",
    "email": "t****@baomidou.com"
  },
  {
    "id": 3,
    "username": "Tom***test***",
    "mobile": "153******83",
    "email": "t****@baomidou.com"
  }
]
GET http://localhost:8080/list?skip&#61;1
[
  {
    "id": 1,
    "username": "Jone",
    "mobile": "15315388881",
    "email": "test1@baomidou.com"
  },
  {
    "id": 2,
    "username": "Jack",
    "mobile": "15315388882",
    "email": "test2@baomidou.com"
  },
  {
    "id": 3,
    "username": "Tom",
    "mobile": "15315388883",
    "email": "test3@baomidou.com"
  }
]

 到此这篇关于Java数据脱敏常用方法(3种)的文章就介绍到这了,更多相关Java数据脱敏内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java对int[]数组做新增删除去重操作代码

    Java对int[]数组做新增删除去重操作代码

    这篇文章主要介绍了Java里面对int[]数组做新增删除去重实现,这里记录下使用int[]数组对数组进行新增删除去重等操作,用来更加了解java里面的集合类思想,需要的朋友可以参考下
    2023-10-10
  • 使用Iterator删除List中的多个元素操作

    使用Iterator删除List中的多个元素操作

    这篇文章主要介绍了使用Iterator删除List中的多个元素操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • Spring 中的 @PathVariable 注解及应用场景分析

    Spring 中的 @PathVariable 注解及应用场景分析

    @PathVariable注解是 Spring 框架中一个非常实用的注解,它可以帮助我们轻松地从 URL 中提取参数,从而实现 RESTful API 的开发,通过本文的介绍,我们了解了@PathVariable注解的基本使用方法和高级用法,以及它的应用场景,感兴趣的朋友跟随小编一起看看吧
    2025-05-05
  • Java Synchronized字节码层分析体验

    Java Synchronized字节码层分析体验

    这篇文章主要介绍了Java Synchronized字节码层分析,synchronized关键字解决了多个线程之间的资源同步性,synchronized关键字保证了它修饰的方法或者代码块任意时刻只有一个线程在访问
    2023-04-04
  • SpringBoot项目启动时如何将需要数据添加到redis缓存

    SpringBoot项目启动时如何将需要数据添加到redis缓存

    文章介绍了使用Java注解@PostConstruct进行项目启动时加载,并使用Spring和Redis进行数据缓存的操作,通过`setCacheObject`方法将数据存储到Redis中,并提供了清空缓存的方法
    2026-04-04
  • 一文带你详细认识文件与Java中操作文件

    一文带你详细认识文件与Java中操作文件

    文件处理是任何应用程序的重要部分,Java 提供了许多用于创建、读取、更新和删除文件的方法,这篇文章主要给大家介绍了关于认识文件与Java中操作文件的相关资料,需要的朋友可以参考下
    2024-05-05
  • Hadoop源码分析六启动文件namenode原理详解

    Hadoop源码分析六启动文件namenode原理详解

    本篇是Hadoop源码分析系列文章第六篇,主要介绍Hadoop中的启动文件namenode,后续本系列文章会持续更新,有需要的朋友可以借鉴参考下
    2021-09-09
  • 详解mybatis.generator配上最新的mysql 8.0.11的一些坑

    详解mybatis.generator配上最新的mysql 8.0.11的一些坑

    这篇文章主要介绍了详解mybatis.generator配上最新的mysql 8.0.11的一些坑,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-10-10
  • @feignclient名字冲突的解决方案

    @feignclient名字冲突的解决方案

    这篇文章主要介绍了@feignclient名字冲突的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • Java连接Oracle数据库并查询

    Java连接Oracle数据库并查询

    这篇文章主要介绍了Java连接Oracle数据库并查询的相关资料,需要的朋友可以参考下
    2017-04-04

最新评论