Code for How to Implement 2FA in Python Tutorial


View on Github

totp.py

import pyotp

# Generate a random key. You can also set to a variable e.g key = "CodingFleet"
key = pyotp.random_base32()
# Make Time based OTPs from the key.
totp = pyotp.TOTP(key)

# Print current key.
print(totp.now())

# Enter OTP for verification
input_code = input("Enter your OTP:")
# Verify OTP
print(totp.verify(input_code))

otp_verification.py

# Program 2: Verify TOTP Code with Google Authenticator
import pyotp


def simulate_authentication(key):
    # Simulate the process of authenticating with a TOTP code.
    totp = pyotp.TOTP(key)
    print("Enter the code from your Google Authenticator app to complete authentication.")
    user_input = input("Enter Code: ")
    if totp.verify(user_input):
        print("Authentication successful!")
    else:
        print("Authentication failed. Please try again with the right key.")


# Main Code
# The key should be the same one generated and used to create the QR code in Program 1
user_key = open("2fa.txt").read()  # Reading the key from the file generated in Program 1 (otp_qrcode_and_key.py)
simulate_authentication(user_key)

hotp.py

import pyotp

# Set the key. A variable this time
key = 'Muhammad'
# Make a HMAC-based OTP
hotp = pyotp.HOTP(key)

# Print results
print(hotp.at(0))
print(hotp.at(1))
print(hotp.at(2))
print(hotp.at(3))

# Set counter
counter = 0
for otp in range(4):
    print(hotp.verify(input("Enter Code: "), counter))
    counter += 1

otp_qrcode_and_key.py

# Program 1: Generate and Save TOTP Key and QR Code
import pyotp, qrcode


def generate_otp_key():
    # Generate a random key for TOTP authentication.
    return pyotp.random_base32()


def generate_qr_code(key, account_name, issuer_name):
    # Generate a QR code for TOTP authentication.
    uri = pyotp.totp.TOTP(key).provisioning_uri(name=account_name, issuer_name=issuer_name)
    img = qrcode.make(uri)
    img.save('totp_qr.png')
    print("QR Code generated and saved as 'totp_qr.png'.")


# Main code.
# Generate user key.
user_key = generate_otp_key()
print("Your Two-Factor Authentication Key:", user_key)
# Save key to a file for reference purposes
with open('2fa.txt', 'w') as f:
    f.write(user_key)
# Generate QR Code.
generate_qr_code(user_key, 'Muhammad', 'CodingFleet.com')