Skip to content

Instantly share code, notes, and snippets.

@nvn1729
Last active June 22, 2019 04:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nvn1729/3e7562bc1802a5c094ddb12a31c2eae1 to your computer and use it in GitHub Desktop.
Save nvn1729/3e7562bc1802a5c094ddb12a31c2eae1 to your computer and use it in GitHub Desktop.
python 3 code for creating OTP code using TOTP algorithm
import hashlib, hmac, time, base64, math
def totp_at(secret, digits, period, algorithm, t):
counter = t // period
counter_bytes = counter.to_bytes(8, byteorder='big')
digest = hmac.new(secret, msg=counter_bytes, digestmod=algorithm).digest()
offset = digest[-1] & 0x0F
v_bytes = [ digest[offset] & 0x7F, digest[offset+1], digest[offset+2], digest[offset+3] ]
v = int.from_bytes(v_bytes, byteorder='big')
code = str(v % (10**digits))
code = (digits - len(code))*'0' + code
return code
def totp_now(secret, digits, period, algorithm):
t = math.floor(time.time())
return totp_at(secret, digits, period, algorithm, t)
secret = base64.b32decode('W2ASCT52EGQLJ42I5THBMEK2BYJ3Q5JRKIZLSEPNN4YW3KSLWQTH2LRSPAVUFFAY')
digits = 6
period = 30
algorithm = hashlib.sha1
code = totp_now(secret, digits, period, algorithm)
print(code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment