SoFunction
Updated on 2025-04-14

Detailed explanation of the method of implementing data desensitization in SpringBoot

During project development, data desensitization is an important safety measure when processing sensitive information. Data desensitization prevents sensitive information from being leaked in unauthorized situations, while protecting user privacy during data sharing and analysis.

1. The necessity of data desensitization

Protect privacy: Prevent sensitive information (such as ID number, mobile phone number, etc.) from being leaked.

Compliance requirements: Comply with data protection regulations (such as GDPR, CCPA, etc.).

Enhanced security: Reduce the risk of data abuse.

2. Commonly used data desensitization strategies

Replace desensitization: Replace part of sensitive information with specific characters, such as*Replace the middle part of the mobile phone number.

Hash desensitization: The hashing algorithm is used to process sensitive information, and the original value cannot be restored.

Fuzzy: Fuzzy the data to make it difficult to identify, but retain a certain amount of usability.

Encrypted desensitization: Encrypted and stored sensitive information and decrypted only under authorization.

3. Implementation steps

3.1 Creating Desensitization Annotations

import ;
import ;
import ;
import ;

@Target()
@Retention()
public @interface Sensitive {
    String type(); // Desensitization type    String pattern() default ""; // Optional mode parameters}

3.2 Policy interface design

First, define a desensitization policy interface, and all desensitization policies will implement this interface:

public interface MaskingStrategy {
    String mask(String value, String pattern);
}

3.3 Implementation of specific desensitization strategies

Next, create a specific implementation class for each desensitization type:

public class PhoneMaskingStrategy implements MaskingStrategy {
    @Override
    public String mask(String value, String pattern) {
        return ("(\d{3})\d{4}(\d{4})", "$1****$2");
    }
}

public class IdCardMaskingStrategy implements MaskingStrategy {
    @Override
    public String mask(String value, String pattern) {
        return ("(\d{6})\d{8}(\d{4})", "$1****$2");
    }
}

public class CustomMaskingStrategy implements MaskingStrategy {
    @Override
    public String mask(String value, String pattern) {
        return (pattern, "****");
    }
}

3.4 Strategy Factory

Create a policy factory and return the corresponding policy instance according to the desensitization type:

import ;
import ;

public class MaskingStrategyFactory {
    private static final Map<String, MaskingStrategy> strategies = new HashMap<>();

    static {
        ("phone", new PhoneMaskingStrategy());
        ("idCard", new IdCardMaskingStrategy());
        ("custom", new CustomMaskingStrategy());
    }

    public static MaskingStrategy getStrategy(String type) {
        return (type, (value, pattern) -> (".", "*")); // Desensitization by default    }
}

3.5 Universal Desensitization Processor

import ;
import ;

@Component
public class GeneralDataMaskingProcessor {

    public void maskSensitiveData(Object obj) throws IllegalAccessException {
        Class<?> clazz = ();
        for (Field field : ()) {
            if (()) {
                (true);
                Object value = (obj);
                if (value != null) {
                    String maskedValue = maskValue((), ());
                    (obj, maskedValue);
                }
            }
        }
    }

    private String maskValue(String value, Sensitive sensitive) {
        String type = ();
        String pattern = ();
        
        MaskingStrategy strategy = (type);
        return (value, pattern);
    }
}

3.6 Use examples

1. Create user entity class

public class User {

    private Long id;

    @Sensitive(type = "phone")
    private String phoneNumber;

    @Sensitive(type = "idCard")
    private String idCard;

    @Sensitive(type = "custom", pattern = "\d{3}-\d{4}") // Custom mode    private String customField;

    private String name;

    // Getters and Setters
}

2. Call the desensitization processor at the service layer

import ;
import ;

@Service
public class UserService {

    @Autowired
    private GeneralDataMaskingProcessor dataMaskingProcessor;

    public User getUser(Long id) {
        User user = findUserById(id); // Assume this is to get user information from the database        try {
            (user);
        } catch (IllegalAccessException e) {
            ();
        }
        return user;
    }

    private User findUserById(Long id) {
        // Simulate to get users from the database        return new User(id, "13812345678", "123456789012345678", "123-4567", "John Doe");
    }
}

3. Test the desensitization function

import ;
import ;
import ;

import static ;

@SpringBootTest
public class UserServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void testGetUser() {
        User user = (1L);
        assertThat(()).isEqualTo("138****5678");
        assertThat(()).isEqualTo("123456****5678");
        assertThat(()).isEqualTo("123-****"); // Custom desensitization    }
}

4. Summary

Through the above steps, the data desensitization function is implemented in the Spring Boot project. Using custom annotations and processors combined with policy patterns, sensitive information can be flexibly desensitized.

This is the end of this article about the detailed explanation of the methods of implementing data desensitization in SpringBoot. For more related SpringBoot data desensitization content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!