Functional Weave
Code in Rust

auth.totp@1.0.0

impl/python/totp_secret.py

784 bytes · the Python implementation · view raw

from typing import Sequence

from .encoding_base32_base32_encode import base32_encode


def totp_secret(random_bytes: Sequence[int]) -> str:
    """A new secret from the caller's random bytes (secrets.token_bytes(20)),
    as unpadded base32. A pure function cannot read randomness itself."""
    if isinstance(random_bytes, (str, dict)) or not hasattr(random_bytes, "__len__"):
        raise TypeError("randomBytes must be a list of integers from 0 to 255")
    for b in random_bytes:
        if type(b) is not int or b < 0 or b > 255:
            raise ValueError("randomBytes must be a list of integers from 0 to 255")
    if len(random_bytes) < 16:
        raise ValueError("randomBytes must hold at least 16 bytes (128 bits)")
    return base32_encode(list(random_bytes), False)