Hazmat TOTP
[Hazmat Home][Home]
TOTP (Timed One Time Passwords) are used to create a one time value which is only valid for a given time period. This is often used in two-factor authentication methods, and where a user has a given amount of time to enter a token value. In this case the time-out is after one second, and where we test every 0.25 seconds. The valid hashing algorithms used are SHA-1 (160 bit hash), SHA-256 (256-bit hash) and SHA-512 (512-bit hash), and the output is a numeric value with between 6 and 8 characters.
|
Code
Hazmat supports core cryptographical primitives for HOTP:
import os import time from cryptography.hazmat.primitives.twofactor.totp import TOTP from cryptography.hazmat.primitives.hashes import SHA256, SHA1, SHA512 from cryptography.hazmat.primitives import twofactor import sys import binascii chars=6 h=SHA256() htype=1 if (len(sys.argv)>1): chars=int(sys.argv[1]) if (len(sys.argv)>2): htype=int(sys.argv[2]) if (htype==1): h=SHA256() if (htype==2): h=SHA1() if (htype==3): h=SHA512() key = os.urandom(20) totp = TOTP(key, chars, h, 1) time_value = time.time() totp_value = totp.generate(time_value) print ("=== TOTP ===") print ("Hash type: ",h.name) print(f"Key: ",binascii.b2a_hex(key)) print() for count in range(0,8): try: time_value = time.time() totp.verify(totp_value, time_value) time.sleep(0.25) except twofactor.InvalidToken: print ("Invalid: ",totp_value,time_value) else: print ("Valid: ",totp_value,time_value)
A sample run is:
=== TOTP === Hash type: sha256 Key: b'43a60f5d1c92b30a6561dfb5ec82a17924aa56eb' Valid: b'750122' 1626852456.053 Valid: b'750122' 1626852456.304 Valid: b'750122' 1626852456.554 Valid: b'750122' 1626852456.804 Invalid: b'750122' 1626852457.0540001 Invalid: b'750122' 1626852457.0540001 Invalid: b'750122' 1626852457.0540001 Invalid: b'750122' 1626852457.0540001