Java數(shù)據(jù)脫敏的常用方式總結(jié)
引言
大家好!今天我們要聊一聊數(shù)據(jù)脫敏。這個(gè)詞聽起來像特工電影里的高科技武器,其實(shí)它就是給敏感數(shù)據(jù)穿上“偽裝衣”,防止“壞人”偷 窺。無論是銀行賬號、身份證號碼、郵箱地址,這些信息都需要時(shí)刻保持低調(diào)。如何低調(diào)?沒錯(cuò)——數(shù)據(jù)脫敏,Java 已準(zhǔn)備好為你服務(wù)!
1. 什么是數(shù)據(jù)脫敏?你是不是以為要給數(shù)據(jù)打馬賽克?
數(shù)據(jù)脫敏,簡單來說就是“數(shù)據(jù)打碼”,讓重要數(shù)據(jù)在數(shù)據(jù)庫、日志、前端展示時(shí)只露出“有限真容”。就像電影里的特工,只看部分特征,整個(gè)人你是認(rèn)不出來的。
2. 為什么數(shù)據(jù)脫敏很重要?因?yàn)殡[私就是“金庫”
數(shù)據(jù)脫敏的重要性不言而喻。想象一下,你的銀行賬號、電話號碼被人公開了,會(huì)是什么感覺?這不僅是隱私問題,也是信息安全問題。所以無論是保護(hù)個(gè)人隱私還是遵守法律法規(guī),數(shù)據(jù)脫敏都是必要的手段。
3. Java 數(shù)據(jù)脫敏的常用方式
Java 提供了多種數(shù)據(jù)脫敏方式,今天咱們來聊幾種經(jīng)典實(shí)用的“偽裝術(shù)”。
3.1 字符遮蓋法(Masking)
這是最常見的脫敏手段之一,簡單粗暴。通過用“*”或者其他字符代替敏感數(shù)據(jù)的中間部分,數(shù)據(jù)仍然保留部分可識別信息,但不會(huì)透露完整內(nèi)容。
public class DataMaskingUtil { // 手機(jī)號脫敏 public static String maskPhoneNumber(String phoneNumber) { if (phoneNumber == null || phoneNumber.length() != 11) { return phoneNumber; // 無法脫敏時(shí),直接返回原號碼 } 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í)候,我們不僅要遮蓋數(shù)據(jù),還要替換數(shù)據(jù)。通過生成假數(shù)據(jù)來掩飾真實(shí)信息。例如,將某個(gè)身份證號替換為隨機(jī)生成的虛擬號碼:
import java.util.Random; public class DataSubstitutionUtil { // 隨機(jī)生成偽身份證號 public static String substituteIdCardNumber() { String prefix = "110101"; // 代表北京市 String suffix = generateRandomDigits(8) + "****"; // 隨機(jī)生成8位數(shù),再加馬賽克 return prefix + suffix; } // 隨機(jī)生成指定位數(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
類來進(jìn)行對稱加密。
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 對稱加密算法 // 生成隨機(jī)密鑰 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)
哈希是一種不可逆的脫敏方式,通常用于密碼或驗(yàn)證場景。數(shù)據(jù)經(jīng)過哈希處理后,無法直接還原為原始數(shù)據(jù),只能用于驗(yàn)證匹配。我們可以用 Java 中的 MessageDigest
來實(shí)現(xiàn)哈希。
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class DataHashingUtil { // 對數(shù)據(jù)進(jìn)行 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ù)脫敏的實(shí)際應(yīng)用場景
在實(shí)際項(xiàng)目中,數(shù)據(jù)脫敏是一個(gè)綜合性的策略,通常用在:
- 日志系統(tǒng):日志里可能會(huì)記錄很多敏感信息,直接展示會(huì)導(dǎo)致泄露風(fēng)險(xiǎn)。
public static void logWithMasking(String userData) { System.out.println("用戶信息: " + maskPhoneNumber(userData)); }
- 數(shù)據(jù)庫查詢展示:很多時(shí)候我們從數(shù)據(jù)庫中查詢出的數(shù)據(jù)需要做脫敏處理再展示給前端。
public static List<String> getMaskedUserData(List<String> rawData) { return rawData.stream() .map(DataMaskingUtil::maskPhoneNumber) // 對手機(jī)號脫敏 .collect(Collectors.toList()); }
- API 響應(yīng):后臺提供的 API 中也要對返回給前端的數(shù)據(jù)進(jìn)行脫敏處理,避免敏感信息泄露。
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ù)脫敏不僅僅是防止信息泄露的工具,它還是保護(hù)用戶隱私的一道防線。在實(shí)際開發(fā)中,選擇合適的脫敏方式(遮蓋、替換、加密或哈希),能大大提升系統(tǒng)的安全性。
到此這篇關(guān)于Java數(shù)據(jù)脫敏的常用方式總結(jié)的文章就介紹到這了,更多相關(guān)Java數(shù)據(jù)脫敏內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MyBatisPlus+SpringBoot實(shí)現(xiàn)樂觀鎖功能詳細(xì)流程
樂觀鎖是針對一些特定問題的解決方案,主要解決丟失更新問題,下面這篇文章主要給大家介紹了關(guān)于MyBatisPlus+SpringBoot實(shí)現(xiàn)樂觀鎖功能的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03詳細(xì)理解JAVA面向?qū)ο蟮姆庋b,繼承,多態(tài),抽象
這篇文章主要介紹了Java基礎(chǔ)之面向?qū)ο髾C(jī)制(多態(tài)、繼承)底層實(shí)現(xiàn),文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-07-07why在重寫equals時(shí)還必須重寫hashcode方法分享
首先我們先來看下String類的源碼:可以發(fā)現(xiàn)String是重寫了Object類的equals方法的,并且也重寫了hashcode方法2013-10-10java 實(shí)現(xiàn)增量同步和自定義同步的操作
這篇文章主要介紹了java 實(shí)現(xiàn)增量同步和自定義同步的操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01java實(shí)現(xiàn)創(chuàng)建縮略圖、伸縮圖片比例生成的方法
這篇文章主要介紹了java實(shí)現(xiàn)創(chuàng)建縮略圖、伸縮圖片比例生成的方法,可實(shí)現(xiàn)針對圖片大小的縮放功能,是Java針對圖片操作的典型應(yīng)用,需要的朋友可以參考下2014-11-11java發(fā)送heartbeat心跳包(byte轉(zhuǎn)16進(jìn)制)
這篇文章主要介紹了java發(fā)送heartbeat心跳包(byte轉(zhuǎn)16進(jìn)制),需要的朋友可以參考下2014-05-05Java 負(fù)載均衡的 5 種算法實(shí)現(xiàn)原理
這篇文章主要介紹Java 負(fù)載均衡的 5 種算法實(shí)現(xiàn)原理,負(fù)載均衡能夠平均分配客戶請求到服 務(wù)器陣列,借此提供快速獲取重要數(shù)據(jù),解決大量并發(fā)訪問服務(wù)問題,這種集群技術(shù)可以用最少的投資獲得接近于大型主機(jī)的性能。下面就來看看文章的具體內(nèi)容吧2021-10-10