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:
pip install pyotp
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.
import pyotpbase32secret = pyotp.random_base32()print('Secret:', base32secret)totp_uri = pyotp.totp.TOTP(base32secret).provisioning_uri(issuer_name="Secure App")print(totp_uri)
Run the above code example: https://repl.it/@nakov/OTP-Server-Side-in-Python.
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.
import pyotpimport timebase32secret = 'S3K3TPI5MYA2M67V'print('Secret:', base32secret)totp = pyotp.TOTP(base32secret)print('OTP code:', totp.now())time.sleep(30)print('OTP code:', totp.now())
Run the above code example: https://repl.it/@nakov/OTP-Client-Side-in-Python.
Secret: S3K3TPI5MYA2M67VOTP code: 339838OTP code: 284911
Example validation check:
import pyotpbase32secret = 'S3K3TPI5MYA2M67V'print('Secret:', base32secret)totp = pyotp.TOTP(base32secret)your_code = '123456'print(totp.verify('Code Valid:', your_code))
Run the above code example: https://repl.it/@nakov/QR-code-scanner-in-Python.
Secret: S3K3TPI5MYA2M67VCode Valid: True