• home
  • about
  • 全ての投稿
  • ソフトウェア・ハードウェアの設定のまとめ
  • 分析関連のまとめ
  • ヘルスケア関連のまとめ
  • 生涯学習関連のまとめ

totp

date: 2021-02-28 excerpt: TOTP(Time-based One-Time Password)について

tag: totpsecurity


TOTP(Time-based One-Time Password)について

TOTPとは銀行やウェブサービスのログインの際に求められるパスワードのことである

仕組み

完結に記すと以下の式になる

\[password = hash(sercretkey, unixtime)\]

これだけなのだがRFCという国際規格にても定義されており挙動が正確に記述されている

pythonで記すと以下のようなコードになる

import hmac, base64, struct, hashlib, time

def get_hotp_token(secret: str, intervals_no: int) -> str:
	# at first, decode key
    key = base64.b32decode(secret, True)
	# change data to C
    msg = struct.pack(">Q", intervals_no)
    h = hmac.new(key, msg, hashlib.sha1).digest()
    o = h[19] & 15
    h = (struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000
    return str(h)

def get_totp_token(secret):
    # ensuring to give the same otp for 30 seconds
    x = get_hotp_token(secret=secret, intervals_no=int(time.time())//30)
    # adding 0 in the beginning till OTP has 6 digits
    while len(x)!=6:
        x+='0'
    return x

実行

#base64 encoded key
secret = 'SOMETHINGSEC===='
print(get_totp_token(secret))

>> 829034

実際に自分で実行してみよう

  • Google Colab

説明用のプレゼン資料

参考

  • Understanding TOTP : In Python
  • Google Authenticator implementation in Python


totpsecurity Share Tweet