TOTPコード生成
Google Authenticator互換の時間ベースワンタイムパスワード(TOTP)を生成します。
現在のコード
------
有効期限 30秒
次のコード
------
Google Authenticator、Authyなどのアプリと互換性があります。コードを確認するには、このシークレットを認証アプリに追加してください。
よくある質問
コード実装
import hmac, hashlib, struct, time, base64
def hotp(secret_b32: str, counter: int, digits: int = 6) -> str:
"""HMAC-based One-Time Password (RFC 4226)."""
key = base64.b32decode(secret_b32.upper().replace(" ", ""))
msg = struct.pack(">Q", counter) # 8-byte big-endian counter
h = hmac.new(key, msg, hashlib.sha1).digest()
offset = h[-1] & 0x0F
code = struct.unpack(">I", h[offset:offset+4])[0] & 0x7FFFFFFF
return str(code % (10 ** digits)).zfill(digits)
def totp(secret_b32: str, digits: int = 6, period: int = 30) -> str:
"""Time-based One-Time Password (RFC 6238)."""
counter = int(time.time()) // period
return hotp(secret_b32, counter, digits)
def totp_remaining_seconds(period: int = 30) -> int:
"""Seconds until the current TOTP window expires."""
return period - (int(time.time()) % period)
# Demo — replace with your own base32 secret
SECRET = "JBSWY3DPEHPK3PXP"
print(f"TOTP: {totp(SECRET)} (expires in {totp_remaining_seconds()}s)")Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.