Hi ππ
In this post, I will share with you How To Generate and Verify OTP Codes Using Python and pyotp.
Step 1
Install pyotp
pip install pyotp
Step 2
Generate secret key
import pyotp
print(pyotp.random_base32())
Result
KDLZXFSPUQQPFG2HUFZNRHBTWJNZUATJ
Step 3
Use this secret key to generate OTP codes
otp = pyotp.TOTP(s='KDLZXFSPUQQPFG2HUFZNRHBTWJNZUATJ')
print(otp.now())
Result
088644
Step 4
verify OTP Codes
otp.verify(otp.now())
Result
True
print(otp.now()) # 294950
time.sleep(30)
print(otp.verify('294950'))
verify code after 30s this will return False because this code expired
Generate QRCode to use it in Google Authenticator, Authy, or another compatible app. Users can set up auth tokens in their apps easily by using their phone camera to scan otpauth:// QR codes provided by PyOTP.
You can use any browser extinction like:
https://chromewebstore.google.com/detail/%D9%85%D8%B5%D8%A7%D8%AF%D9%82%D8%A9/bhghoamapcdpbohphigoooaddinpkbai
Install pyqrcode
pip install pyqrcode
import pyqrcode
secret_key = 'KDLZXFSPUQQPFG2HUFZNRHBTWJNZUATJ'
auth_data = pyotp.TOTP(s = secret_key).provisioning_uri(
name = 'user123@test.com',
issuer_name = 'Secure APP',
)
qr = pyqrcode.create(auth_data)
qr.png('qr.png')
Result
I used Google Authenticator
otp = pyotp.TOTP(s='KDLZXFSPUQQPFG2HUFZNRHBTWJNZUATJ')
otp_code = '087035' # from Google Authenticator
print(otp.verify(otp_code))
Result
True
Note
"After 30 seconds, this code will expire."
Top comments (0)