L3 - Create Python Console Application to randomly generate OTP kind of secure code
To create a Python console application that randomly generates a secure OTP (One-Time Password),
follow these steps:
Step 1: Set Up Your Environment
Make sure you have Python installed. You can check this by running:
python –version
If Python is not installed, download and install it from the official Python website.
Step 2: Import Necessary Libraries
You'll need the random and string libraries to generate random OTPs.
import random
import string
Step 3: Define a Function to Generate the OTP
Here, you'll define a function that generates an OTP of a specified length.
def generate_otp(length=6):
characters = string.ascii_letters + string.digits
otp = ''.join(random.choice(characters) for _ in range(length))
return otp
Step 4: Create the Console Application
Now, integrate the function into a simple console application.
def main():
print("Welcome to the OTP Generator")
length = int(input("Enter the length of the OTP: "))
otp = generate_otp(length)
print(f"Your OTP is: {otp}")
if __name__ == "__main__":
main()
Step 5: Run the Application
Save your script as otp_generator.py and run it:
Step 6: Add Security Features (Optional)
Use a Cryptographic Random Generator: Instead of random, you can use secrets for a more
secure OTP.
import secrets
def generate_otp(length=6):
characters = string.ascii_letters + string.digits
otp = ''.join(secrets.choice(characters) for _ in range(length))
return otp
Restrict to Digits Only: If you want the OTP to be numeric, modify the characters variable.
Step 7: Error Handling and Enhancements (Optional)
You can add error handling, such as ensuring the user inputs a valid number for the OTP length.
Step 8: Test the Application
Run the script multiple times to ensure it works as expected.
This Python console application will generate a secure OTP based on user-specified length and can
be easily modified or extended for additional functionality.