58 lines
1.7 KiB
Python
58 lines
1.7 KiB
Python
"""TOTP/RFC 6238 без внешней зависимости + recovery-коды."""
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import hashlib
|
|
import hmac
|
|
import secrets
|
|
import struct
|
|
import time
|
|
|
|
STEP = 30
|
|
DIGITS = 6
|
|
|
|
|
|
def new_secret() -> str:
|
|
return base64.b32encode(secrets.token_bytes(20)).decode().rstrip("=")
|
|
|
|
|
|
def _key(secret: str) -> bytes:
|
|
return base64.b32decode(secret.upper() + "=" * ((8 - len(secret) % 8) % 8))
|
|
|
|
|
|
def code_at(secret: str, counter: int) -> str:
|
|
digest = hmac.new(_key(secret), struct.pack(">Q", counter), hashlib.sha1).digest()
|
|
off = digest[-1] & 0x0F
|
|
num = struct.unpack(">I", digest[off:off + 4])[0] & 0x7FFFFFFF
|
|
return str(num % 10 ** DIGITS).zfill(DIGITS)
|
|
|
|
|
|
def verify(secret: str, code: str, at: float | None = None, window: int = 1) -> bool:
|
|
if not secret or not code or not str(code).isdigit() or len(str(code)) != DIGITS:
|
|
return False
|
|
counter = int((time.time() if at is None else at) // STEP)
|
|
return any(hmac.compare_digest(code_at(secret, counter + d), str(code))
|
|
for d in range(-window, window + 1))
|
|
|
|
|
|
def provisioning_uri(secret: str, email: str, issuer: str = "smeta") -> str:
|
|
from urllib.parse import quote
|
|
label = quote(f"{issuer}:{email}")
|
|
return f"otpauth://totp/{label}?secret={secret}&issuer={quote(issuer)}&digits=6&period=30"
|
|
|
|
|
|
def new_recovery_codes(n: int = 8) -> list[str]:
|
|
return [secrets.token_hex(5) for _ in range(n)]
|
|
|
|
|
|
def hash_recovery(code: str) -> str:
|
|
return hashlib.sha256(code.strip().lower().encode()).hexdigest()
|
|
|
|
|
|
def verify_recovery(code: str, hashes: list[str]) -> str | None:
|
|
h = hash_recovery(code)
|
|
for i, x in enumerate(hashes):
|
|
if hmac.compare_digest(h, x):
|
|
return str(i)
|
|
return None
|