掩码敏感数据 Args: data: 要掩码的数据 mask_char: 掩码字符 Returns: 掩码后的数据
(data: Union[str, Dict, List], mask_char: str = "*")
| 467 | |
| 468 | |
| 469 | def mask_sensitive_data(data: Union[str, Dict, List], mask_char: str = "*") -> Union[str, Dict, List]: |
| 470 | """ |
| 471 | 掩码敏感数据 |
| 472 | |
| 473 | Args: |
| 474 | data: 要掩码的数据 |
| 475 | mask_char: 掩码字符 |
| 476 | |
| 477 | Returns: |
| 478 | 掩码后的数据 |
| 479 | """ |
| 480 | if isinstance(data, str): |
| 481 | # 如果是邮箱,掩码中间部分 |
| 482 | if "@" in data: |
| 483 | local, domain = data.split("@", 1) |
| 484 | if len(local) > 2: |
| 485 | masked_local = local[0] + mask_char * (len(local) - 2) + local[-1] |
| 486 | else: |
| 487 | masked_local = mask_char * len(local) |
| 488 | return f"{masked_local}@{domain}" |
| 489 | |
| 490 | # 如果是 token 或密钥,掩码大部分内容 |
| 491 | if len(data) > 10: |
| 492 | return data[:4] + mask_char * (len(data) - 8) + data[-4:] |
| 493 | return mask_char * len(data) |
| 494 | |
| 495 | elif isinstance(data, dict): |
| 496 | masked_dict = {} |
| 497 | for key, value in data.items(): |
| 498 | # 敏感字段名 |
| 499 | sensitive_keys = ["password", "token", "secret", "key", "auth", "credential"] |
| 500 | if any(sensitive in key.lower() for sensitive in sensitive_keys): |
| 501 | masked_dict[key] = mask_sensitive_data(value, mask_char) |
| 502 | else: |
| 503 | masked_dict[key] = value |
| 504 | return masked_dict |
| 505 | |
| 506 | elif isinstance(data, list): |
| 507 | return [mask_sensitive_data(item, mask_char) for item in data] |
| 508 | |
| 509 | return data |
| 510 | |
| 511 | |
| 512 | def calculate_md5(data: Union[str, bytes]) -> str: |
nothing calls this directly
no outgoing calls
no test coverage detected