Java數(shù)據(jù)脫敏的常用方式總結(jié)
引言
大家好!今天我們要聊一聊數(shù)據(jù)脫敏。這個詞聽起來像特工電影里的高科技武器,其實它就是給敏感數(shù)據(jù)穿上“偽裝衣”,防止“壞人”偷 窺。無論是銀行賬號、身份證號碼、郵箱地址,這些信息都需要時刻保持低調(diào)。如何低調(diào)?沒錯——數(shù)據(jù)脫敏,Java 已準(zhǔn)備好為你服務(wù)!
1. 什么是數(shù)據(jù)脫敏?你是不是以為要給數(shù)據(jù)打馬賽克?
數(shù)據(jù)脫敏,簡單來說就是“數(shù)據(jù)打碼”,讓重要數(shù)據(jù)在數(shù)據(jù)庫、日志、前端展示時只露出“有限真容”。就像電影里的特工,只看部分特征,整個人你是認不出來的。
2. 為什么數(shù)據(jù)脫敏很重要?因為隱私就是“金庫”
數(shù)據(jù)脫敏的重要性不言而喻。想象一下,你的銀行賬號、電話號碼被人公開了,會是什么感覺?這不僅是隱私問題,也是信息安全問題。所以無論是保護個人隱私還是遵守法律法規(guī),數(shù)據(jù)脫敏都是必要的手段。
3. Java 數(shù)據(jù)脫敏的常用方式
Java 提供了多種數(shù)據(jù)脫敏方式,今天咱們來聊幾種經(jīng)典實用的“偽裝術(shù)”。
3.1 字符遮蓋法(Masking)
這是最常見的脫敏手段之一,簡單粗暴。通過用“*”或者其他字符代替敏感數(shù)據(jù)的中間部分,數(shù)據(jù)仍然保留部分可識別信息,但不會透露完整內(nèi)容。
public class DataMaskingUtil {
// 手機號脫敏
public static String maskPhoneNumber(String phoneNumber) {
if (phoneNumber == null || phoneNumber.length() != 11) {
return phoneNumber; // 無法脫敏時,直接返回原號碼
}
return phoneNumber.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
}
// 身份證號脫敏
public static String maskIdCardNumber(String idCard) {
if (idCard == null || idCard.length() != 18) {
return idCard; // 不符合18位身份證長度
}
return idCard.replaceAll("(\\d{6})\\d{8}(\\d{4})", "$1********$2");
}
// 郵箱地址脫敏
public static String maskEmailAddress(String email) {
if (email == null || !email.contains("@")) {
return email;
}
return email.replaceAll("(\\w{2})\\w*(\\w{1}@.*)", "$1****$2");
}
// 銀行卡號脫敏
public static String maskBankCardNumber(String cardNumber) {
if (cardNumber == null || cardNumber.length() < 16) {
return cardNumber;
}
return cardNumber.replaceAll("(\\d{4})\\d{8,12}(\\d{4})", "$1****$2");
}
// 示例:脫敏信用卡號只保留最后4位
public static String maskCreditCardNumber(String cardNumber) {
if (cardNumber == null || cardNumber.length() < 16) {
return cardNumber;
}
return cardNumber.replaceAll("\\d{12}(\\d{4})", "**** **** **** $1");
}
}
3.2 數(shù)據(jù)替換法(Substitution)
有時候,我們不僅要遮蓋數(shù)據(jù),還要替換數(shù)據(jù)。通過生成假數(shù)據(jù)來掩飾真實信息。例如,將某個身份證號替換為隨機生成的虛擬號碼:
import java.util.Random;
public class DataSubstitutionUtil {
// 隨機生成偽身份證號
public static String substituteIdCardNumber() {
String prefix = "110101"; // 代表北京市
String suffix = generateRandomDigits(8) + "****"; // 隨機生成8位數(shù),再加馬賽克
return prefix + suffix;
}
// 隨機生成指定位數(shù)的數(shù)字
private static String generateRandomDigits(int length) {
Random random = new Random();
StringBuilder digits = new StringBuilder();
for (int i = 0; i < length; i++) {
digits.append(random.nextInt(10));
}
return digits.toString();
}
// 測試身份證替換
public static void main(String[] args) {
System.out.println("替換身份證號: " + substituteIdCardNumber());
}
}
3.3 數(shù)據(jù)加密法(Encryption)
加密脫敏是高級手段,通過加密算法將數(shù)據(jù)轉(zhuǎn)換為無法識別的密文,只有擁有密鑰的用戶才能解密。這里我們使用 Java 提供的 Cipher 類來進行對稱加密。
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;
public class DataEncryptionUtil {
private static final String ALGORITHM = "AES"; // 使用 AES 對稱加密算法
// 生成隨機密鑰
public static SecretKey generateKey() throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
keyGenerator.init(128);
return keyGenerator.generateKey();
}
// 加密數(shù)據(jù)
public static String encrypt(String data, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
// 解密數(shù)據(jù)
public static String decrypt(String encryptedData, SecretKey secretKey) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
byte[] decryptedBytes = cipher.doFinal(decodedBytes);
return new String(decryptedBytes);
}
// 示例測試加密解密
public static void main(String[] args) throws Exception {
SecretKey secretKey = generateKey();
String originalData = "SensitiveData123";
String encryptedData = encrypt(originalData, secretKey);
String decryptedData = decrypt(encryptedData, secretKey);
System.out.println("原始數(shù)據(jù): " + originalData);
System.out.println("加密后的數(shù)據(jù): " + encryptedData);
System.out.println("解密后的數(shù)據(jù): " + decryptedData);
}
}
3.4 哈希法(Hashing)
哈希是一種不可逆的脫敏方式,通常用于密碼或驗證場景。數(shù)據(jù)經(jīng)過哈希處理后,無法直接還原為原始數(shù)據(jù),只能用于驗證匹配。我們可以用 Java 中的 MessageDigest 來實現(xiàn)哈希。
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class DataHashingUtil {
// 對數(shù)據(jù)進行 SHA-256 哈希
public static String hashData(String data) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest(data.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : hashBytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("哈希算法異常", e);
}
}
// 示例測試
public static void main(String[] args) {
String originalData = "SensitiveData123";
String hashedData = hashData(originalData);
System.out.println("原始數(shù)據(jù): " + originalData);
System.out.println("哈希后的數(shù)據(jù): " + hashedData);
}
}
4. 數(shù)據(jù)脫敏的實際應(yīng)用場景
在實際項目中,數(shù)據(jù)脫敏是一個綜合性的策略,通常用在:
- 日志系統(tǒng):日志里可能會記錄很多敏感信息,直接展示會導(dǎo)致泄露風(fēng)險。
public static void logWithMasking(String userData) {
System.out.println("用戶信息: " + maskPhoneNumber(userData));
}
- 數(shù)據(jù)庫查詢展示:很多時候我們從數(shù)據(jù)庫中查詢出的數(shù)據(jù)需要做脫敏處理再展示給前端。
public static List<String> getMaskedUserData(List<String> rawData) {
return rawData.stream()
.map(DataMaskingUtil::maskPhoneNumber) // 對手機號脫敏
.collect(Collectors.toList());
}
- API 響應(yīng):后臺提供的 API 中也要對返回給前端的數(shù)據(jù)進行脫敏處理,避免敏感信息泄露。
public ResponseEntity<UserInfoDto> getUserInfo(Long userId) {
UserInfoDto userInfo = userService.findById(userId);
userInfo.setPhoneNumber(DataMaskingUtil.maskPhoneNumber(userInfo.getPhoneNumber()));
return ResponseEntity.ok(userInfo);
}
5. 總結(jié)
Java 數(shù)據(jù)脫敏不僅僅是防止信息泄露的工具,它還是保護用戶隱私的一道防線。在實際開發(fā)中,選擇合適的脫敏方式(遮蓋、替換、加密或哈希),能大大提升系統(tǒng)的安全性。
到此這篇關(guān)于Java數(shù)據(jù)脫敏的常用方式總結(jié)的文章就介紹到這了,更多相關(guān)Java數(shù)據(jù)脫敏內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring創(chuàng)建bean對象三種方式代碼實例
這篇文章主要介紹了Spring創(chuàng)建bean對象三種方式代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-07-07
使用?Spring?Boot?Admin?監(jiān)控應(yīng)用狀態(tài)的詳細過程
這篇文章主要介紹了使用?Spring?Boot?Admin?監(jiān)控應(yīng)用狀態(tài),該模塊采集應(yīng)用的內(nèi)部信息,并暴露給外部的模塊,支持?HTTP?和?JMX,并可以與一些第三方監(jiān)控系統(tǒng)(如?Prometheus)整合,需要的朋友可以參考下2022-09-09
Java IO三大模型(BIO/NIO/AIO)的使用總結(jié)
相信很多Java開發(fā)剛接觸IO模型時,都會被「BIO、NIO、AIO」「同步、異步、阻塞、非阻塞」這些概念繞暈,下面就來詳細的介紹一下 IO三大模型的使用,感興趣的可以了解一下2026-02-02

