"""Encryption of personal identity codes (spec 4: stored encrypted, HMAC for duplicates).""" import hashlib import hmac from functools import cache from cryptography.fernet import Fernet, MultiFernet from django.conf import settings from django.core.checks import Error, register @cache def _fernet() -> MultiFernet: return MultiFernet([Fernet(key.encode()) for key in settings.FIELD_ENCRYPTION_KEYS]) def encrypt(code: str) -> str: return _fernet().encrypt(code.encode()).decode() def decrypt(token: str) -> str: return _fernet().decrypt(token.encode()).decode() def fingerprint(code: str) -> str: key = settings.PERSONAL_ID_HASH_KEY.encode() return hmac.new(key, code.strip().upper().encode(), hashlib.sha256).hexdigest() @register() def check_keys(app_configs: object, **kwargs: object) -> list[Error]: errors = [] if not settings.FIELD_ENCRYPTION_KEYS: errors.append(Error("FIELD_ENCRYPTION_KEYS is not set in .env", id="customers.E001")) else: try: _fernet() except ValueError: errors.append( Error("FIELD_ENCRYPTION_KEYS has an invalid Fernet key", id="customers.E002") ) if len(settings.PERSONAL_ID_HASH_KEY) < 32: errors.append( Error("PERSONAL_ID_HASH_KEY must be at least 32 characters", id="customers.E003") ) return errors