PII Redaction
PII Redaction 是在将用户输入发送给 LLM 前,检测并脱敏个人可识别信息(手机号、身份证、银行卡号)的技术。
#type / concept
#status / evergreen
#tech / ai
#tech / security
[!info] related notes
- 所属 MOC: AI Agent Application MOC, Security MOC
- 相关: Content Safety
PII Redaction
一句话定义
PII Redaction 是在将用户输入发送给 LLM 前,检测并脱敏个人可识别信息(PII)的技术。用户的手机号、身份证号、银行卡号不应该发送给第三方 LLM。
核心原理
PII 类型
| 类型 | 示例 | 脱敏方式 |
|---|---|---|
| 手机号 | 13812345678 | 138****5678 |
| 身份证 | 110105199001011234 | 110105****01011234 |
| 银行卡 | 6222021234567890 | 6222****7890 |
| 邮箱 | test@example.com | t***@example.com |
Python 实现
import re
class PIIRedactor:
PATTERNS = {
"phone": (r'1[3-9]\d{9}', lambda m: m.group()[:3] + "****" + m.group()[-4:]),
"id_card": (r'\d{17}[\dXx]', lambda m: m.group()[:6] + "****" + m.group()[-8:]),
"bank_card": (r'\d{16,19}', lambda m: m.group()[:4] + "****" + m.group()[-4:]),
"email": (r'[\w.]+@[\w.]+', lambda m: m.group()[0] + "***@" + m.group().split("@")[1]),
}
def redact(self, text: str) -> tuple[str, dict]:
redacted = text
pii_found = {}
for pii_type, (pattern, replacer) in self.PATTERNS.items():
matches = re.findall(pattern, redacted)
if matches:
pii_found[pii_type] = len(matches)
redacted = re.sub(pattern, replacer, redacted)
return redacted, pii_found
常见坑
- 不做 PII 脱敏: 用户隐私数据发送给第三方
- 脱敏不完整: 新的 PII 格式没有覆盖
- 脱敏后不可逆: 需要保留映射关系用于回复