Skip to content

Instantly share code, notes, and snippets.

@BharatKalluri
Created October 24, 2021 13:23
Show Gist options
  • Select an option

  • Save BharatKalluri/fde73e3e0d734b35465f12ed23086494 to your computer and use it in GitHub Desktop.

Select an option

Save BharatKalluri/fde73e3e0d734b35465f12ed23086494 to your computer and use it in GitHub Desktop.
TOTP implementation in python
import base64
import hashlib
import hmac
import math
import time
def dynamic_truncation(raw_key: hmac.HMAC, length: int) -> str:
hex_digest: str = raw_key.hexdigest()
int_repr: int = int(hex_digest, base=16)
bitstring: str = bin(int_repr)
last_four_bits: str = bitstring[-4:]
offset: int = int(last_four_bits, base=2)
chosen_32_bits: str = bitstring[offset * 8: offset * 8 + 32]
full_totp: str = str(int(chosen_32_bits, base=2))
return full_totp[-length:]
def generate_totp(shared_key: str, length: int = 6) -> str:
now_in_seconds: int = math.floor(time.time())
step_in_seconds = 30
t: int = math.floor(now_in_seconds / step_in_seconds)
hmac_hash = hmac.new(
base64.b32decode(shared_key, True),
t.to_bytes(length=8, byteorder="big"),
hashlib.sha1,
)
return dynamic_truncation(hmac_hash, length)
def validate_totp(totp: str, shared_key: str) -> bool:
return totp == generate_totp(shared_key)
if __name__ == "__main__":
secret = "VNIGBG35N7XUHCZZ"
print("Generating One-Time Password...")
totp = generate_totp(secret)
print(f"Done. It is: {totp}")
print("Validating One-Time Password...")
if validate_totp(totp, secret):
print("It is valid!")
else:
print("It is invalid.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment