Functional Weave
Code in Rust

auth.totp@1.0.0

impl/python/hotp_code.py

2,300 bytes · the Python implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from typing import Any, List

from .auth_totp_types import TotpAlgorithm, TotpSettings
from .crypto_hmac_sha1 import hmac_sha1  ← from crypto.hmac-sha1 ^1.0.0 · built alongside by fune
from .crypto_hmac_sha256 import hmac_sha256  ← from crypto.hmac-sha256 ^1.0.0 · built alongside by fune
from .encoding_base32_base32_decode import base32_decode

MAX_SAFE = 9007199254740991


def is_totp_whole(value: Any) -> bool:
    """Whole number from 0 to 2^53 - 1: the range all three languages agree on."""
    return type(value) is int and 0 <= value <= MAX_SAFE


def check_totp_digits(digits: Any) -> None:
    if type(digits) is not int or digits not in (6, 7, 8):
        raise ValueError("digits must be 6, 7 or 8")


def check_totp_algorithm(algorithm: Any) -> None:
    if algorithm not in ("SHA1", "SHA256"):
        raise ValueError("algorithm must be SHA1 or SHA256")


def check_totp_settings(settings: TotpSettings) -> None:
    check_totp_algorithm(settings.algorithm)
    check_totp_digits(settings.digits)
    if not is_totp_whole(settings.period) or settings.period < 1:
        raise ValueError("period must be a whole number of seconds, 1 or more")


def totp_secret_key(secret: str) -> List[int]:
    """The secret's bytes. Old Google Authenticator secrets are 80 bits, so
    10 bytes is the least accepted; new ones from totp_secret are 16 or more."""
    key = base32_decode(secret)
    if len(key) < 10:
        raise ValueError("secret must decode to at least 10 bytes")
    return key


def hotp_from_key(key: List[int], counter: int, digits: int, algorithm: str) -> str:
    """RFC 4226 section 5.3: HMAC of the 8-byte big-endian counter, then
    dynamic truncation."""
    message = list(counter.to_bytes(8, "big"))
    mac = hmac_sha1(key, message) if algorithm == "SHA1" else hmac_sha256(key, message)
    offset = mac[-1] & 15
    binary = ((mac[offset] & 127) << 24) | (mac[offset + 1] << 16) | (mac[offset + 2] << 8) | mac[offset + 3]
    return str(binary % (10 ** digits)).zfill(digits)


def hotp_code(secret: str, counter: int, digits: int, algorithm: TotpAlgorithm) -> str:
    """The RFC 4226 HOTP code for one counter value."""
    if not is_totp_whole(counter):
        raise ValueError("counter must be a whole number from 0 to 2^53 - 1")
    check_totp_digits(digits)
    check_totp_algorithm(algorithm)
    return hotp_from_key(totp_secret_key(secret), counter, digits, algorithm)