One-Time Passwords (OTP) - Example

In this section, we shall provide an example of how to generate and validate One-Time Passwords (OTP) in Python. The Python library of our choice is PyOTParrow-up-right, which implement the RFC 4226arrow-up-right and RFC 6238arrow-up-right standards. If you want to use this library you should follow the requirements in those standards. Installation:

pip install pyotp

Server-Side Setup

We need to create a base32 secret which has to be shared between the authentication server and the client. We will use Google Authenticator OpenSourcearrow-up-right OTP model which produce a URI for an exchange, the secret and additional client-server details. It includes the shared secret, the client's username, and the issuer's name.

import pyotp

base32secret = pyotp.random_base32()
print('Secret:', base32secret)

totp_uri = pyotp.totp.TOTP(base32secret).provisioning_uri(
    "[email protected]",
    issuer_name="Secure App")
print(totp_uri)

Run the above code example: https://repl.it/@nakov/OTP-Server-Side-in-Pythonarrow-up-right.

Sample output:

Secret: S3K3TPI5MYA2M67V
otpauth://totp/Secure%20App:alice%40google.com?secret=S3K3TPI5MYA2M67V&issuer=Secure%20App

Client-Side Setup

Once the client stores the secret in a secure way, in a time-interval of a 30 seconds (by default) a new code will be generated.

Run the above code example: https://repl.it/@nakov/OTP-Client-Side-in-Pythonarrow-up-right.

Sample output:

Working Example

You can install Google Authenticator from Google Playarrow-up-right or App Storearrow-up-right and scan the QR code below:

OTP Auth

Example validation check:

Run the above code example: https://repl.it/@nakov/QR-code-scanner-in-Pythonarrow-up-right.

Output:

Last updated