import base64 import hashlib from cryptography.fernet import Fernet from django.conf import settings class PhoneEncryption: """ 手机号 AES-256-GCM 加密存储 + SHA-256 哈希索引 存储字段:phone_encrypted(加密密文)+ phone_hash(哈希,用于精确查询) 显示:脱敏格式 138****1234 """ @staticmethod def encrypt(phone: str) -> str: """加密手机号,返回 base64 密文""" ... @staticmethod def decrypt(ciphertext: str) -> str: """解密返回明文""" ... @staticmethod def hash(phone: str) -> str: """返回 SHA-256 哈希(用于 DB 索引查询)""" ... @staticmethod def mask(phone: str) -> str: """返回脱敏格式:138****1234""" if not phone or len(phone) < 7: return "***" return phone[:3] + "****" + phone[-4:]