Created
January 15, 2026 13:43
-
-
Save kBashar/1bdd72a1b7887b86d7362bc35173f009 to your computer and use it in GitHub Desktop.
Implementing TOTP and Dynamic Truncation
This file contains hidden or 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 base64 | |
| import time | |
| import math | |
| import hmac | |
| import hashlib | |
| def print_bytes(bytes): | |
| print(",".join([str(byt) for byt in bytes])) | |
| def base32_decode(encoded_str): | |
| return base64.b32decode(s=encoded_str) | |
| def counter_array(): | |
| timestamp = time.time() | |
| counter = math.floor(timestamp/30) | |
| counter_bytes = counter.to_bytes(8, byteorder="big") | |
| return counter_bytes | |
| def hmac_sha1_bytes(secretkey_bytes, counter_bytes): | |
| hmac_obj = hmac.new(secretkey_bytes, counter_bytes, digestmod=hashlib.sha1) | |
| digest_bytes = hmac_obj.digest() | |
| return digest_bytes | |
| def generate_code(secretkey_bytes, counter_bytes): | |
| digest_bytes = hmac_sha1_bytes(secretkey_bytes, counter_bytes) | |
| last_byte = digest_bytes[-1] | |
| four_digit_mask = 0b1111 | |
| last_four_digits = last_byte & four_digit_mask | |
| offset = last_four_digits | |
| random_four_bytes = digest_bytes[offset:offset+4] # from the offset take 4 bytes | |
| number = int.from_bytes(random_four_bytes, byteorder="big") | |
| mask = 0x7FFFFFFF | |
| positive_number = number & mask | |
| six_digit_codes = positive_number % 1000000 | |
| return str(six_digit_codes).zfill(6) | |
| def main(): | |
| secret_key = "JBSWY3DPEHPK3PXP" | |
| secretkey_byte_array = base32_decode(secret_key) | |
| counter_bytes = counter_array() | |
| code = generate_code(secretkey_byte_array, counter_bytes) | |
| print(code) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment