Skip to content

code (py) 2.0

Choose a tag to compare

@Janhavi1018 Janhavi1018 released this 15 May 13:50
502e353

`import secrets # For cryptographically secure random generation
import tkinter as tk # For GUI window and widgets
from tkinter import ttk # For modern themed widgets (buttons, entries, etc.)
from collections import namedtuple # For structured OTP storage
import time # For time-based expiry

-----------------------------

Data Structure and Logic

-----------------------------

Define a namedtuple to store OTP and its expiration time as a single entity

OTP = namedtuple("OTP", ["value", "expires_at"])

OTPManager class to encapsulate all OTP generation and validation logic

class OTPManager:
def init(self, expiry_seconds=30):
self.current_otp = None # Will hold the current OTP and its metadata
self.expiry_seconds = expiry_seconds # Time in seconds until the OTP expires

# Generate a secure OTP using the selected character set and desired length
def generate_otp(self, length=6, alphanumeric=True):
    digits = "0123456789"  # Numeric character set
    alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"  # Alphanumeric set
    charset = alphanum if alphanumeric else digits  # Choose the character set

    # Use secrets module to securely select random characters
    otp_value = ''.join(secrets.choice(charset) for _ in range(length))
    expiry = time.time() + self.expiry_seconds  # Calculate the expiration timestamp

    # Store the OTP and its expiration time
    self.current_otp = OTP(otp_value, expiry)
    return otp_value  # Return the generated OTP to the caller

# Check whether the current OTP is still valid (not expired)
def is_valid(self):
    return self.current_otp and time.time() < self.current_otp.expires_at

# Return the remaining time until the OTP expires
def time_left(self):
    if self.current_otp:
        return max(0, int(self.current_otp.expires_at - time.time()))
    return 0

-----------------------------

GUI Logic

-----------------------------

Instantiate the OTP manager

otp_manager = OTPManager(expiry_seconds=30)

Handle the Generate OTP button click

def update_otp():
global countdown_active # Use global flag to control countdown state

try:
    # Read and validate user input from entry field
    length = int(length_entry.get())
    use_alphanumeric = alphanum_var.get()

    # Generate a new OTP using the logic class
    otp = otp_manager.generate_otp(length, use_alphanumeric)

    # Display the OTP in the GUI
    otp_label.config(text=f"Your OTP is:\n{otp}")

    # Start the countdown timer
    countdown_active = True
    update_timer()
except ValueError:
    # If the user entered a non-integer value
    otp_label.config(text="Please enter a valid number!")
    timer_label.config(text="")

Update the countdown timer label every second

def update_timer():
global countdown_active

if countdown_active and otp_manager.is_valid():
    # Get remaining time and update the label
    remaining = otp_manager.time_left()
    timer_label.config(text=f"OTP expires in {remaining} seconds")

    # Call this function again after 1 second (1000 ms)
    root.after(1000, update_timer)
else:
    # If the OTP has expired or countdown stopped
    countdown_active = False
    timer_label.config(text="OTP expired. Generate a new one.")

-----------------------------

GUI Setup and Layout

-----------------------------

Create the main application window

root = tk.Tk()
root.title("Secure OTP Generator with Timer") # Window title
root.geometry("400x300") # Window size
root.resizable(False, False) # Prevent resizing

Title label

title = ttk.Label(root, text="OTP Generator", font=("Helvetica", 16))
title.pack(pady=10) # Vertical spacing

Frame to hold OTP length input field

length_frame = ttk.Frame(root)
length_frame.pack(pady=5)

Label and entry for OTP length

ttk.Label(length_frame, text="OTP Length:").pack(side=tk.LEFT, padx=5)
length_entry = ttk.Entry(length_frame, width=5)
length_entry.insert(0, "6") # Set default value to 6
length_entry.pack(side=tk.LEFT)

Checkbox to choose alphanumeric OTP

alphanum_var = tk.BooleanVar(value=True) # Default value: True
alphanum_check = ttk.Checkbutton(root, text="Use Alphanumeric", variable=alphanum_var)
alphanum_check.pack(pady=5)

Button to trigger OTP generation

generate_btn = ttk.Button(root, text="Generate OTP", command=update_otp)
generate_btn.pack(pady=10)

Label to display the generated OTP

otp_label = ttk.Label(root, text="", font=("Courier", 14), foreground="blue", justify=tk.CENTER)
otp_label.pack(pady=10)

Label to display the countdown timer

timer_label = ttk.Label(root, text="", font=("Arial", 10), foreground="red")
timer_label.pack()

Global variable to manage countdown state

countdown_active = False

Start the GUI event loop (keeps the window open and responsive)

root.mainloop()`