OATHTool

2.4.0 · active · verified Fri Apr 17

oathtool is a command-line tool and Python library for generating one-time passwords, supporting both HOTP (HMAC-based) and TOTP (Time-based) algorithms. The current version is 2.4.0, and it maintains a stable, albeit infrequent, release schedule, focusing on reliability and security.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to generate a TOTP code using a base32-encoded secret key, typically obtained from a 2FA setup process. It emphasizes retrieving the secret securely from an environment variable and includes basic error handling for common key issues.

import os
from oathtool.totp import TOTP

# Retrieve your base32-encoded secret key from an environment variable.
# Example: 'JBSWY3DPEHPK3PXP' (this is a placeholder, use your actual secret)
secret_base32 = os.environ.get('OATHTOOL_SECRET', 'JBSWY3DPEHPK3PXP')

if secret_base32 == 'JBSWY3DPEHPK3PXP':
    print("WARNING: Using a placeholder secret. Set OATHTOOL_SECRET environment variable for actual use.")

try:
    # Initialize the TOTP generator with your secret.
    # oathtool expects the secret to be base32-encoded or raw bytes.
    # If a base32 string is provided, it will be decoded automatically.
    totp = TOTP(secret_base32)

    # Generate the current time-based one-time password.
    current_otp = totp.code()
    print(f"Generated TOTP: {current_otp}")

    # You can also get the remaining time until the next code.
    # time_left = totp.time_left()
    # print(f"Time left until next code: {time_left} seconds")

except Exception as e:
    print(f"Error generating OTP: {e}")
    print("Ensure your OATHTOOL_SECRET is a valid base32 encoded string.")

view raw JSON →