Last active
June 22, 2019 04:55
-
-
Save nvn1729/3e7562bc1802a5c094ddb12a31c2eae1 to your computer and use it in GitHub Desktop.
python 3 code for creating OTP code using TOTP algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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