Functional Weave
Code in Python

auth.recovery-codes@1.0.0

impl/python/generate_recovery_codes.py

1,603 bytes · the Python implementation · view raw

from typing import List, Sequence

# Crockford's base32 alphabet, lower case: no i, l, o or u to misread.
RECOVERY_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz"

_BYTES_PER_CODE = 10


def generate_recovery_codes(entropy: Sequence[int], count: int) -> List[str]:
    """Recovery codes from the caller's random bytes, 10 bytes (80 bits) each,
    as 16 Crockford base32 characters in four groups. Pass bytes from a CSPRNG
    (secrets.token_bytes), never the random module."""
    if isinstance(entropy, (str, dict)) or not hasattr(entropy, "__len__"):
        raise TypeError("entropy must be a list of integers from 0 to 255")
    for b in entropy:
        if type(b) is not int or b < 0 or b > 255:
            raise ValueError("entropy must be a list of integers from 0 to 255")
    if type(count) is not int or count < 1 or count > 50:
        raise ValueError("count must be a whole number from 1 to 50")
    needed = count * _BYTES_PER_CODE
    if len(entropy) < needed:
        raise ValueError(
            "entropy must hold at least 10 bytes per code: %d needed, %d given" % (needed, len(entropy))
        )
    codes = []
    for c in range(count):
        chars = []
        buffer = 0
        bits = 0
        for i in range(_BYTES_PER_CODE):
            buffer = ((buffer << 8) | entropy[c * _BYTES_PER_CODE + i]) & 0xFFFF
            bits += 8
            while bits >= 5:
                bits -= 5
                chars.append(RECOVERY_ALPHABET[(buffer >> bits) & 31])
        s = "".join(chars)
        codes.append("%s-%s-%s-%s" % (s[0:4], s[4:8], s[8:12], s[12:16]))
    return codes