auth.totp
Authenticator-app two-factor codes (TOTP RFC 6238, HOTP RFC 4226): secret, QR URI, codes, verify with window and drift.
1.0.0 · published 2026-10-10 by charlie · Anterra
Pinned by 80 tests, run in TypeScript, Python and Rust.totpSecret 8 · totpUri 11 · hotpCode 20 · totpCode 19 · verifyTotp 22
What it does
Two-factor sign-in with an authenticator app (Google Authenticator, Microsoft Authenticator, 1Password, Authy): TOTP from RFC 6238, which is HOTP from RFC 4226 counted in time steps. Everything is pure: the random bytes and the time come from the caller.
## Setting it up for a user
The functions
A group: 5 functions that work together, each in its own file, each pinned by its own tests in TypeScript, Python and Rust. A project can install only the ones it calls.
- totp_secret (randomBytes: int[]) -> string
- totp_uri (issuer: string, account: string, secret: string, settings: TotpSettings) -> string
- hotp_code (secret: string, counter: int, digits: int, algorithm: TotpAlgorithm) -> string
- totp_code (secret: string, now: int, settings: TotpSettings) -> string
- verify_totp (secret: string, code: string, now: int, settings: TotpSettings, window: int, drift: int, lastUsedStep: int?) -> TotpCheck
The types it declares, generated into your project
TotpAlgorithm = Literal["SHA1", "SHA256"]
@dataclass(frozen=True)
class TotpSettings:
"""How codes are made. Authenticator apps expect SHA1, 6 digits, 30 seconds."""
algorithm: TotpAlgorithm
#: 6, 7 or 8
digits: int
#: seconds per step, 1 or more; 30 is the default everywhere
period: int
TotpReason = Literal["wrong_code", "malformed_code", "replayed"]
@dataclass(frozen=True)
class TotpCheck:
"""Whether a code was accepted, and what to store if it was."""
valid: bool
#: the time step that matched; store it as lastUsedStep
step: Optional[int]
#: matched step minus expected step; store it to centre the next window
drift: Optional[int]
#: why not, when not valid
reason: Optional[TotpReason]
Once installed, your code imports each one from the group's module.
totp_secret throws on bad input 8 tests
def totp_secret(random_bytes: Sequence[int]) -> str
| random_bytes | int[] | at least 16 bytes from a secure random source, read by the caller; 20 is usual |
| returns | string | the secret as unpadded base32, to store (encrypted) and to show in the QR code |
For example
totp_secret(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)→ AAAQEAYEAUDAOCAJBIFQYDIOB4IBCEQT 20 random bytes, the usual size, are 32 characterstotp_secret(255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240)→ 777P37H37L47R57W6X2PH4XR6A 16 bytes, the least accepted (RFC 4226 R6: 128 bits)totp_secret(49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48)→ GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ the RFC 4226 test secret
from fune.auth.totp import totp_secret # auth.totp@^1
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)totp_uri throws on bad input 11 tests
def totp_uri(issuer: str, account: str, secret: str, settings: TotpSettings) -> str
| issuer | string | your app's name, shown in the authenticator; no colon |
| account | string | the user's email or username; no colon |
| secret | string | the base32 secret from totpSecret |
| settings | TotpSettings | the algorithm, digits and period; SHA1, 6 and 30 for every authenticator app |
| returns | string | the otpauth://totp/ URI to put in a QR code |
For example
totp_uri(Acme, ada@example.com, JBSWY3DPEHPK3PXP, algorithm SHA1, digits 6, period 30)→ otpauth://totp/Acme:ada%40example.com?secret=JBSWY3DPEHPK3PXP&issuer=Acme&algorithm=SHA1&digits=6&period=30 the usual QR code: SHA1, 6 digits, 30 secondstotp_uri(Acme Corp, ada lovelace@example.com, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30)→ otpauth://totp/Acme%20Corp:ada%20lovelace%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Acme%20Corp&algorithm=SHA1&digits=6&period=30 spaces and an at sign are percent-encoded in the label and the issuertotp_uri(Acme, ada, gezdgnbvgy3tqojqgezdgnbvgy3tqojq, algorithm SHA1, digits 6, period 30)→ otpauth://totp/Acme:ada?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Acme&algorithm=SHA1&digits=6&period=30 a lower-case, padded secret is written back canonical
from fune.auth.totp import totp_uri # auth.totp@^1
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
from .auth_totp_hotp_code import check_totp_settings, totp_secret_key ← hotpCode, another function of this group · built into the same file, even by a slim install
from .auth_totp_types import TotpSettings
from .encoding_base32_base32_encode import base32_encode
_UNRESERVED = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
def _percent_encode(text: str) -> str:
# RFC 3986: everything but the unreserved characters, as UTF-8 bytes.
out = []
for b in text.encode("utf-8"):
ch = chr(b)
out.append(ch if ch in _UNRESERVED else "%%%02X" % b)
return "".join(out)
def _check_label_part(value: Any, name: str) -> None:
if not isinstance(value, str):
raise TypeError("%s must be text" % name)
if value == "":
raise ValueError("%s must not be empty" % name)
if ":" in value:
raise ValueError("%s must not contain a colon" % name)
def totp_uri(issuer: str, account: str, secret: str, settings: TotpSettings) -> str:
"""The Key Uri Format authenticator apps scan from a QR code. The secret
is written back in canonical form (upper case, unpadded)."""
_check_label_part(issuer, "issuer")
_check_label_part(account, "account")
check_totp_settings(settings)
canonical = base32_encode(totp_secret_key(secret), False)
return "otpauth://totp/%s:%s?secret=%s&issuer=%s&algorithm=%s&digits=%d&period=%d" % (
_percent_encode(issuer),
_percent_encode(account),
canonical,
_percent_encode(issuer),
settings.algorithm,
settings.digits,
settings.period,
)hotp_code throws on bad input 20 tests
def hotp_code(secret: str, counter: int, digits: int, algorithm: TotpAlgorithm) -> str
| secret | string | the base32 secret |
| counter | int | the moving factor, 0 to 2^53 - 1 |
| digits | int | 6, 7 or 8 |
| algorithm | TotpAlgorithm | |
| returns | string | the code, zero-padded to digits |
For example
hotp_code(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 6, SHA1)→ 755224 RFC 4226 Appendix D: counter 0hotp_code(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1, 6, SHA1)→ 287082 RFC 4226 Appendix D: counter 1hotp_code(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 2, 6, SHA1)→ 359152 RFC 4226 Appendix D: counter 2
from fune.auth.totp import hotp_code # auth.totp@^1
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)totp_code throws on bad input 19 tests
def totp_code(secret: str, now: int, settings: TotpSettings) -> str
| secret | string | the base32 secret |
| now | int | the current time in Unix seconds, read by the caller |
| settings | TotpSettings | |
| returns | string | the code for the time step now falls in |
For example
totp_code(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59, algorithm SHA1, digits 8, period 30)→ 94287082 RFC 6238 Appendix B: SHA1 at 59totp_code(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 59, algorithm SHA256, digits 8, period 30)→ 46119246 RFC 6238 Appendix B: SHA256 at 59totp_code(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,111,111,109, algorithm SHA1, digits 8, period 30)→ 07081804 RFC 6238 Appendix B: SHA1 at 1111111109
from fune.auth.totp import totp_code # auth.totp@^1
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
from .auth_totp_hotp_code import check_totp_settings, hotp_from_key, is_totp_whole, totp_secret_key ← hotpCode, another function of this group · built into the same file, even by a slim install
from .auth_totp_types import TotpSettings
def check_totp_now(now: Any) -> None:
if not is_totp_whole(now):
raise ValueError("now must be a whole number of seconds from 0 to 2^53 - 1")
def totp_code(secret: str, now: int, settings: TotpSettings) -> str:
"""The RFC 6238 code for the time step now falls in: HOTP at
floor(now / period)."""
check_totp_now(now)
check_totp_settings(settings)
key = totp_secret_key(secret)
return hotp_from_key(key, now // settings.period, settings.digits, settings.algorithm)verify_totp throws on bad input 22 tests
def verify_totp(secret: str, code: str, now: int, settings: TotpSettings, window: int, drift: int, last_used_step: Optional[int]) -> TotpCheck
| secret | string | the base32 secret |
| code | string | what the user typed; spaces are ignored |
| now | int | the current time in Unix seconds, read by the caller |
| settings | TotpSettings | |
| window | int | steps accepted either side of the expected one, 0 to 10; 1 is usual |
| drift | int | the user's known clock drift in steps, from an earlier check; 0 when none |
| last_used_step | int? | the step of the last code this user signed in with, or null; that step and earlier ones are refused |
| returns | TotpCheck | valid with the step and drift to store, or not valid with the reason |
For example
verify_totp(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, —)→ valid true, step 37,037,037, drift 0, reason — the current code is valid, no driftverify_totp(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 081804, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, —)→ valid true, step 37,037,036, drift -1, reason — the previous step's code inside a window of 1, drift -1verify_totp(GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 266759, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, —)→ valid true, step 37,037,038, drift 1, reason — the next step's code, drift +1
from fune.auth.totp import verify_totp # auth.totp@^1
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 List, Optional
from .auth_totp_hotp_code import check_totp_settings, hotp_from_key, totp_secret_key ← hotpCode, another function of this group · built into the same file, even by a slim install
from .auth_totp_totp_code import check_totp_now ← totpCode, another function of this group · built into the same file, even by a slim install
from .auth_totp_types import TotpCheck, TotpSettings
from .crypto_constant_time_equal import constant_time_equal ← from crypto.constant-time-equal ^1.0.0 · built alongside by fune
def _ascii(text: str) -> List[int]:
return [ord(ch) & 255 for ch in text]
def verify_totp(
secret: str,
code: str,
now: int,
settings: TotpSettings,
window: int,
drift: int,
last_used_step: Optional[int],
) -> TotpCheck:
"""Checks a typed code against the steps around now (centred on the
user's known drift), closest first, earlier first on a tie. Every step in
the window is compared in constant time. A step at or before
last_used_step is refused as replayed."""
check_totp_now(now)
check_totp_settings(settings)
if type(window) is not int or window < 0 or window > 10:
raise ValueError("window must be a whole number from 0 to 10")
if type(drift) is not int or drift < -1000 or drift > 1000:
raise ValueError("drift must be a whole number from -1000 to 1000")
if last_used_step is not None and type(last_used_step) is not int:
raise TypeError("lastUsedStep must be a whole number or null")
if not isinstance(code, str):
raise TypeError("code must be text")
key = totp_secret_key(secret)
typed = code.replace(" ", "")
if len(typed) != settings.digits or not all("0" <= ch <= "9" for ch in typed):
return TotpCheck(valid=False, step=None, drift=None, reason="malformed_code")
expected = now // settings.period
centre = expected + drift
typed_bytes = _ascii(typed)
accepted = None
replayed = False
for distance in range(window + 1):
for step in [centre] if distance == 0 else [centre - distance, centre + distance]:
if step < 0:
continue
if not constant_time_equal(_ascii(hotp_from_key(key, step, settings.digits, settings.algorithm)), typed_bytes):
continue
if last_used_step is not None and step <= last_used_step:
replayed = True
elif accepted is None:
accepted = step
if accepted is not None:
return TotpCheck(valid=True, step=accepted, drift=accepted - expected, reason=None)
return TotpCheck(valid=False, step=None, drift=None, reason="replayed" if replayed else "wrong_code")Install
fune build
With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 4 dependencies, pins them in fune.lock, downloads only the Python package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:
fune add auth.totp
That builds the whole group. To build only what you call, and whatever it uses inside the group:
fune add auth.totp --only totpSecret
The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./auth.totp-1.0.0-python.fune, or fetch it from a terminal with fune pull auth.totp@1.0.0:python.
The whole function, every language, is one file too: auth.totp-1.0.0.fune, 62,297 bytes, sha256 92c28b8b0cdbe81f910af8b79eaf833d66b5aaf7d830e292e0668d19dfdf7e59. It installs into a project of any language.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
# fune: before auth.totp.totpSecret
# fune: before auth.totp.totpUri
# fune: before auth.totp.hotpCode
# fune: before auth.totp.totpCode
# fune: before auth.totp.verifyTotp
after — your function gets the result and the arguments, and returns the final result.
# fune: after auth.totp.totpSecret
# fune: after auth.totp.totpUri
# fune: after auth.totp.hotpCode
# fune: after auth.totp.totpCode
# fune: after auth.totp.verifyTotp
replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.
# fune: replace crypto.constant-time-equal in auth.totp
# fune: replace crypto.hmac-sha1 in auth.totp
# fune: replace crypto.hmac-sha256 in auth.totp
# fune: replace encoding.base32 in auth.totp
step — your function runs at a numbered point inside a function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show auth.totp --steps.
# fune: step auth.totp.<fn> after <n|label>
Tests
A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.
totpSecret 8 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| 20 random bytes, the usual size, are 32 characters | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 | → | AAAQEAYEAUDAOCAJBIFQYDIOB4IBCEQT |
| 16 bytes, the least accepted (RFC 4226 R6: 128 bits) | 255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240 | → | 777P37H37L47R57W6X2PH4XR6A |
| the RFC 4226 test secret | 49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 48 | → | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ |
| 32 bytes need no padding character either way, 52 characters unpadded | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 | → | AAAQEAYEAUDAOCAJBIFQYDIOB4IBCEQTCQKRMFYYDENBWHA5DYPQ |
| 15 bytes are too few | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 | → | error: randomBytes must hold at least 16 bytes (128 bits) |
| no bytes at all | → | error: randomBytes must hold at least 16 bytes (128 bits) | |
| a value above 255 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 300 | → | error: randomBytes must be a list of integers from 0 to 255 |
| a fraction is not a byte | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 1.5 | → | error: randomBytes must be a list of integers from 0 to 255 |
totpUri 11 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| the usual QR code: SHA1, 6 digits, 30 seconds | Acme, ada@example.com, JBSWY3DPEHPK3PXP, algorithm SHA1, digits 6, period 30 | → | otpauth://totp/Acme:ada%40example.com?secret=JBSWY3DPEHPK3PXP&issuer=Acme&algorithm=SHA1&digits=6&period=30 |
| spaces and an at sign are percent-encoded in the label and the issuer | Acme Corp, ada lovelace@example.com, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 | → | otpauth://totp/Acme%20Corp:ada%20lovelace%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Acme%20Corp&algorithm=SHA1&digits=6&period=30 |
| a lower-case, padded secret is written back canonical | Acme, ada, gezdgnbvgy3tqojqgezdgnbvgy3tqojq, algorithm SHA1, digits 6, period 30 | → | otpauth://totp/Acme:ada?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Acme&algorithm=SHA1&digits=6&period=30 |
| SHA256, 8 digits, 60 seconds | Acme, ada, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, algorithm SHA256, digits 8, period 60 | → | otpauth://totp/Acme:ada?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA&issuer=Acme&algorithm=SHA256&digits=8&period=60 |
| non-ASCII text is percent-encoded as UTF-8 | Café Ltd, zoë@example.com, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 | → | otpauth://totp/Caf%C3%A9%20Ltd:zo%C3%AB%40example.com?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Caf%C3%A9%20Ltd&algorithm=SHA1&digits=6&period=30 |
| a colon in the issuer would break the label | Acme:Corp, ada, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 | → | error: issuer must not contain a colon |
| a colon in the account | Acme, ada:1, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 | → | error: account must not contain a colon |
| an empty issuer | , ada, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 | → | error: issuer must not be empty |
| an empty account | Acme, , GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 6, period 30 | → | error: account must not be empty |
| a secret that is not base32 | Acme, ada, JBSW Y3DP, algorithm SHA1, digits 6, period 30 | → | error: base32 text may only contain A-Z and 2-7 |
Show the other 1 test
| Case | Arguments | Expected | |
|---|---|---|---|
| 5 digits is not a code length authenticators show | Acme, ada, GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, algorithm SHA1, digits 5, period 30 | → | error: digits must be 6, 7 or 8 |
hotpCode 20 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| RFC 4226 Appendix D: counter 0 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 6, SHA1 | → | 755224 |
| RFC 4226 Appendix D: counter 1 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1, 6, SHA1 | → | 287082 |
| RFC 4226 Appendix D: counter 2 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 2, 6, SHA1 | → | 359152 |
| RFC 4226 Appendix D: counter 3 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 3, 6, SHA1 | → | 969429 |
| RFC 4226 Appendix D: counter 4 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 4, 6, SHA1 | → | 338314 |
| RFC 4226 Appendix D: counter 5 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 5, 6, SHA1 | → | 254676 |
| RFC 4226 Appendix D: counter 6 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 6, 6, SHA1 | → | 287922 |
| RFC 4226 Appendix D: counter 7 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 7, 6, SHA1 | → | 162583 |
| RFC 4226 Appendix D: counter 8 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 8, 6, SHA1 | → | 399871 |
| RFC 4226 Appendix D: counter 9 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 9, 6, SHA1 | → | 520489 |
Show the other 10 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| 8 digits at counter 0 (reference: Python hmac) | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 8, SHA1 | → | 84755224 |
| SHA256 at counter 1 (reference: Python hmac) | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 1, 6, SHA256 | → | 119246 |
| a counter above 2^32 uses all eight counter bytes (reference: Python hmac) | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 4,294,967,297, 6, SHA1 | → | 108930 |
| the largest counter, 2^53 - 1 (reference: Python hmac) | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 9,007,199,254,740,991, 6, SHA1 | → | 891307 |
| a negative counter | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, -1, 6, SHA1 | → | error: counter must be a whole number from 0 to 2^53 - 1 |
| a fractional counter | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1.5, 6, SHA1 | → | error: counter must be a whole number from 0 to 2^53 - 1 |
| 9 digits | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 9, SHA1 | → | error: digits must be 6, 7 or 8 |
| SHA512 is not offered | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, 6, SHA512 | → | error: algorithm must be SHA1 or SHA256 |
| a secret under 80 bits | AAAAAAAAAAAAAAA, 0, 6, SHA1 | → | error: secret must decode to at least 10 bytes |
| a secret with a trailing newline | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ , 0, 6, SHA1 | → | error: base32 text may only contain A-Z and 2-7 |
totpCode 19 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| RFC 6238 Appendix B: SHA1 at 59 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59, algorithm SHA1, digits 8, period 30 | → | 94287082 |
| RFC 6238 Appendix B: SHA256 at 59 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 59, algorithm SHA256, digits 8, period 30 | → | 46119246 |
| RFC 6238 Appendix B: SHA1 at 1111111109 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,111,111,109, algorithm SHA1, digits 8, period 30 | → | 07081804 |
| RFC 6238 Appendix B: SHA256 at 1111111109 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 1,111,111,109, algorithm SHA256, digits 8, period 30 | → | 68084774 |
| RFC 6238 Appendix B: SHA1 at 1111111111 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,111,111,111, algorithm SHA1, digits 8, period 30 | → | 14050471 |
| RFC 6238 Appendix B: SHA256 at 1111111111 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 1,111,111,111, algorithm SHA256, digits 8, period 30 | → | 67062674 |
| RFC 6238 Appendix B: SHA1 at 1234567890 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,234,567,890, algorithm SHA1, digits 8, period 30 | → | 89005924 |
| RFC 6238 Appendix B: SHA256 at 1234567890 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 1,234,567,890, algorithm SHA256, digits 8, period 30 | → | 91819424 |
| RFC 6238 Appendix B: SHA1 at 2000000000 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 2,000,000,000, algorithm SHA1, digits 8, period 30 | → | 69279037 |
| RFC 6238 Appendix B: SHA256 at 2000000000 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 2,000,000,000, algorithm SHA256, digits 8, period 30 | → | 90698825 |
Show the other 9 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| RFC 6238 Appendix B: SHA1 at 20000000000 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 20,000,000,000, algorithm SHA1, digits 8, period 30 | → | 65353130 |
| RFC 6238 Appendix B: SHA256 at 20000000000 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 20,000,000,000, algorithm SHA256, digits 8, period 30 | → | 77737706 |
| 6 digits, the last second of a step (59 is still step 1) | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59, algorithm SHA1, digits 6, period 30 | → | 287082 |
| the first second of the next step | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 60, algorithm SHA1, digits 6, period 30 | → | 359152 |
| time zero is step zero | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 0, algorithm SHA1, digits 6, period 30 | → | 755224 |
| a 60-second period halves the step (reference: Python hmac) | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 1,111,111,111, algorithm SHA1, digits 6, period 60 | → | 360094 |
| a time before 1970 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, -1, algorithm SHA1, digits 6, period 30 | → | error: now must be a whole number of seconds from 0 to 2^53 - 1 |
| a period of 0 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59, algorithm SHA1, digits 6, period 0 | → | error: period must be a whole number of seconds, 1 or more |
| a fractional time | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 59.5, algorithm SHA1, digits 6, period 30 | → | error: now must be a whole number of seconds from 0 to 2^53 - 1 |
verifyTotp 22 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| the current code is valid, no drift | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid true, step 37,037,037, drift 0, reason — |
| the previous step's code inside a window of 1, drift -1 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 081804, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid true, step 37,037,036, drift -1, reason — |
| the next step's code, drift +1 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 266759, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid true, step 37,037,038, drift 1, reason — |
| two steps old is outside a window of 1 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 731029, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid false, step —, drift —, reason wrong_code |
| a stored drift of -2 centres the window: two steps old is now the middle | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 731029, 1,111,111,111, algorithm SHA1, digits 6, period 30, 0, -2, — | → | valid true, step 37,037,035, drift -2, reason — |
| window 0 accepts only the centre | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 266759, 1,111,111,111, algorithm SHA1, digits 6, period 30, 0, 0, — | → | valid false, step —, drift —, reason wrong_code |
| spaces in a typed code are ignored | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050 471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid true, step 37,037,037, drift 0, reason — |
| the code already used at this step is replayed | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, 37,037,037 | → | valid false, step —, drift —, reason replayed |
| a later step than the last one used is fine | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 266759, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, 37,037,037 | → | valid true, step 37,037,038, drift 1, reason — |
| an older code after a newer one was used is replayed | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 081804, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, 37,037,037 | → | valid false, step —, drift —, reason replayed |
Show the other 12 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| five digits is malformed, not wrong | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 05047, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid false, step —, drift —, reason malformed_code |
| letters are malformed | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 12a456, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid false, step —, drift —, reason malformed_code |
| full-width digits are malformed | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 123456, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid false, step —, drift —, reason malformed_code |
| a code that matches no step in the window | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 000000, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid false, step —, drift —, reason wrong_code |
| at time zero the window never reaches a negative step | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 755224, 0, algorithm SHA1, digits 6, period 30, 1, 0, — | → | valid true, step 0, drift 0, reason — |
| RFC 6238 SHA256, 8 digits, at 2000000000 | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQGEZA, 90698825, 2,000,000,000, algorithm SHA256, digits 8, period 30, 1, 0, — | → | valid true, step 66,666,666, drift 0, reason — |
| a window of 11 is too wide | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 11, 0, — | → | error: window must be a whole number from 0 to 10 |
| a negative window | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, -1, 0, — | → | error: window must be a whole number from 0 to 10 |
| a drift beyond 1000 steps | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 1,001, — | → | error: drift must be a whole number from -1000 to 1000 |
| a fractional last used step | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, 1.5 | → | error: lastUsedStep must be a whole number or null |
| the code as a number rather than text | GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ, 123,456, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | error: code must be text |
| a secret that is too short is an error, not a wrong code | AAAAAAAA, 050471, 1,111,111,111, algorithm SHA1, digits 6, period 30, 1, 0, — | → | error: secret must decode to at least 10 bytes |
Verification
Verified by the operator, not the sandbox 80 test vectors declared; none run by the registry.
Verified locally by the registry's operator, not by the sandbox. This version was published with FUNE_VERIFY_MODE=inline-dev (the operator's import of the first-party registry, or a development server): the server validated the package - its manifest, signatures, imports, safety lint and test rules - but the registry did not run its test vectors in its sandbox. The operator runs them with `fune verify --all` before importing.
Signed by the registry with key fw-9dc887227da47575 (ed25519), over its integrity and this report's digest. The full report · JSON
More from the author
const secret = totpSecret([...crypto.getRandomValues(new Uint8Array(20))]);
const settings = { algorithm: "SHA1", digits: 6, period: 30 };
const uri = totpUri("Acme", user.email, secret, settings); // render as a QR code
// store the secret (encrypted at rest) as pending; confirm it with one
// verifyTotp before switching two-factor on, so a mis-scan never locks them out`totpSecret` takes at least 16 random bytes (RFC 4226 R6 asks for 128 bits, recommends 160; 20 is what most services use) and returns unpadded base32, the form the otpauth:// URI and manual entry both use. `totpUri` writes the Google Authenticator Key Uri Format: `otpauth://totp/Acme:ada%40example.com?secret=...&issuer=Acme&algorithm=SHA1&digits=6&period=30`. The issuer and account are percent-encoded per RFC 3986 (unreserved characters kept, the rest as UTF-8 `%XX`), and a colon in either is refused because it would break the `Issuer:account` label.
**Use SHA1, 6 digits, 30 seconds** unless you control the authenticator: many apps ignore `algorithm`, `digits` and `period` and silently show the wrong codes. SHA1 here is HMAC-SHA1, which is still sound (see `crypto.sha1`). SHA256 is offered for authenticators that honour it; SHA-512 is not offered, because the registry has no SHA-512 yet.
## Checking a code
const check = verifyTotp(secret, typed, nowSeconds, settings, 1, user.totpDrift ?? 0, user.totpLastStep);
if (check.valid) save({ totpLastStep: check.step, totpDrift: check.drift });- **Window.** Steps `drift - window` to `drift + window` around the expected step are accepted (`window` 0 to 10; 1 is RFC 6238's recommendation, which allows about 30 seconds of clock difference either way). They are tried closest first, the earlier step first on a tie, so the answer is deterministic. - **Drift.** `drift` in the result is how many steps the user's device is off. Store it and pass it next time to centre the window on that device's clock (RFC 6238 section 6), keeping the window small. - **Replay.** Pass the `step` of the user's last accepted code as `lastUsedStep`; a code for that step or an earlier one is refused with `replayed`, so a code seen over a shoulder or in a log cannot be used again (RFC 6238 section 5.2). Store the new `step` after every success. - **Typed input.** Spaces are removed first (`123 456`); anything that is not then exactly `digits` ASCII digits is `malformed_code`, not `wrong_code`. - Every step in the window is computed and compared with `crypto.constant-time-equal`, so timing does not say which step matched.
Rate-limit attempts (see `auth.login-throttle`): six digits are a million codes, and a window of 1 accepts three of them.
A secret must decode to at least 10 bytes (80 bits, the size older services issued) so existing secrets keep working; new ones are 16 or more. Base32 errors in a secret come straight from `encoding.base32`; strip spaces from a secret shown in groups before passing it.
`hotpCode` is the counter-based RFC 4226 code on its own, for hardware tokens or email/SMS codes keyed by a counter. Counters and times are 0 to 2^53 - 1, the range all three languages share.
## Vectors
RFC 4226 Appendix D (all ten counters) and RFC 6238 Appendix B (SHA1 and SHA256, all six times, 8 digits), with the test secrets `12345678901234567890` (base32 `GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ`) and `12345678901234567890123456789012`. Other expected codes were computed with Python's `hmac` module as an independent reference, and the URIs with `urllib.parse.quote`.
Sources: RFC 4226, HOTP (https://www.rfc-editor.org/rfc/rfc4226); RFC 6238, TOTP (https://www.rfc-editor.org/rfc/rfc6238); Key Uri Format (https://github.com/google/google-authenticator/wiki/Key-Uri-Format).