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 PyOTP, which implement the RFC 4226 and RFC 6238 standards. If you want to use this library you should follow the requirements in those standards. Installation:
1
pip install pyotp
Copied!

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 OpenSource 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.
1
import pyotp
2
3
base32secret = pyotp.random_base32()
4
print('Secret:', base32secret)
5
6
totp_uri = pyotp.totp.TOTP(base32secret).provisioning_uri(
8
issuer_name="Secure App")
9
print(totp_uri)
Copied!
Sample output:
1
Secret: S3K3TPI5MYA2M67V
2
otpauth://totp/Secure%20App:alice%40google.com?secret=S3K3TPI5MYA2M67V&issuer=Secure%20App
Copied!

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.
1
import pyotp
2
import time
3
4
base32secret = 'S3K3TPI5MYA2M67V'
5
print('Secret:', base32secret)
6
7
totp = pyotp.TOTP(base32secret)
8
print('OTP code:', totp.now())
9
time.sleep(30)
10
print('OTP code:', totp.now())
Copied!
Sample output:
1
Secret: S3K3TPI5MYA2M67V
2
OTP code: 339838
3
OTP code: 284911
Copied!

Working Example

You can install Google Authenticator from Google Play or App Store and scan the QR code below:
OTP Auth
Example validation check:
1
import pyotp
2
3
base32secret = 'S3K3TPI5MYA2M67V'
4
print('Secret:', base32secret)
5
6
totp = pyotp.TOTP(base32secret)
7
your_code = '123456'
8
print(totp.verify('Code Valid:', your_code))
Copied!
Output:
1
Secret: S3K3TPI5MYA2M67V
2
Code Valid: True
Copied!
Last modified 4d ago