目录
一、引入hutool的依赖
二、sql脚本
三、自定义注解代码
3.1 自定义注解
3.2 自定义一个枚举,用于定义脱敏的类型
3.3 序列化
四、使用脱敏注解
4.1 Person.java
4.2 controller
4.3 dao
五、源代码参考
一、引入hutool的依赖
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.18</version></dependency>
项目结构
二、sql脚本
/*Navicat Premium Data TransferSource Server : 192.168.14.23Source Server Type : MySQLSource Server Version : 80031Source Host : 192.168.14.23:3306Source Schema : ssTarget Server Type : MySQLTarget Server Version : 80031File Encoding : 65001Date: 23/10/2023 15:43:05
*/SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for person
-- ----------------------------
DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (`id` int(0) NOT NULL AUTO_INCREMENT,`name` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,`idCard` varchar(18) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,`fixedtel` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,`tel` varchar(11) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,`address` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,`email` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,`password` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,`carid` varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,`bankcard` varchar(19) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL,`registertime` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0),PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of person
-- ----------------------------
INSERT INTO `person` VALUES (1, 'zhang san', NULL, NULL, '15692536584', '河南省郑州市', NULL, '123654789', NULL, NULL, '2023-10-20 20:08:10');
INSERT INTO `person` VALUES (2, 'zhang san', NULL, NULL, '15692536584', '河南省郑州市高新区科学大道108号', NULL, '123654789', NULL, NULL, '2023-10-20 20:19:52');
INSERT INTO `person` VALUES (3, 'zhang san', NULL, NULL, '15692536584', '河南省郑州市高新区科学大道108号', NULL, '123654789', NULL, NULL, '2023-10-20 20:20:20');
INSERT INTO `person` VALUES (4, 'zhang san', NULL, NULL, '15692536584', '河南省郑州市高新区科学大道108号', NULL, '123654789', NULL, NULL, '2023-10-20 20:23:42');
INSERT INTO `person` VALUES (5, 'zhang san', '130169566636956632', NULL, '15692536584', '河南省郑州市高新区科学大道108号', NULL, '123654789', NULL, NULL, '2023-10-20 20:40:06');
INSERT INTO `person` VALUES (6, '张三丰', '136956366695687746', NULL, '13211975672', '河南省郑州市高新区科学大道108号', '123456@163.com', 'sdfgsgsgsgaa ', '陕A184d5D', '6246605000005734228', '2023-10-20 21:19:27');SET FOREIGN_KEY_CHECKS = 1;
三、自定义注解代码
3.1 自定义注解
package com.beiyou.annotation;import com.beiyou.enums.SensitizeRuleEnums;
import com.beiyou.serializer.SensitiveJsonSerializer;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** @author 黄远超*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@JacksonAnnotationsInside
//使用自定义的序列化方式
@JsonSerialize(using = SensitiveJsonSerializer.class)
public @interface Sensitize {SensitizeRuleEnums rule();
}
3.2 自定义一个枚举,用于定义脱敏的类型
package com.beiyou.enums;import cn.hutool.core.util.DesensitizedUtil;
import java.util.function.Function;/*** @author 黄远超*/public enum SensitizeRuleEnums {/*** 用户id脱敏*/USER_ID(s -> String.valueOf(DesensitizedUtil.userId())),/*** 中文姓名脱敏*/CHINESE_NAME(DesensitizedUtil::chineseName),/*** 身份证脱敏*/ID_CARD(s -> DesensitizedUtil.idCardNum(s, 3, 4)),/*** 固定电话*/FIXED_PHONE(DesensitizedUtil::fixedPhone),/*** 手机号脱敏*/MOBILE_PHONE(DesensitizedUtil::mobilePhone),/*** 地址脱敏*/ADDRESS(s -> DesensitizedUtil.address(s, 8)),/*** 电子邮箱脱敏*/EMAIL(DesensitizedUtil::email),/*** 密码脱敏*/PASSWORD(DesensitizedUtil::password),/*** 中国车牌脱敏*/CAR_LICENSE(DesensitizedUtil::carLicense),/*** 银行卡脱敏*/BANK_CARD(DesensitizedUtil::bankCard);private final Function<String, String> sensitize;public Function<String, String> sensitize() {return sensitize;}SensitizeRuleEnums(Function<String, String> sensitize) {this.sensitize = sensitize;}
}
3.3 序列化
package com.beiyou.serializer;import com.beiyou.annotation.Sensitize;import com.beiyou.enums.SensitizeRuleEnums;import com.fasterxml.jackson.core.JsonGenerator;import com.fasterxml.jackson.databind.BeanProperty;import com.fasterxml.jackson.databind.JsonMappingException;import com.fasterxml.jackson.databind.JsonSerializer;import com.fasterxml.jackson.databind.SerializerProvider;import com.fasterxml.jackson.databind.ser.ContextualSerializer;import java.io.IOException;import java.util.Objects;public class SensitiveJsonSerializer extends JsonSerializer<Object> implements ContextualSerializer {private SensitizeRuleEnums rule;@Overridepublic JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {Sensitize annotation = beanProperty.getAnnotation(Sensitize.class);if (Objects.nonNull(annotation)) {this.rule = annotation.rule();return this;}return null;}@Overridepublic void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {jsonGenerator.writeString(rule.sensitize().apply(o.toString()));}}
四、使用脱敏注解
第三步的时候已经将自定义注解定义出来了,那么我们只需要在实体类中添加注解,并且通过枚举指定实体属性的脱敏类型即可。
4.1 Person.java
package com.beiyou.model;import com.beiyou.annotation.Sensitize;
import com.beiyou.enums.SensitizeRuleEnums;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Person {@Sensitize(rule = SensitizeRuleEnums.USER_ID)private Integer id;@Sensitize(rule = SensitizeRuleEnums.CHINESE_NAME)private String name;@Sensitize(rule = SensitizeRuleEnums.ID_CARD)private String idCard;@Sensitize(rule = SensitizeRuleEnums.FIXED_PHONE)private String fixedtel;@Sensitize(rule = SensitizeRuleEnums.MOBILE_PHONE)private String tel;@Sensitize(rule = SensitizeRuleEnums.ADDRESS)private String address;@Sensitize(rule = SensitizeRuleEnums.EMAIL)private String email;@Sensitize(rule = SensitizeRuleEnums.PASSWORD)private String password;@Sensitize(rule = SensitizeRuleEnums.ID_CARD)private String carid;@Sensitize(rule = SensitizeRuleEnums.BANK_CARD)private Long bankcard;}
4.2 controller
package com.beiyou.controller;import com.beiyou.dao.PersonDao;
import com.beiyou.model.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/api")
public class PersonController {@AutowiredPersonDao personDao;@PostMapping("/insert")public int insert(@RequestBody Person person) {return personDao.insert(person);}@GetMapping("getPerson")public Person getPerson() {Person person = new Person();person.setId(1555555550);person.setName("张三丰");person.setIdCard("16396583578");person.setTel("13211975672");person.setAddress("河南省郑州市高新区科学大道108号");person.setEmail("123456@163.com");person.setPassword("123456");person.setCarid("冀A888888");person.setBankcard(6246605000005734228L);return person;}@GetMapping("getPerson1")public Person getPerson1(Integer id) {return personDao.select(id);}}
4.3 dao
package com.beiyou.dao;import com.beiyou.model.Person;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;@Mapper
public interface PersonDao {@Insert("insert person(name,IdCard,fixedtel,tel,address,email,password,carid,bankcard) values (#{name},#{idCard},#{fixedtel},#{tel},#{address},#{email},#{password},#{carid},#{bankcard})")int insert(Person person);@Select("select id,name,IdCard,fixedtel,tel,address,email,password,carid,bankcard from person where id = #{id}")Person select (Integer id);}
五、源代码参考
阿里云登录 - 欢迎登录阿里云,安全稳定的云计算服务平台