PII Redaction

PII Redaction 是在将用户输入发送给 LLM 前,检测并脱敏个人可识别信息(手机号、身份证、银行卡号)的技术。

#type / concept #status / evergreen #tech / ai #tech / security

[!info] related notes

PII Redaction

一句话定义

PII Redaction 是在将用户输入发送给 LLM 前,检测并脱敏个人可识别信息(PII)的技术。用户的手机号、身份证号、银行卡号不应该发送给第三方 LLM。

核心原理

PII 类型

类型示例脱敏方式
手机号13812345678138****5678
身份证110105199001011234110105****01011234
银行卡62220212345678906222****7890
邮箱test@example.comt***@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

常见坑

  1. 不做 PII 脱敏: 用户隐私数据发送给第三方
  2. 脱敏不完整: 新的 PII 格式没有覆盖
  3. 脱敏后不可逆: 需要保留映射关系用于回复

参考资料

创建于 2026/6/30 更新于 2026/7/15