数据脱敏的 3 种常见方案,好用到爆!

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介: 数据脱敏的 3 种常见方案,好用到爆!

来源:blog.csdn.net/weixin_61594803

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


https://gitee.com/strong_sea/sensitive-plus


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


3.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 代码目录

image.png

Spring Boot 基础就不介绍了,推荐看这个免费教程:

https://github.com/javastacks/spring-boot-best-practice

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=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"
  }
]
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
缓存 NoSQL Java
Spring Boot如何优雅实现动态灵活可配置的高性能数据脱敏功能
在当下互联网高速发展的时代下,涉及到用户的隐私数据安全越发重要,一旦泄露将造成不可估量的后果。所以现在的业务系统开发中都会对用户隐私数据加密之后存储落库,同时还要求后端返回数据给前台之前进行数据脱敏。所谓脱敏处理其实就是将数据进行混淆隐藏,如将用户的手机号脱敏展示为`178****5939,采用 * 进行隐藏,以免泄露个人隐私信息
1461 0
|
11月前
|
数据安全/隐私保护 数据格式
数据安全必备:三种实用的数据脱敏技术
在数字化时代,数据安全和隐私保护成为了企业和个人关注的焦点。数据脱敏作为一种有效的数据保护手段,能够降低数据泄露的风险,保护用户隐私。本文将介绍三种常见的数据脱敏方案,帮助您在实际工作中选择合适的脱敏技术。
1086 2
|
3月前
|
机器学习/深度学习 人工智能 自动驾驶
AI Agent多模态融合策略研究与实证应用
本文从多模态信息融合的理论基础出发,构建了一个结合图像与文本的AI Agent模型,并通过PyTorch代码实现了完整的图文问答流程。未来,多模态智能体将在医疗、自动驾驶、虚拟助手等领域展现巨大潜力。模型优化的核心是提升不同模态的协同理解与推理能力,从而打造真正“理解世界”的AI Agent。
AI Agent多模态融合策略研究与实证应用
|
12月前
|
Java fastjson Apache
【数据安全】数据脱敏方案总结
【数据安全】数据脱敏方案总结
667 1
|
算法 安全
数据脱敏?看我一行注解搞定!
本文主要分享什么是数据脱敏,如何优雅的在项目中运用一个注解实现数据脱敏,为项目进行赋能。希望能给你们带来帮助。
1298 3
|
11月前
|
Linux iOS开发 MacOS
如何设置 Ping 命令的超时时间?
如何设置 Ping 命令的超时时间?
1825 3
|
12月前
|
存储 JavaScript API
深入理解RESTful API设计
【10月更文挑战第6天】深入理解RESTful API设计
|
存储 安全 算法
Java中的数据脱敏与隐私保护技术
Java中的数据脱敏与隐私保护技术
|
小程序
[渲染层错误] [jsbridge] invoke remoteDebugInfo fail: too eayly.
这篇文章分享了在小程序开发过程中遇到的一个渲染层错误,原因是路径错误,特别是图片后缀名的遗漏,通过手动修正后问题得到解决。
[渲染层错误] [jsbridge] invoke remoteDebugInfo fail: too eayly.
|
安全 API Windows
CreateMutex用法
CreateMutex用法