Skip to content
TheChatArchiveThe Chat Archive
GLMGLM-5 / Pony Alpha· unknownHugging Face Frontier Reasoning Traces

Develop a Python script to generate time-based one-time passwords (TOTP).

  1. User

    Develop a Python script to generate time-based one-time passwords (TOTP).

  2. GLM Assistant

    The user wants a Python script to generate Time-based One-Time Passwords (TOTP).

    1. Understand the Requirements:

    • Language: Python.
    • Core Function: Generate TOTPs.
    • Standard: Must adhere to RFC 6238 (TOTP).
    • Inputs: Typically a shared secret key and the current time.
    • Output: A numerical code (usually 6 or 8 digits).

    2. Identify Necessary Libraries:

    • Python has a built-in hmac library for hashing (HMAC-SHA-1 is the default for TOTP).
    • Python has a built-in hashlib library (needed for SHA-1, SHA-256, etc.).
    • Python has a built-in time library for getting the current Unix timestamp.
    • Python has a built-in struct library for packing/unpacking binary data (handling endianness).
    • Python has a built-in base64 library for decoding the secret key (usually Base32 encoded).

    Alternative: pyotp is a very popular library that wraps all this logic. However, for a "develop a script" request, implementing it from scratch using standard libraries is usually more educational and robust (fewer dependencies), but offering the pyotp solution is good for practical use. I should probably provide both: a "from scratch" implementation to show how it works, and a "using library" implementation for production readiness.

    3. Algorithm (RFC 6238 / RFC 4226):

    1. Secret Key: Needs to be decoded from Base32 (usually).
    2. Time: Get current Unix time (time.time()).
    3. Time Step: Divide time by the interval (usually 30 seconds). Take the integer part.
    4. Counter: Convert this integer time step into a byte array (Big Endian, 8 bytes).
    5. HMAC: Calculate HMAC-SHA-1 (or SHA-256/SHA-512) using the secret key and the counter.
    6. Dynamic Truncation:
      • Get the last nibble (4 bits) of the hash result (offset).
      • Extract 4 bytes from the hash starting at offset.
      • Mask the most significant bit (to avoid signed/unsigned issues).
    7. Modulo: Take the result modulo 10digits10^{\text{digits}} (e.g., 10610^6).
    8. Padding: If the result is shorter than the digit count, pad with zeros (e.g., "012345").

    4. Drafting the "From Scratch" Script:

    • Imports: time, hmac, hashlib, struct, base64, sys.
    • Function: generate_totp(secret, time_step=30, digits=6).
    • Secret handling: Google Authenticator style keys are Base32.
    • Code snippet:
      import time, hmac, hashlib, struct, base64
      
      def generate_totp(secret, time_step=30, digits=6, digest=hashlib.sha1):
          # Decode Base32 secret
          key = base64.b32decode(secret, case_insensitive=True)
      
          # Calculate counter
          current_time = int(time.time())
          counter = current_time // time_step
      
          # Pack counter as 8-byte big-endian
          counter_bytes = struct.pack('>Q', counter)
      
          # HMAC
          hmac_result = hmac.new(key, counter_bytes, digest).digest()
      
          # Dynamic Truncation
          offset = hmac_result[-1] & 0x0f
          code_int = struct.unpack('>I', hmac_result[offset:offset+4])[0]
          code_int &= 0x7fffffff # Strip sign bit
      
          # Modulo
          code = code_int % (10 ** digits)
      
          # Format with padding
          return str(code).zfill(digits)
      

    5. Drafting the "Library" Script (pyotp):

    • This is much simpler.
    • pip install pyotp
    • import pyotp
    • totp = pyotp.TOTP('BASE32SECRET')
    • print(totp.now())

    6. Refining the Output: The user asked for a script. A good script should be runnable.

    • I will provide the implementation using standard libraries (no pip install required) because it works out of the box in Python.
    • I will explain the code sections.
    • I will add an if __name__ == "__main__": block so the user can run it immediately with a test secret.
    • I will also mention pyotp as the "easy way" for production apps.

    7. Specific considerations for the Standard Library version:

    • Base32 decoding can fail if the string is bad. case_insensitive=True helps.
    • Need to handle the "remaining time" calculation to show the user how long the code is valid. This adds value.

    8. Constructing the Final Response:

    • Introduction: Acknowledge TOTP and RFC 6238.
    • Solution 1 (Standard Library): The "no dependencies" approach.
      • Provide the full code.
      • Include comments explaining the bitwise operations (truncation).
      • Include a demo loop.
    • Solution 2 (Using pyotp): The "industry standard" approach.
      • Briefly explain how to install and use it.
    • How to test: Explain how to use an authenticator app (Google/Microsoft Auth) with the provided secret to verify the script works.

    Self-Correction/Review during drafting:

    • Did I use base64.b64decode or b32decode? TOTP standard uses Base32 for the keys (e.g., JBSWY3DPEHPK3PXP). I must use b32decode.
    • Which Hash Algorithm? SHA1 is the default in Google Authenticator. SHA256 is optional but good to support. I'll stick to SHA1 as the default for maximum compatibility.
    • Endianness: TOTP requires Big Endian (>Q in struct). I made sure to include that.

    Final Code Structure:

    import hmac
    import hashlib
    import time
    import struct
    import base64
    
    def generate_totp(secret_key, interval=30, digits=6):
        # 1. Decode key
        # 2. Get time counter
        # 3. HMAC-SHA1
        # 4. Dynamic Truncation
        # 5. Return digits
        pass
    
    # Main execution block to run loop
    

    This looks solid. I will proceed with generating the response based on this structure. Here are two ways to do this. The first method uses Python's standard library (no installation required), which is best for understanding how the algorithm works. The second method uses the pyotp library, which is the industry standard for production applications.

    Method 1: Using Python Standard Library (No installation)

    This script implements the TOTP algorithm (RFC 6238) from scratch using hmac, hashlib, and time. It uses a Base32 encoded secret (the standard used by Google Authenticator and Authy).

    import hmac
    import hashlib
    import time
    import struct
    import base64
    import sys
    
    def generate_totp(secret_key, time_step=30, digits=6, hash_algorithm=hashlib.sha1):
        """
        Generates a Time-based One-Time Password (TOTP).
        
        :param secret_key: Base32 encoded secret key (string)
        :param time_step: Time interval in seconds (default 30)
        :param digits: Number of digits in the OTP (default 6)
        :param hash_algorithm: Hash function (default SHA-1)
        :return: OTP string
        """
        
        # 1. Decode the Base32 secret key
        # Padding is often missing in user keys, so we add it dynamically
        missing_padding = len(secret_key) % 8
        if missing_padding != 0:
            secret_key += '=' * (8 - missing_padding)
            
        try:
            key = base64.b32decode(secret_key, case_insensitive=True)
        except base64.binascii.Error:
            return "Error: Invalid Base32 secret key."
    
        # 2. Calculate the time counter (Number of intervals since Unix epoch)
        current_time = int(time.time())
        counter = int(current_time / time_step)
    
        # 3. Pack the counter into a byte string (Big Endian, 8 bytes)
        # This effectively converts the integer time counter to bytes
        counter_bytes = struct.pack('>Q', counter)
    
        # 4. Calculate the HMAC hash
        # hmac.new(key, msg, digest)
        hmac_hash = hmac.new(key, counter_bytes, hash_algorithm).digest()
    
        # 5. Dynamic Truncation (Extract a specific integer from the hash)
        # Get the last 4 bits of the hash to find the offset
        offset = hmac_hash[-1] & 0x0F
        
        # Extract 4 bytes starting at the offset
        truncated_hash = hmac_hash[offset:offset + 4]
        
        # Unpack as an integer (Big Endian)
        truncated_int = struct.unpack('>I', truncated_hash)[0]
        
        # Strip the most significant bit (to avoid signed/unsigned issues)
        truncated_int &= 0x7FFFFFFF
    
        # 6. Modulo to get the desired number of digits
        otp = truncated_int % (10 ** digits)
    
        # 7. Format with leading zeros if necessary
        return f"{otp:0{digits}d}"
    
    if __name__ == "__main__":
        # Example Secret (Base32)
        # In a real app, this secret is securely stored and shared with the user
        # This specific key is a common test vector: "12345678901234567890" in Base32
        MY_SECRET = "JBSWY3DPEHPK3PXP" 
    
        try:
            while True:
                otp = generate_totp(MY_SECRET)
                
                # Calculate remaining seconds
                remaining_seconds = 30 - (int(time.time()) % 30)
                
                # Print with carriage return to overwrite line
                sys.stdout.write(f"\rCurrent OTP: {otp} (Expires in {remaining_seconds}s)")
                sys.stdout.flush()
                
                time.sleep(1)
        except KeyboardInterrupt:
            print("\nExited.")
    

    Method 2: Using pyotp (Recommended for Production)

    If you are building a real application, you should use pyotp to ensure edge cases and compliance with various authenticator apps are handled correctly.

    Installation:

    pip install pyotp
    

    The Script:

    import pyotp
    import time
    import sys
    
    # Generate a random Base32 secret (Do this once and save it securely)
    # secret = pyotp.random_base32()
    # print(f"Your new secret is: {secret}")
    
    # Or use an existing secret
    SECRET = "JBSWY3DPEHPK3PXP"
    
    totp = pyotp.TOTP(SECRET)
    
    try:
        while True:
            current_otp = totp.now()
            remaining = 30 - (int(time.time()) % 30)
            
            sys.stdout.write(f"\rCurrent OTP: {current_otp} (Expires in {remaining}s)")
            sys.stdout.flush()
            
            time.sleep(1)
    except KeyboardInterrupt:
        print("\nExited.")
    

    How to verify it works

    1. Run the script.
    2. Open an authenticator app (Google Authenticator, Microsoft Authenticator, or Authy) on your phone.
    3. Select "Add Account" -> "Enter Setup Key" (or similar).
    4. For the secret key, enter: JBSWY3DPEHPK3PXP.
    5. The code on your phone should match the code generated by the Python script, and they should change at the exact same time.

    How the Algorithm Works (Breakdown)

    1. Secret Decoding: The keys are usually Base32 encoded. We decode them to raw bytes.
    2. Time Slicing: TOTP relies on the current time. We take the Unix timestamp (seconds since 1970) and divide it by a time step (usually 30 seconds). This gives us a "counter" that stays static for 30 seconds.
    3. HMAC: We calculate a Hash-based Message Authentication Code (HMAC) using the secret key and the time counter.
    4. Dynamic Truncation: The hash is long and complex. We take a small chunk (dynamic truncation) to convert those bytes into a single integer.
    5. Digit Reduction: We use the modulo operator (e.g., % 1000000) to turn that large integer into a 6-digit code.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.