01. A Fórmula Matemática Central do TOTP
// 1. Contador baseado no relógio Unix (janelas de 30s):
T = floor((Tempo_Atual - 0) / 30)
// 2. Digest HMAC com chave compartilhada:
HMAC_Result = HMAC-SHA-1(Chave_Secreta, T)
// 3. Truncamento dinâmico e módulo 10^6:
TOTP = Truncate(HMAC_Result) mod 1000000
02. Implementação Completa em Python Puro
import hmac import hashlib import time import struct import base64def generate_totp(secret: str, interval: int = 30) -> str: cleaned = secret.replace(” ”, "").upper() padding = len(cleaned) % 8 if padding: cleaned += ’=’ * (8 - padding) key = base64.b32decode(cleaned)
time_step = int(time.time()) // interval msg = struct.pack(“>Q”, time_step) digest = hmac.new(key, msg, hashlib.sha1).digest()
offset = digest[-1] & 0x0F code_int = struct.unpack(“>I”, digest[offset:offset+4])[0] & 0x7FFFFFFF return str(code_int % 1000000).zfill(6)
if name == “main”: print(“Código TOTP atual:”, generate_totp(“JBSWY3DPEHPK3PXP”))