I write this code in python at jupyter notebook envirment. I try to implement TOTP without build in library "pyotp". I generate QR code and scan it with google authenticator but the code which authenticator generates dose not match the code generated with my python code!!
import hashlib
import hmac
import struct
import time
import base64
import os
import qrcode
from IPython.display import Image
secret_key = base64.b32encode(os.urandom(10))
print(secret_key)
def generate_totp(secret, time_step=30, digits=6):
timestamp = int(time.time())
counter = timestamp // time_step
counter_bytes = struct.pack('>Q', counter)
hmac_sha1 = hmac.new(secret, counter_bytes, hashlib.sha1).digest()
offset = hmac_sha1[-1] & 0x0F
binary = struct.unpack('>I', hmac_sha1[offset:offset + 4])[0]
totp = binary % 10 ** digits
return str(totp).zfill(digits)
totp_code = generate_totp(secret_key)
otp_uri = f'otpauth://totp/MyServiceName?secret={secret_key.decode()}'
qr = qrcode.QRCode(version=1, box_size=10, border=5)
qr.add_data(otp_uri)
qr.make(fit=True)
img = qr.make_image(fill='black', back_color='white')
img.save('totp_qr.png')
Image(filename='totp_qr.png')
user_input_code =int(input("Please, enter your code: "))
is_valid = int(generate_totp(secret_key))
if is_valid == user_input_code:
print("User's TOTP code is valid")
else:
print("User's TOTP code is not valid")