๐ Day 104/150 – OTP Generator in Python
One-Time Passwords (OTPs) are widely used to verify user identity during login, registration, online payments, and password recovery. Python provides multiple ways to generate OTPs, ranging from simple random numbers to cryptographically secure methods suitable for real-world applications.
In this post, we'll explore four different ways to generate OTPs in Python.
Method 1 – Random 4-Digit OTP
The simplest way to generate an OTP is by creating a random 4-digit number.
Sample Output
Your OTP is: 4831
Explanation
import random imports Python's random module.
random.randint(1000, 9999) generates a random integer between 1000 and 9999.
The generated number is printed as the OTP.
This method is easy to understand and suitable for learning purposes.
Note: The random module is not recommended for security-sensitive applications.
Method 2 – Random 6-Digit OTP
Many websites and mobile applications use 6-digit OTPs because they provide more possible combinations.
Sample Output
Your OTP is: 824175
Explanation
random.randint(100000, 999999) generates a random 6-digit number.
Since the minimum value is 100000, leading zeros are avoided.
This method is commonly used in practice for basic OTP generation.
Method 3 – OTP Using Digits
Instead of generating a random integer, we can build an OTP by randomly selecting digits.
Sample Output
Your OTP is: 593804
Explanation
string.digits contains all numeric characters (0123456789).
random.choices() randomly selects 6 digits.
"".join() combines those digits into a single string.
Since the OTP is a string, it can start with 0, which is useful in many authentication systems.
Method 4 – Secure OTP Generator
For real-world applications, Python's secrets module provides a more secure way to generate OTPs.
Sample Output
Your Secure OTP is: 071638
Explanation
secrets is designed for generating cryptographically secure random values.
secrets.choice() selects one random digit securely.
The loop runs 6 times to generate a 6-digit OTP.
This method is recommended for authentication systems, banking applications, and password reset features.
Tip: Whenever security matters, prefer the secrets module over random.


0 Comments:
Post a Comment