introduction
Hello everyone! Today we are going to talk about data desensitization. This word sounds like a high-tech weapon in a agent's movie, but in fact it is to put "disguised clothes" on sensitive data to prevent "bad people" from sneaking. Whether it is a bank account, ID number, or email address, these information needs to be kept low-key at all times. How to keep a low profile? That's right - data desensitization, Java is ready to serve you!
1. What is data desensitization? Do you think you want to mosaic the data?
Data desensitization, simply put, is "data coding", allowing important data to only reveal "limited true appearance" when displayed in databases, logs, and front-end. Just like the agent in the movie, you can't recognize the whole person by looking at only some of the characteristics.
2. Why is data desensitization important? Because privacy is the "treasury"
The importance of data desensitization is self-evident. Imagine how it would be like to have your bank account and phone number been made public? This is not only a privacy issue, but also an information security issue. Therefore, whether it is protecting personal privacy or complying with laws and regulations, data desensitization is a necessary means.
3. Common ways to desensitize Java data
Java provides a variety of data desensitization methods. Today we will talk about several classic and practical "camouflage techniques".
3.1 Character masking method
This is one of the most common desensitization methods, simple and crude. By replacing the middle part of the sensitive data with "*" or other characters, the data still retains partially identifiable information, but does not disclose the complete content.
public class DataMaskingUtil { // Desensitization of mobile phone number public static String maskPhoneNumber(String phoneNumber) { if (phoneNumber == null || () != 11) { return phoneNumber; // When desensitization cannot be done, return to the original number directly } return ("(\\d{3})\\d{4}(\\d{4})", "$1****$2"); } // Identity card number desensitized public static String maskIdCardNumber(String idCard) { if (idCard == null || () != 18) { return idCard; // Does not meet the length of the 18-digit ID card } return ("(\\d{6})\\d{8}(\\d{4})", "$1********$2"); } // Desensitized email address public static String maskEmailAddress(String email) { if (email == null || !("@")) { return email; } return ("(\\w{2})\\w*(\\w{1}@.*)", "$1****$2"); } // Desensitization of bank card number public static String maskBankCardNumber(String cardNumber) { if (cardNumber == null || () < 16) { return cardNumber; } return ("(\\d{4})\\d{8,12}(\\d{4})", "$1****$2"); } // Example: Only the last 4 digits of the desensitized credit card number are retained public static String maskCreditCardNumber(String cardNumber) { if (cardNumber == null || () < 16) { return cardNumber; } return ("\\d{12}(\\d{4})", "**** **** **** $1"); } }
3.2 Data substitution method
Sometimes, we not only have to cover up the data, but alsoReplace data. Conceal the real information by generating fake data. For example, replace an ID number with a randomly generated virtual number:
import ; public class DataSubstitutionUtil { // Randomly generate pseudo-id number public static String substituteIdCardNumber() { String prefix = "110101"; // Representative to Beijing String suffix = generateRandomDigits(8) + "****"; // Randomly generate 8 digits, add mosaic return prefix + suffix; } // Randomly generates a number of specified digits private static String generateRandomDigits(int length) { Random random = new Random(); StringBuilder digits = new StringBuilder(); for (int i = 0; i < length; i++) { ((10)); } return (); } // Test ID card replacement public static void main(String[] args) { ("Replace ID number: " + substituteIdCardNumber()); } }
3.3 Data encryption method (Encryption)
Encryption desensitization is an advanced method. The data is converted into unrecognized ciphertext through encryption algorithms, and only users with the key can decrypt it. Here we use the provided by JavaCipher
Classes for symmetric encryption.
import ; import ; import ; import .Base64; public class DataEncryptionUtil { private static final String ALGORITHM = "AES"; // Use AES symmetric encryption algorithm // Generate random keys public static SecretKey generateKey() throws Exception { KeyGenerator keyGenerator = (ALGORITHM); (128); return (); } // Encrypt data public static String encrypt(String data, SecretKey secretKey) throws Exception { Cipher cipher = (ALGORITHM); (Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = (()); return ().encodeToString(encryptedBytes); } // Decrypt the data public static String decrypt(String encryptedData, SecretKey secretKey) throws Exception { Cipher cipher = (ALGORITHM); (Cipher.DECRYPT_MODE, secretKey); byte[] decodedBytes = ().decode(encryptedData); byte[] decryptedBytes = (decodedBytes); return new String(decryptedBytes); } // Sample test encryption decryption public static void main(String[] args) throws Exception { SecretKey secretKey = generateKey(); String originalData = "SensitiveData123"; String encryptedData = encrypt(originalData, secretKey); String decryptedData = decrypt(encryptedData, secretKey); ("Raw Data: " + originalData); ("Encrypted data: " + encryptedData); ("Decrypted data: " + decryptedData); } }
3.4 Hashing
Hash is an irreversible desensitization method that is often used in password or verification scenarios. After the data has been hashed, it cannot be directly restored to the original data and can only be used to verify the match. We can use theMessageDigest
to implement hashing.
import ; import ; public class DataHashingUtil { // SHA-256 hashing the data public static String hashData(String data) { try { MessageDigest digest = ("SHA-256"); byte[] hashBytes = (()); StringBuilder hexString = new StringBuilder(); for (byte b : hashBytes) { String hex = (0xff & b); if (() == 1) { ('0'); } (hex); } return (); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Hash algorithm exception", e); } } // Sample test public static void main(String[] args) { String originalData = "SensitiveData123"; String hashedData = hashData(originalData); ("Raw Data: " + originalData); ("Hased data: " + hashedData); } }
4. Practical application scenarios of data desensitization
In actual projects, data desensitization is aComprehensive strategy, usually used in:
- Log system: A lot of sensitive information may be recorded in the log, and direct display will lead to the risk of leakage.
public static void logWithMasking(String userData) { ("User Information: " + maskPhoneNumber(userData)); }
- Database query display: Many times the data we query from the database needs to be desensitized before being displayed to the front end.
public static List<String> getMaskedUserData(List<String> rawData) { return () .map(DataMaskingUtil::maskPhoneNumber) // Desensitization to mobile phone numbers .collect(()); }
- API Response: The data returned to the front end should also be desensitized in the API provided by the backend to avoid leakage of sensitive information.
public ResponseEntity<UserInfoDto> getUserInfo(Long userId) { UserInfoDto userInfo = (userId); ((())); return (userInfo); }
5. Summary
Java data desensitization is not just a tool to prevent information leakage, it is also a line of defense to protect user privacy. In actual development, choosing the appropriate desensitization method (covering, replacing, encryption or hashing) can greatly improve the security of the system.
This is the end of this article about the common methods of Java data desensitization. For more related Java 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!