Skip to content

Instantly share code, notes, and snippets.

@frasertweedale
Last active August 19, 2018 22:45
Show Gist options
  • Save frasertweedale/607c2e80683c36d576d2 to your computer and use it in GitHub Desktop.
Save frasertweedale/607c2e80683c36d576d2 to your computer and use it in GitHub Desktop.
HOTP implementation; Python
import hashlib
import hmac
import struct
def dt(mac):
hdig = mac.hexdigest()
offset = int(hdig[-1], 16)
p = hdig[offset * 2 : offset * 2 + 8]
return int(p, 16) & 0x7fffffff
def hotp(k, c, n):
"""Generate an HOTP token.
``k``
Key; bytestring of length 20.
``c``
Counter; integer in range 0 .. 2**64 - 1
``n``
Token length; integer in {6,7,8}
"""
mac = hmac.new(k, struct.pack(">Q", c), hashlib.sha1)
s = dt(mac)
return "{:06}".format(s % 10 ** n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment