Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To automate a TOTP-protected login, your authorized automation must have access to the same shared secret as the verifier, use the verifier’s time-step and hashing settings, calculate the current time step, and submit the resulting code through the normal login flow. RFC 6238 specifies a 30-second default time step, but a service can configure another value. Treat the TOTP seed as credential material: keep it in a secrets store, out of source control and logs, and limit access to the process that needs it.

What TOTP automation actually does

TOTP is the time-based form of HOTP. HOTP uses a shared secret and counter; TOTP replaces the event counter with a value derived from the current Unix time. RFC 6238 requires the prover (your script or authenticator) and verifier (the login server) to know or derive the same current time and use the same time-step. Its default step is 30 seconds. See the RFC 6238 specification and the underlying RFC 4226 HOTP specification.

At a high level, generation is:

  1. Read the account’s shared secret, commonly encoded as Base32.
  2. Read the current Unix time in UTC.
  3. Divide time by the configured step (30 seconds by default) to obtain the moving counter.
  4. Apply HOTP’s HMAC calculation and dynamic truncation.
  5. Reduce the result to the verifier’s digit count, commonly six digits.
  6. Submit the code before the verifier’s acceptance window closes.

The secret is account-specific. A code generated from another account’s seed is not a substitute, and possessing a secret without authorization is equivalent to possessing a reusable authentication credential.

Prerequisites before writing code

  • An account and a documented, authorized automation use case.
  • The exact TOTP seed for that account, or an approved way to retrieve it at runtime.
  • The verifier’s algorithm, digit count, time-step, and any issuer-specific configuration. Do not assume the defaults if the service documents different values.
  • A clock synchronized closely enough for the verifier’s allowed drift and entry delay.
  • A login client that can submit the code over the service’s normal authenticated, encrypted connection.

Keep the seed in an operating-system secret store, CI secret, or equivalent protected storage. Do not place it in a repository, command-line history, screenshots, ordinary application logs, exception messages, or test fixtures shared with unrelated users. RFC 6238 calls for keys to be randomly generated or derived securely and protected from unauthorized access; NIST’s guidance likewise requires strong protection of the shared key.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Yubico - Security Key C NFC - Basic Compatibility - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-C or NFC, FIDO Certified
  • POWERFUL SECURITY KEY: The Security Key C NFC is the essential physical passkey for protecting your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with Google, Microsoft, and Apple. A single Security Key C NFC secures 100 of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your Security Key C NFC via USB-C and tap it, or tap it against your phone (NFC) to authenticate. No batteries, no internet connection, and no extra fees required.
  • TRUSTED PASSKEY TECHNOLOGY: Uses the latest passkey standards (FIDO2/WebAuthn & FIDO U2F) but does not support One-Time Passwords. For complex needs, check out the YubiKey 5 Series.
  • BUILT TO LAST: Made from tough, waterproof, and crush-resistant materials. Manufactured in Sweden and programmed in the USA with the highest security standards.

Generate a TOTP code in Python

The following example uses Python’s standard library. It assumes a Base32 seed, a six-digit code, SHA-1 as the configured HMAC hash, and the RFC 6238 default 30-second step. Change those values only when the verifier’s configuration requires it.

import base64
import hashlib
import hmac
import os
import struct
import time


def totp(secret_b32: str, *, step: int = 30, digits: int = 6,
         digest=hashlib.sha1, now: int | None = None) -> str:
    if step <= 0:
        raise ValueError("step must be positive")
    if digits <= 0:
        raise ValueError("digits must be positive")

    # Base32 copied from an enrollment record often contains spaces or padding.
    normalized = secret_b32.replace(" ", "").replace("-", "").upper()
    normalized += "=" * ((8 - len(normalized) % 8) % 8)
    key = base64.b32decode(normalized, casefold=True)

    timestamp = int(time.time() if now is None else now)
    counter = timestamp // step
    message = struct.pack(">Q", counter)
    digest_bytes = hmac.new(key, message, digest).digest()
    offset = digest_bytes[-1] & 0x0F
    binary = struct.unpack(">I", digest_bytes[offset:offset + 4])[0] & 0x7FFFFFFF
    code = binary % (10 ** digits)
    return f"{code:0{digits}d}"


secret = os.environ["MFA_TOTP_SECRET"]
print(totp(secret))

Set MFA_TOTP_SECRET through your secret manager or process environment rather than hard-coding it. The optional now argument is useful for deterministic unit tests using RFC test vectors; production code should use a synchronized system clock. Do not print the seed or retain generated codes longer than the login operation requires.

Generate a TOTP code in Node.js

This implementation uses Node’s built-in cryptography APIs and the same defaults. It avoids third-party package behavior assumptions.

Rank #2
Yubico - YubiKey 5C NFC - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-C or NFC, FIDO Certified - Protect Your Online Accounts
  • POWERFUL SECURITY KEY: The YubiKey 5C NFC is the most versatile physical passkey, protecting your digital life from phishing attacks. It ensures only you can access your accounts
  • WORKS WITH 1000+ ACCOUNTS: Compatible with popular accounts like Google, Microsoft, and Apple. A single YubiKey 5C NFC secures 100+ of your favorite accounts, including email, password managers, and more
  • FAST & CONVENIENT LOGIN: Plug in your YubiKey 5C NFC via USB and tap it, or tap it against your phone (NFC), to authenticate. No batteries, no internet connection, and no extra fees required
  • MOST SECURE PASSKEY: Supports FIDO2/WebAuthn, FIDO U2F, Yubico OTP, OATH-TOTP/HOTP, Smart card (PIV), and OpenPGP. That means it’s versatile, working almost anywhere you need it
  • PRIMARY & SPARE KEYS: Just like having a spare house key, we recommend buying two YubiKeys - one for daily use and one as a spare. That way you’ll never get locked out of your accounts
import crypto from "node:crypto";

function base32Decode(value) {
  const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
  const clean = value.replace(/[ =-]/g, "").toUpperCase();
  let bits = "";
  for (const ch of clean) {
    const n = alphabet.indexOf(ch);
    if (n < 0) throw new Error("Invalid Base32 secret");
    bits += n.toString(2).padStart(5, "0");
  }
  const bytes = [];
  for (let i = 0; i + 8 <= bits.length; i += 8) bytes.push(parseInt(bits.slice(i, i + 8), 2));
  return Buffer.from(bytes);
}

function totp(secret, { step = 30, digits = 6, algorithm = "sha1" } = {}) {
  const counter = Math.floor(Date.now() / 1000 / step);
  const msg = Buffer.alloc(8);
  msg.writeBigUInt64BE(BigInt(counter));
  const mac = crypto.createHmac(algorithm, base32Decode(secret)).update(msg).digest();
  const offset = mac[mac.length - 1] & 0x0f;
  const binary = (mac.readUInt32BE(offset) & 0x7fffffff) % (10 ** digits);
  return String(binary).padStart(digits, "0");
}

console.log(totp(process.env.MFA_TOTP_SECRET));

Use the generated value immediately in the account’s login request. A script that automates the browser or HTTP client must still handle username, password, CSRF tokens, redirects, consent screens, and session cookies according to that service’s documented flow. Never bypass a bot check or access-control decision you are not authorized to bypass.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How the verifier should handle the code

Generation is only one side of MFA. The verifier independently calculates the expected value from its copy of the secret and current time, then decides whether the submitted value is acceptable.

Time windows and clock drift

A code can be rejected even when the seed is correct if either side has an inaccurate clock, a different time-step, a different hash, or a different digit count. NIST says the validity lifetime should account for expected clock drift, network delay, and the time a claimant needs to enter the OTP. A wider acceptance window is not free: it increases the period in which a captured code may work. Configure the narrowest window that meets the service’s operational needs.

Rank #3
Yubico - YubiKey 5 NFC - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB-A or NFC, FIDO Certified - Protect Your Online Accounts
  • POWERFUL SECURITY KEY: The YubiKey 5 NFC is the most versatile physical passkey, protecting your digital life from phishing attacks. It ensures only you can access your accounts
  • WORKS WITH 1000+ ACCOUNTS: Compatible with popular accounts like Google, Microsoft, and Apple. A single YubiKey 5 NFC secures 100+ of your favorite accounts, including email, password managers, and more
  • FAST & CONVENIENT LOGIN: Plug in your YubiKey 5 NFC via USB and tap it, or tap it against your phone (NFC), to authenticate. No batteries, no internet connection, and no extra fees required
  • MOST SECURE PASSKEY: Supports FIDO2/WebAuthn, FIDO U2F, Yubico OTP, OATH-TOTP/HOTP, Smart card (PIV), and OpenPGP. That means it’s versatile, working almost anywhere you need it
  • PRIMARY & SPARE KEYS: Just like having a spare house key, we recommend buying two YubiKeys - one for daily use and one as a spare. That way you’ll never get locked out of your accounts

Replay prevention

The verifier should accept a given OTP only once while it is valid. Record successful use in a way that prevents the same code from being replayed during the acceptance window, while accounting for the verifier’s chosen drift policy.

Rate limiting and protected transport

Collect codes over an authenticated, encrypted channel and apply effective rate limits to failed attempts. NIST’s authenticator guidance requires rate limiting where the OTP output is less than 64 bits. Return errors that do not disclose whether the seed, username, or password was the specific problem.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why a correct code may fail

Symptom Likely cause Fix
Every code is rejected Wrong account seed, Base32 transcription error, or incompatible hash/digit settings Re-enroll or securely verify the exact seed and documented parameters; check for spaces, omitted characters, and accidental account mixing.
Codes work only occasionally Clock drift or a boundary between time steps Synchronize the host clock; inspect UTC time and the verifier’s documented drift policy.
Manual app works but script fails Different seed, step, hash, or digit count; script may submit an expired value Compare configuration and generate-and-submit without delays or logging the secret.
Retries lock the account No backoff or verifier rate limiting Stop automatic retries, follow the service’s recovery process, and add bounded backoff and alerting.
Login succeeds once, then repeats fail Replay protection correctly rejected a reused code Generate a fresh value for each attempt and do not queue codes for later use.

Is TOTP phishing-resistant?

No. NIST states, “OTP authentication is not phishing-resistant.” A manually entered TOTP is not cryptographically bound to the website or authentication session. A phishing site can ask for the current code and relay it to the real verifier before it expires. TOTP is still a useful additional factor against some password-only attacks, but it should not be described as phishing-resistant. For higher-risk access, evaluate an authentication method that cryptographically binds the authenticator to the relying party.

Rank #4
Yubico - Security Key NFC - Basic Compatibility - Multi-Factor Authentication (MFA) Key, Connect via USB-A or NFC, FIDO Certified
  • POWERFUL SECURITY KEY: The Security Key NFC is the essential physical passkey for protecting your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with Google, Microsoft, and Apple. A single Security Key NFC secures 100 of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your Security Key NFC via USB-A and tap it, or tap it against your phone (NFC) to authenticate. No batteries, no internet connection, and no extra fees required.
  • TRUSTED PASSKEY TECHNOLOGY: Uses the latest passkey standards (FIDO2/WebAuthn & FIDO U2F) but does not support One-Time Passwords. For complex needs, check out the YubiKey 5 Series.
  • BUILT TO LAST: Made from tough, waterproof, and crush-resistant materials. Manufactured in Sweden and programmed in the USA with the highest security standards.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Software versus hardware OTP authenticators

Standards describe both software and hardware OTP authenticators. Hardware is not inherently required for code-generation automation; what matters is that the authorized prover can use the same protected secret and compatible parameters. Compare approaches by phishing resistance, whether the secret can be exported or copied, key protection, manual versus workflow-integrated interaction, and verifier controls for drift, replay, and failed-attempt rate limiting. The standards cited here do not establish product-by-product performance or usability rankings.

Or skip the browser setup

If your automation also needs clean screenshots of login or verification pages, ScreenshotNeo provides a one-call website screenshot API. Before capture it accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for all options. A direct request is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

There is a free allowance of 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account to begin.

Best Value
Yubico - YubiKey 5C - Multi-Factor authentication (MFA) Security Key and passkey, Connect via USB, FIDO Certified - Protect Your Online Accounts (5C)
  • POWERFUL SECURITY KEY: The YubiKey 5 is a versatile physical passkey that protects your digital life from phishing attacks. It ensures only you can access your accounts.
  • WORKS WITH 1000+ ACCOUNTS: Compatible with popular accounts like Google, Microsoft, and Apple. A single YubiKey 5 secures 100+ of your favorite accounts, including email, password managers, and more.
  • FAST & CONVENIENT LOGIN: Plug in your YubiKey 5 via USB and tap it to authenticate. No batteries, no internet connection, and no extra fees required.
  • MOST SECURE PASSKEY: Supports FIDO2/WebAuthn, FIDO U2F, Yubico OTP, OATH-TOTP/HOTP, Smart card (PIV), and OpenPGP. That means it’s versatile, working almost anywhere you need it.
  • BUILT TO LAST: Made from tough, waterproof, and crush-resistant materials. Manufactured in Sweden and programmed in the USA with the highest security standards.

Frequently Asked Questions

Can I generate a TOTP code without the account’s secret?

No. The prover must know or derive the same secret as the verifier; a username, QR-code image, or current time alone is insufficient.

What time zone should a TOTP script use?

TOTP uses Unix time, which is an absolute UTC-based count. Local time-zone display settings do not matter, but the host clock must be accurate.

Should I store generated TOTP codes for reuse?

No. Generate a fresh code for each authorized attempt and submit it promptly; verifiers may reject a previously accepted value.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.