import re from .crypto_sha256 import sha256 from .encoding_hex_hex_encode import hex_encode from .encoding_utf8_utf8_encode import utf8_encode _PURPOSE = re.compile(r"[a-z0-9-]{1,40}") def check_email_token_purpose(purpose: str) -> None: """Refuses a purpose that is not 1 to 40 characters of a-z, 0-9 and -.""" if not isinstance(purpose, str) or not _PURPOSE.fullmatch(purpose): raise ValueError("purpose must be 1 to 40 characters of a-z, 0-9 and -") def hash_email_token(token: str, purpose: str) -> str: """The stored key for a token: the hex SHA-256 of the purpose, ":" and the token, so a token issued for one purpose never matches another.""" check_email_token_purpose(purpose) if not isinstance(token, str) or len(token) == 0: raise ValueError("token must be a non-empty string") return hex_encode(sha256(utf8_encode(purpose + ":" + token)))