如何對數(shù)據(jù)進行脫敏處理?
一、背景
實際的業(yè)務(wù)開發(fā)過程中,我們經(jīng)常需要對用戶的隱私數(shù)據(jù)進行脫敏處理,所謂脫敏處理其實就是將數(shù)據(jù)進行混淆隱藏,例如下圖,將用戶的手機號、地址等數(shù)據(jù)信息,采用*進行隱藏,以免泄露個人隱私信息。
如果需要脫敏的數(shù)據(jù)范圍很小很小,甚至就是指定的字段,一般的處理方式也很簡單,就是寫一個隱藏方法即可實現(xiàn)數(shù)據(jù)脫敏。
如果是需求很少的情況下,采用這種方式實現(xiàn)沒太大問題,好維護!
但如果是類似上面那種很多位置的數(shù)據(jù),需要分門別類的進行脫敏處理,通過這種簡單粗暴的處理,代碼似乎就顯得不太優(yōu)雅了。
思考一下,我們可不可以在數(shù)據(jù)輸出的階段,進行統(tǒng)一數(shù)據(jù)脫敏處理,這樣就可以省下不少體力活。
說到數(shù)據(jù)輸出,很多同學可能會想到 JSON 序列化。是的沒錯,我們所熟悉的 web 系統(tǒng),就是將數(shù)據(jù)通過 json 序列化之后展示給前端。
那么問題來了,如何在序列化的時候,進行數(shù)據(jù)脫敏處理呢?
廢話不多說,代碼直接擼上!
二、程序?qū)嵺`
2.1、首先添加依賴包
默認的情況下,如果當前項目已經(jīng)添加了spring-web包或者spring-boot-starter-web包,因為這些jar包已經(jīng)集成了jackson相關(guān)包,因此無需重復依賴。
如果當前項目沒有jackson包,可以通過如下方式進行添加相關(guān)依賴包。
- <!--jackson依賴-->
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>2.9.8</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
- <version>2.9.8</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>2.9.8</version>
- </dependency>
2.2、編寫脫敏類型枚舉類,滿足不同場景的處理
- public enum SensitiveEnum {
- /**
- * 中文名
- */
- CHINESE_NAME,
- /**
- * 身份證號
- */
- ID_CARD,
- /**
- * 座機號
- */
- FIXED_PHONE,
- /**
- * 手機號
- */
- MOBILE_PHONE,
- /**
- * 地址
- */
- ADDRESS,
- /**
- * 電子郵件
- */
- EMAIL,
- /**
- * 銀行卡
- */
- BANK_CARD,
- /**
- * 公司開戶銀行聯(lián)號
- */
- CNAPS_CODE
- }
2.3、編寫脫敏注解類
- import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
- import com.fasterxml.jackson.databind.annotation.JsonSerialize;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- @Retention(RetentionPolicy.RUNTIME)
- @JacksonAnnotationsInside
- @JsonSerialize(using = SensitiveSerialize.class)
- public @interface SensitiveWrapped {
- /**
- * 脫敏類型
- * @return
- */
- SensitiveEnum value();
- }
2.4、編寫脫敏序列化類
- 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 SensitiveSerialize extends JsonSerializer<String> implements ContextualSerializer {
- /**
- * 脫敏類型
- */
- private SensitiveEnum type;
- @Override
- public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
- switch (this.type) {
- case CHINESE_NAME: {
- jsonGenerator.writeString(SensitiveInfoUtils.chineseName(s));
- break;
- }
- case ID_CARD: {
- jsonGenerator.writeString(SensitiveInfoUtils.idCardNum(s));
- break;
- }
- case FIXED_PHONE: {
- jsonGenerator.writeString(SensitiveInfoUtils.fixedPhone(s));
- break;
- }
- case MOBILE_PHONE: {
- jsonGenerator.writeString(SensitiveInfoUtils.mobilePhone(s));
- break;
- }
- case ADDRESS: {
- jsonGenerator.writeString(SensitiveInfoUtils.address(s, 4));
- break;
- }
- case EMAIL: {
- jsonGenerator.writeString(SensitiveInfoUtils.email(s));
- break;
- }
- case BANK_CARD: {
- jsonGenerator.writeString(SensitiveInfoUtils.bankCard(s));
- break;
- }
- case CNAPS_CODE: {
- jsonGenerator.writeString(SensitiveInfoUtils.cnapsCode(s));
- break;
- }
- }
- }
- @Override
- public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
- // 為空直接跳過
- if (beanProperty != null) {
- // 非 String 類直接跳過
- if (Objects.equals(beanProperty.getType().getRawClass(), String.class)) {
- SensitiveWrapped sensitiveWrapped = beanProperty.getAnnotation(SensitiveWrapped.class);
- if (sensitiveWrapped == null) {
- sensitiveWrapped = beanProperty.getContextAnnotation(SensitiveWrapped.class);
- }
- if (sensitiveWrapped != null) {
- // 如果能得到注解,就將注解的 value 傳入 SensitiveSerialize
- return new SensitiveSerialize(sensitiveWrapped.value());
- }
- }
- return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
- }
- return serializerProvider.findNullValueSerializer(beanProperty);
- }
- public SensitiveSerialize() {}
- public SensitiveSerialize(final SensitiveEnum type) {
- this.type = type;
- }
- }
其中createContextual的作用是通過字段已知的上下文信息定制JsonSerializer對象。
2.5、編寫脫敏工具類
- import org.apache.commons.lang3.StringUtils;
- public class SensitiveInfoUtils {
- /**
- * [中文姓名] 只顯示第一個漢字,其他隱藏為2個星號<例子:李**>
- */
- public static String chineseName(final String fullName) {
- if (StringUtils.isBlank(fullName)) {
- return "";
- }
- final String name = StringUtils.left(fullName, 1);
- return StringUtils.rightPad(name, StringUtils.length(fullName), "*");
- }
- /**
- * [中文姓名] 只顯示第一個漢字,其他隱藏為2個星號<例子:李**>
- */
- public static String chineseName(final String familyName, final String givenName) {
- if (StringUtils.isBlank(familyName) || StringUtils.isBlank(givenName)) {
- return "";
- }
- return chineseName(familyName + givenName);
- }
- /**
- * [身份證號] 顯示最后四位,其他隱藏。共計18位或者15位。<例子:420**********5762>
- */
- public static String idCardNum(final String id) {
- if (StringUtils.isBlank(id)) {
- return "";
- }
- return StringUtils.left(id, 3).concat(StringUtils
- .removeStart(StringUtils.leftPad(StringUtils.right(id, 4), StringUtils.length(id), "*"),
- "***"));
- }
- /**
- * [固定電話] 后四位,其他隱藏<例子:****1234>
- */
- public static String fixedPhone(final String num) {
- if (StringUtils.isBlank(num)) {
- return "";
- }
- return StringUtils.leftPad(StringUtils.right(num, 4), StringUtils.length(num), "*");
- }
- /**
- * [手機號碼] 前三位,后四位,其他隱藏<例子:138******1234>
- */
- public static String mobilePhone(final String num) {
- if (StringUtils.isBlank(num)) {
- return "";
- }
- return StringUtils.left(num, 3).concat(StringUtils
- .removeStart(StringUtils.leftPad(StringUtils.right(num, 4), StringUtils.length(num), "*"),
- "***"));
- }
- /**
- * [地址] 只顯示到地區(qū),不顯示詳細地址;我們要對個人信息增強保護<例子:北京市海淀區(qū)****>
- *
- * @param sensitiveSize 敏感信息長度
- */
- public static String address(final String address, final int sensitiveSize) {
- if (StringUtils.isBlank(address)) {
- return "";
- }
- final int length = StringUtils.length(address);
- return StringUtils.rightPad(StringUtils.left(address, length - sensitiveSize), length, "*");
- }
- /**
- * [電子郵箱] 郵箱前綴僅顯示第一個字母,前綴其他隱藏,用星號代替,@及后面的地址顯示<例子:g**@163.com>
- */
- public static String email(final String email) {
- if (StringUtils.isBlank(email)) {
- return "";
- }
- final int index = StringUtils.indexOf(email, "@");
- if (index <= 1) {
- return email;
- } else {
- return StringUtils.rightPad(StringUtils.left(email, 1), index, "*")
- .concat(StringUtils.mid(email, index, StringUtils.length(email)));
- }
- }
- /**
- * [銀行卡號] 前六位,后四位,其他用星號隱藏每位1個星號<例子:6222600**********1234>
- */
- public static String bankCard(final String cardNum) {
- if (StringUtils.isBlank(cardNum)) {
- return "";
- }
- return StringUtils.left(cardNum, 6).concat(StringUtils.removeStart(
- StringUtils.leftPad(StringUtils.right(cardNum, 4), StringUtils.length(cardNum), "*"),
- "******"));
- }
- /**
- * [公司開戶銀行聯(lián)號] 公司開戶銀行聯(lián)行號,顯示前兩位,其他用星號隱藏,每位1個星號<例子:12********>
- */
- public static String cnapsCode(final String code) {
- if (StringUtils.isBlank(code)) {
- return "";
- }
- return StringUtils.rightPad(StringUtils.left(code, 2), StringUtils.length(code), "*");
- }
- }
2.6、編寫測試實體類
最后,我們編寫一個實體類UserEntity,看看轉(zhuǎn)換后的效果如何?
- public class UserEntity {
- /**
- * 用戶ID
- */
- private Long userId;
- /**
- * 用戶姓名
- */
- private String name;
- /**
- * 手機號
- */
- @SensitiveWrapped(SensitiveEnum.MOBILE_PHONE)
- private String mobile;
- /**
- * 身份證號碼
- */
- @SensitiveWrapped(SensitiveEnum.ID_CARD)
- private String idCard;
- /**
- * 年齡
- */
- private String sex;
- /**
- * 性別
- */
- private int age;
- //省略get、set...
- }
測試程序如下:
- public class SensitiveDemo {
- public static void main(String[] args) throws JsonProcessingException {
- UserEntity userEntity = new UserEntity();
- userEntity.setUserId(1l);
- userEntity.setName("張三");
- userEntity.setMobile("18000000001");
- userEntity.setIdCard("420117200001011000008888");
- userEntity.setAge(20);
- userEntity.setSex("男");
- //通過jackson方式,將對象序列化成json字符串
- ObjectMapper objectMapper = new ObjectMapper();
- System.out.println(objectMapper.writeValueAsString(userEntity));
- }
- }
結(jié)果如下:
- {"userId":1,"name":"張三","mobile":"180****0001","idCard":"420*****************8888","sex":"男","age":20}
很清晰的看到,轉(zhuǎn)換結(jié)果成功!
如果你當前的項目是基于SpringMVC框架進行開發(fā)的,那么在對象返回的時候,框架會自動幫你采用jackson框架進行序列化。
- @RequestMapping("/hello")
- public UserEntity hello() {
- UserEntity userEntity = new UserEntity();
- userEntity.setUserId(1l);
- userEntity.setName("張三");
- userEntity.setMobile("18000000001");
- userEntity.setIdCard("420117200001011000008888");
- userEntity.setAge(20);
- userEntity.setSex("男");
- return userEntity;
- }
請求網(wǎng)頁http://127.0.0.1:8080/hello,結(jié)果如下:
三、小結(jié)
在實際的業(yè)務(wù)場景開發(fā)中,采用注解方式進行全局數(shù)據(jù)脫敏處理,可以有效的解決敏感數(shù)據(jù)隱私泄露的問題。
本文主要從實操層面對數(shù)據(jù)脫敏處理做了簡單的介紹,可能有些網(wǎng)友還有更好的解決方案,歡迎下方留言,后面如果遇到了好的解決辦法,也會分享給大家,愿對大家有所幫助!
四、參考
1、CSDN - 注解實現(xiàn)json序列化的時候自動進行數(shù)據(jù)脫敏
2、yanbin.blog - 自定義 Jackson 注解與禁用某一特定的注解
3、簡書 - 數(shù)據(jù)脫敏處理