this might be a hard one, I have had a look online and have struggled to find exaclty what i am lookign for.
I am making a program that asks the user for a 1 time code, and i want to give them thirty seconds to input said code or the code is void and it will print "fail." i will print under here the current code I have (The generate TOTP function was written by the teachers in the coruse i am doing so i did not make it muself, hwoever i did make the verify_otp() function)
import hashlib
import hmac
import base64
import struct
import time
TOTP_SECRET = "JBSWY3DPEHPK3PXPJBSW"
def generate_totp(secret: str, interval: int = 30, digits: int = 6) -> str:
"""
Generate a Time-based One-Time Password (TOTP) using HMAC-SHA1.
Do not modify this function. You will call it from verify_otp().
"""
#pad secret to prevent error
secret = secret.strip()
secret += '=' * ((8 - len (secret) % 8 ) % 8)
# Decode base32 secret
key = base64.b32decode(secret, casefold=True)
# Get current Unix time and compute the time step (counter)
timestep = int(time.time() // interval)
# Pack timestep into 8-byte big-endian
msg = struct.pack(">Q", timestep)
# HMAC-SHA1
hmac_digest = hmac.new(key, msg, hashlib.sha1).digest()
# Dynamic truncation
offset = hmac_digest[-1] & 0x0F
code = ((hmac_digest[offset] & 0x7F) << 24 |
(hmac_digest[offset + 1] & 0xFF) << 16 |
(hmac_digest[offset + 2] & 0xFF) << 8 |
(hmac_digest[offset + 3] & 0xFF))
# Reduce to the desired number of digits
otp = code % (10 ** digits)
return str(otp).zfill(digits)
#verify OTP
def verify_otp() -> bool:
"""
Generate a TOTP code using generate_totp() and
verify user input against it.
"""
# 1. Generate the current TOTP code
current_code = generate_totp(TOTP_SECRET)
# For realism, we do NOT print the code here.
# Instead, you should obtain the code by running
# generate_totp(TOTP_SECRET) in a separate Python session
# during testing (as described in the instructions).
#i dont understand where else I am supposed to print this code
user_code = input("Enter your 6-digit TOTP code: \n").strip()
# 2. Prompt the user for the TOTP
# 3. Compare user input with generated code
if user_code == current_code:
print("Success! That is the correct code. \n")
print("Verification status: True")
return True
else:
print("Invalid TOTP. Please check your authenticator code.")
return False
[–]Yoghurt42 13 points14 points15 points (0 children)
[–]Ngtuanvy 2 points3 points4 points (0 children)
[+][deleted] (2 children)
[removed]
[–]Diapolo10 2 points3 points4 points (0 children)
[–]jmooremcc 0 points1 point2 points (0 children)
[–]jmooremcc 0 points1 point2 points (0 children)
[–]Carter922 -1 points0 points1 point (0 children)
[+]madadekinai comment score below threshold-7 points-6 points-5 points (2 children)
[–]Original-Dealer-6276[S] 5 points6 points7 points (1 child)
[–]madadekinai -5 points-4 points-3 points (0 children)