前言
某次新来的同事,在开发环境执行了这样的代码:
// 反例:直接将生产数据同步到测试环境
public void syncUserToTest(User user) {
testDB.insert(user); // 包含手机号、身份证等敏感字段
}
直接将生产的数据,比如:手机号、身份证等敏感字段,同步到了测试环境。
结果1天后,受到了公司领导的批评。
这个案例揭示了数据脱敏的极端重要性。
这篇文章给大家分享3种常用的数据脱敏方案,希望对你会有所帮助。
方案1:字符串替换(青铜级)
技术原理:通过正则表达式对敏感数据进行部分字符替换
典型代码实现:
public class StringMasker {
// 手机号脱敏:13812345678 → 138****5678
public static String maskMobile(String mobile) {
return mobile.replaceAll("(\d{3})\d{4}(\d{4})", "$1****$2");
}
// 身份证脱敏:110101199003077777 → 1101********7777
public static String maskIdCard(String idCard) {
if (idCard.length() == 18) {
return idCard.replaceAll("(\d{4})\d{10}(\w{4})", "$1****$2");
}
return idCard; // 处理15位旧身份证
}
}
使用正则表达式将关键字字段替换成了*
适用场景对比:
优缺点分析:
- ✅ 优点:实现简单、性能高(时间复杂度O(n))
- ❌ 缺点:
-
- 无法恢复原始数据
- 正则表达式需考虑多国数据格式差异
- 存在模式被破解风险(如固定位置替换)
方案2:加密算法(白银级)
加密算法选型:
算法类型 | 代表算法 | 特点 | 适用场景 |
---|---|---|---|
对称加密 | AES | 加解密快,密钥管理复杂 | 支付信息存储 |
非对称加密 | RSA | 速度慢,安全性高 | 密钥交换 |
国密算法 | SM4 | 符合国家标准 | 政府/金融系统 |
完整实现示例:
public class AESEncryptor {
privatestaticfinal String ALGORITHM = "AES/GCM/NoPadding";
privatestaticfinalint TAG_LENGTH = 128; // 认证标签长度
public static String encrypt(String plaintext, SecretKey key) {
byte[] iv = newbyte[12]; // GCM推荐12字节IV
SecureRandom random = new SecureRandom();
random.nextBytes(iv);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(TAG_LENGTH, iv));
byte[] ciphertext = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(iv) + ":" +
Base64.getEncoder().encodeToString(ciphertext);
}
// 解密方法类似...
}
密钥管理方案对比:
顺便吆喝一句,技术大厂机遇,前后端测试捞人,待遇还可以~
方案3:数据遮蔽(黄金级)
数据库层实现数据遮蔽:
-- 创建脱敏视图
CREATE VIEW masked_customers AS
SELECT
id,
CONCAT(SUBSTR(name,1,1), '***') AS name,
CONCAT(SUBSTR(mobile,1,3), '****', SUBSTR(mobile,8,4)) AS mobile
FROM customers;
-- 使用列级权限控制
GRANT SELECT (id, name, mobile) ON masked_customers TO test_user;
创建数据脱敏视图,在视图中将关键字段做遮蔽。
然后在后面需要用到这些字段的代码,需要统一从视图中查询数据。
代理层实现(ShardingSphere示例) :
rules:
-!MASK
tables:
user:
columns:
phone:
maskAlgorithm:phone_mask
maskAlgorithms:
phone_mask:
type:MD5
props:
salt:abcdefg123456
性能影响测试数据:
数据量 | 原始查询(ms) | 遮蔽查询(ms) | 性能损耗 |
---|---|---|---|
10万 | 120 | 145 | 20.8% |
100万 | 980 | 1150 | 17.3% |
1000万 | 10500 | 12200 | 16.2% |
——转载自:苏三说技术