第5章:敏感数据(Sensitive Data)
一、导读
1.1 本章学习目标
第5章讲解敏感数据的保护——加密、哈希、脱敏。
本章的核心学习目标包括:
- 理解加密的基本概念:对称加密、非对称加密
- 掌握密码哈希的最佳实践
- 学会数据脱敏技术
- 理解密钥管理的重要性
1.2 为什么本章如此重要
数据泄露是最常见的安全事件。即使系统被攻破,正确加密的数据也能保护用户隐私。
1.3 核心问题引导
对称加密和非对称加密有什么区别?各适用于什么场景?
为什么不能用 MD5/SHA1 存储密码?
数据脱敏有哪些常用技术?
密钥管理为什么是安全中最难的部分?
二、核心概念详解
2.1 加密基础
对称加密:加密和解密使用同一个密钥
→ AES-256:速度快,适合大量数据
→ 问题:如何安全地分发密钥?
非对称加密:公钥加密,私钥解密
→ RSA、ECC:速度慢,适合密钥交换
→ 公钥可以公开,私钥必须保密2.2 密码哈希
java
// 危险!MD5 和 SHA1 已被攻破
String hash = DigestUtils.md5Hex(password); // 不安全!
// 安全:使用 bcrypt
String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt(12));
// 验证
boolean matches = BCrypt.checkpw(inputPassword, hashedPassword);
// 其他选择:Argon2、scrypt2.3 数据脱敏
java
// 邮箱脱敏
public String maskEmail(String email) {
int atIndex = email.indexOf('@');
if (atIndex <= 2) return email;
return email.substring(0, 2) + "***" + email.substring(atIndex);
}
// alice@example.com → al***@example.com
// 手机号脱敏
public String maskPhone(String phone) {
return phone.substring(0, 3) + "****" + phone.substring(7);
}
// 13812345678 → 138****5678
// 信用卡号脱敏
public String maskCard(String card) {
return "****-****-****-" + card.substring(card.length() - 4);
}2.4 密钥管理
密钥管理最佳实践:
1. 永远不要在代码中硬编码密钥
2. 使用密钥管理服务(KMS)
3. 定期轮换密钥
4. 分离不同环境的密钥
5. 限制密钥的访问权限三、实战案例
3.1 案例一:AES 加密文件
java
public class FileEncryption {
public void encrypt(Path inputFile, Path outputFile, SecretKey key) throws Exception {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] iv = cipher.getIV();
try (OutputStream os = Files.newOutputStream(outputFile)) {
os.write(iv); // 写入 IV
try (InputStream is = Files.newInputStream(inputFile)) {
byte[] buffer = new byte[8192];
int read;
while ((read = is.read(buffer)) != -1) {
byte[] encrypted = cipher.update(buffer, 0, read);
os.write(encrypted);
}
byte[] finalBlock = cipher.doFinal();
os.write(finalBlock);
}
}
}
}四、本章小结
对称加密:AES-256,适合大量数据。
非对称加密:RSA/ECC,适合密钥交换。
密码哈希:bcrypt/Argon2,永远不要明文存储密码。
数据脱敏:在日志、测试、展示中隐藏敏感数据。
五、思考与练习
为什么密码哈希需要加盐(salt)?
AES 的 GCM 模式和 CBC 模式有什么区别?
设计一个完整的密钥管理方案。