The user wants a Python script for generating time-based one-time passwords (TOTPs) based on RFC 6238. I think I should use libraries like pyotp, but I could also write it from scratch with hmac, hashlib, and a base32 secret. They didn't specify how detailed the script should be, but I'll provide a complete example with CLI arguments for options like secret, digits, and timestep. It might be good to include some concise explanations. Let's get to it!Implementing TOTP Functionality
I need to outline what the script should do for generating TOTP. First, it needs to accept a Base32 secret key and compute the TOTP based on the current Unix time. The steps include calculating T using the formula, converting it to an 8-byte big-endian format, then computing HMAC with SHA-1, SHA-256, or SHA-512 as specified. I'll ensure the default is 30 seconds, 6 digits, and SHA-1. I’ll also provide testing with known vectors and necessary imports and argument parsing. Let's dive in!Designing the TOTP Script
I'm drafting a sample Python script for generating TOTP codes. It starts with necessary imports and includes a function to normalize the Base32 secret by removing spaces and adjusting padding. The main function, totp, computes the TOTP based on the provided secret and time. It allows customization for time steps, number of digits, and hashing algorithms like SHA-1, SHA-256, and SHA-512. I’ll connect this to an argument parser for user inputs, enhancing usability. Let’s refine this further!Finalizing the TOTP Script
I’m wrapping up the TOTP script by adding argument options for the time step and the algorithm. I'll include a way to generate a TOTP for a specific Unix time, which will be useful for testing. I plan to add a docstring, maybe even a sample usage like python totp.py JBSWY3DPEHPK3PXP using the "Hello!" secret.
To enhance security, I’ll remind users not to hard-code secrets but rather use environment variables. I'll keep the explanations concise, using bullet points for clarity, and ensure it’s clear that Python 3.6+ is needed. Below is a self-contained Python script that generates TOTP codes (RFC 6238–compatible), without requiring external libraries.
python
#!/usr/bin/env python3
"""
Simple TOTP (Time-based One-Time Password) generator.
Usage:
python totp.py YOUR_BASE32_SECRET
Example:
python totp.py JBSWY3DPEHPK3PXP
"""
import time
import hmac
import hashlib
import base64
import struct
import argparse
def normalize_base32(secret: str) -> str:
"""
Normalize a Base32-encoded secret:
- remove spaces
- uppercase
- pad with '=' to a multiple of 8 chars (for base32 decoder)
"""
s = ''.join(secret.split()).upper()
padding = (-len(s)) % 8
if padding:
s += '=' * padding
return s
def generate_totp(secret: str,
time_step: int = 30,
digits: int = 6,
algo: str = "SHA1",
t0: int = 0,
for_time: float | None = None) -> str:
"""
Generate a TOTP code.
:param secret: Base32-encoded secret key
:param time_step: Time step in seconds (X), default 30
:param digits: Number of output digits, default 6
:param algo: HMAC algorithm: "SHA1", "SHA256", or "SHA512"
:param t0: Unix time to start counting from, usually 0
:param for_time: Unix timestamp to generate the code for; defaults to now
:return: Zero-padded TOTP code as a string
"""
if for_time is None:
for_time = time.time()
# Counter value (T in RFC 6238)
counter = int((for_time - t0) / time_step)
# Decode Base32 secret
key = base64.b32decode(normalize_base32(secret), casefold=True)
# Convert counter to 8-byte big-endian
msg = struct.pack(">Q", counter)
algo = algo.upper()
if algo in ("SHA1", "SHA-1"):
digest = hashlib.sha1
elif algo in ("SHA256", "SHA-256"):
digest = hashlib.sha256
elif algo in ("SHA512", "SHA-512"):
digest = hashlib.sha512
else:
raise ValueError("Unsupported algorithm. Use SHA1, SHA256, or SHA512.")
hmac_hash = hmac.new(key, msg, digest).digest()
# Dynamic truncation
offset = hmac_hash[-1] & 0x0F
code_int = struct.unpack(">I", hmac_hash[offset:offset + 4])[0]
code_int &= 0x7FFFFFFF
code_int %= 10 ** digits
return str(code_int).zfill(digits)
def main():
parser = argparse.ArgumentParser(description="Generate a TOTP code (RFC 6238).")
parser.add_argument("secret", help="Base32-encoded secret (like in your authenticator app).")
parser.add_argument("-d", "--digits", type=int, default=6,
help="Number of digits in the TOTP (default: 6).")
parser.add_argument("-t", "--time-step", type=int, default=30,
help="Time step in seconds (default: 30).")
parser.add_argument("-a", "--algo",
choices=["SHA1", "SHA-1", "SHA256", "SHA-256", "SHA512", "SHA-512"],
default="SHA1",
help="HMAC algorithm (default: SHA1).")
parser.add_argument("--at", type=int, metavar="UNIX_TIME",
help="Generate TOTP for a specific Unix time (for testing).")
args = parser.parse_args()
now = args.at if args.at is not None else time.time()
code = generate_totp(
secret=args.secret,
time_step=args.time_step,
digits=args.digits,
algo=args.algo,
for_time=now,
)
print(code)
# Show remaining validity only when using current time
if args.at is None:
remaining = args.time_step - (int(now) % args.time_step)
print(f"Valid for ~{remaining} more second(s).")
if __name__ == "__main__":
main()
Usage summary:
Save as totp.py.
Run:
bash
python totp.py YOUR_BASE32_SECRET
Optional parameters:
-d / --digits (default 6)
-t / --time-step (default 30)
-a / --algo (SHA1, SHA256, SHA512; default SHA1)
--at UNIX_TIME to generate for a specific timestamp (for testing/vectors).
If you want, I can also show how to verify this against the pyotp library or standard test vectors.