"""REL1 · utilidades comunes: clave HMAC (la del satélite BORME, nunca impresa), hash de personas, normalizadores.""" import hashlib, hmac, os, re, stat, unicodedata TEXTO_HUELLA = b"buscalicitaciones-borme-huella-v1" # el mismo del satélite: la huella debe ser 1300ad242603 HUELLA_ESPERADA = "1300ad242603" def leer_clave() -> bytes: p = os.environ.get('REL1_HMAC_CLAVE') if not p or not os.path.isfile(p): raise SystemExit('falta la clave HMAC (REL1_HMAC_CLAVE)') if stat.S_IMODE(os.stat(p).st_mode) & 0o077: raise SystemExit('la clave HMAC tiene permisos de grupo u otros') k = open(p, 'rb').read().strip() if len(k) < 32: raise SystemExit('clave HMAC demasiado corta') if hmac.new(k, TEXTO_HUELLA, hashlib.sha256).hexdigest()[:12] != HUELLA_ESPERADA: raise SystemExit('la huella de la clave no es la del satélite') return k def huella(k: bytes) -> str: return hmac.new(k, TEXTO_HUELLA, hashlib.sha256).hexdigest()[:12] def pf_hmac(k: bytes, texto: str) -> str: """Clave opaca de una persona física: 'PF:' + HMAC-SHA256(clave, 'rel1-pf|' + texto)[:20].""" return 'PF:' + hmac.new(k, ('rel1-pf|' + texto).encode(), hashlib.sha256).hexdigest()[:20] def sin_tildes(s): return ''.join(ch for ch in unicodedata.normalize('NFKD', s or '') if not unicodedata.combining(ch)) def nif_limpio(s): return re.sub(r'[^A-Z0-9]', '', sin_tildes(str(s or '')).upper()) # Clase del NIF (personas físicas: DNI/NIE; jurídicas: letra de sociedad o entidad) RE_DNI = re.compile(r'^[0-9]{8}[A-Z]$'); RE_NIE = re.compile(r'^[XYZ][0-9]{7}[A-Z]$') RE_PJ = re.compile(r'^[ABCDEFGHJNPQRSUVW][0-9]{7}[0-9A-J]$') def clase_nif(n): if not n: return 'sin_nif' if RE_DNI.match(n) or RE_NIE.match(n) or re.match(r'^[KLM][0-9]{7}[A-Z]$', n): return 'pf' if RE_PJ.match(n): return 'pj' if '*' in str(n): return 'enmascarado' return 'otro'