generate OTP using python

How to generate OTP? | With Python

OTP we all know what they are and why they are used but most of use don’t know how they are generated in this article we will explore how an OTP is generated and how you can generate OTP. We will also be creating a small python app that requires an OTP for Login and an Authenticator app as well.

Setting up a one-time password

Enhancing security measures for your applications entails configuring a one-time password (OTP) mechanism.

To achieve this, a confidential key is produced and bestowed upon the user who plans to perform authentication.

Maintaining the secrecy of this particular key is paramount since it is the foundation for generating the OTP value.

Once the user obtains the confidential key, they are permitted to operate it with a Time-based One-Time Password (TOTP) generator application or software that fabricates OTP values for authentication.

On top of that, the server-side application also needs to authenticate the OTP and verify that it matches the anticipated value for successful validation.

By implementing a one-time password strategy, you can add another layer of safeguarding to your applications hence guaranteeing that only granted users have admission to sensitive data or the ability to perform restricted actions.

Why you should use OTP instead of a regular Login password?

Using one-time passwords or OTP provides an extra layer of security for user accounts. Regular login passwords can be more vulnerable to hacking or keylogging attacks that steal user credentials.

An OTP is a random code sent to the user’s mobile number via text message. It is valid for a single login session and expires quickly, often within a few minutes. This means that even if the account password is compromised, the hacker would not be able to access the account without also gaining access to the user’s mobile phone.

For further information read this Article

What is OTP? | One-Time Password Explained

We all know about OTP and use it almost every day but most of us doesn’t completely understands it…

How OTP is generated?

To generate OTP you can use Authentication apps like Google or Microsoft Authenticator which uses a secret key to generate one-time passwords.

But first you will need to get a secret key for your App. How will you get one we will dive into that later, let’s first talk about the requirements.

Requirements

You will need to get these three packages along with Python 3.0+

1) pyotp

To install pyotp, copy and paste this command in your terminal

pip install pyotp

2) qrcode

To install qrcode, copy and paste this command in your terminal

pip install qrcode

3) time

It is build into Python so no need to install it manually ?

Get a Secret Key

Now you have all the things you need to get a secret key and create a new Python file and write:

import pyotp
key = pyotp.random_base32()
print(key)

This is going to give you a random 32-character-long secret key let’s say your secret key is something like

Secret Key: CQKELSVRP4ILEI4IVJX24LQW6IU7TYJI

You have your Secret Key with you now you need to get an OTP out of it ❗

Generate OTP using Authentication App

This is something really interesting to generate a one-time password for your app you can either

  1. Use Authenticator apps like Google Authenticator and Microsoft Authenticator or
  2. You can create your own Authentication App

1) Use Authenticator apps like Google and Microsoft Authenticator to Generate OTP

To use the Authenticator apps for generating One-Time Passwords, simply create another Python file.
Write these lines inside this Python file and run the program.

import qrcode, pyotp

key = "CQKELSVRP4ILEI4IVJX24LQW6IU7TYJI"

Totp = pyotp.TOTP(key)

Uri = Totp.provisioning_uri(name="Name of the App/Company", issuer_name="User Name")
print(Uri)
qrcode.make(Uri).show()

In line One Paste the Secret key that you generated previously. This program is going to Create a URI for your secret key.

Change the nameand issuer_name variable in line 7 to Name of your Company or App ( Just write you app name if you don’t have a company ?) and Name of the user for which OTP is generated.

This program is going to open a QR code on the screen. open any Authenticator app of your choice and scan this QR code to start generating One-Time Passwords.

You can now generate OTP for your app, now it’s time to setup your app which is going to utilize the generated OTP.

1) Create your own Authentication App

Creating your own Authentication App is really simple ( If you just copy-paste the code from here ? ). All you need to do is, just create another Python file name it OAuth.py and insert these lines in it.

import pyotp
import time

# Replace this with your own shared secret key
shared_secret = 'CQKELSVRP4ILEI4IVJX24LQW6IU7TYJI'

# Create a TOTP object with a time step of 30 seconds
totp = pyotp.TOTP(shared_secret, interval=30)

# Define a function to display the countdown and current OTP
def display_otp():
    # Get the current OTP
    current_otp = totp.now()

    # Print the current OTP and countdown
    print("Current OTP:", current_otp,"|")
    for i in range(30, 0, -1):
        print(i, end=" ", flush=True)
        time.sleep(1)
        print("\r", end="", flush=True)
    print()


# Loop indefinitely to generate and display OTPs
while True:
    display_otp()

Paste your secret key in line 5 and just run the program it is going to generate a TOTP based on your secret key.

Creating a 2FA App in Python

You got your secret key and OTP generation working, now the only thing left to do is create an app for testing that generates One-Time Passwords that is generated using a secret key. For this example, we will be using Time-Based OTP (TOTP) generation algorithm to generate one-time passwords for our app.

Create a new python file named App.py with the following content in it.

import pyotp

key = "CQKELSVRP4ILEI4IVJX24LQW6IU7TYJI"
Totp = pyotp.TOTP(key)

def Generate_Verify_OTP():
    Generated_Otp = Totp.now()
    print("Current OTP : ", Generated_Otp) # Remove this line to stop print the required OTP

    User_Otp = input("Enter your OTP : ")
    if Totp.verify(User_Otp):
        print("\n\n\tVerified OTP !!\n")
    else:
        print("\n\n\tInvalid OTP !!\n")
if __name__ == "__main__":
    while True:
        Generate_Verify_OTP()

In line 3 paste your own Secrete key and run the program. It is going to print the OTP required to log in to the Application. Remove line 8 to stop printing the required OTP.

Now Open your Authentication app which you went with in OTP Generation with Authentication Apps section.

You now have a fully functioning 2FA Python App that uses the TOTP algorithm to generate One-Time-Passwords.