From 3d1701682378a0231d18f8647bb5a089b36aaba6 Mon Sep 17 00:00:00 2001 From: whaffman Date: Thu, 3 Jul 2025 20:05:20 +0200 Subject: [PATCH] Improve error handling and user feedback in OTP key generation and reading functions --- ft_otp.py | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/ft_otp.py b/ft_otp.py index 97d5b10..a93ac04 100644 --- a/ft_otp.py +++ b/ft_otp.py @@ -26,7 +26,6 @@ def main(): elif args.q: # Call the function to generate a QR code for the OTP key generate_qr_code() - print("QR code generated successfully.") else: print("No action specified. Use -g to generate a new OTP key or -k to generate a OTP from a key file.") parser.print_help() @@ -41,8 +40,15 @@ def is_hex(s): def generate_secret_key(secret_file): print(f"Generating OTP key from {secret_file}...") machine_id = get_machine_hash() - with open(secret_file, 'rb') as f: - secret = f.read().strip() + try: + with open(secret_file, 'r') as f: + secret = f.read().strip() + except FileNotFoundError: + print(f"Secret file {secret_file} not found. Please provide a valid file.") + return + if not secret: + print("The provided secret file is empty. Please provide a valid secret.") + return if not is_hex(secret.decode()): print("The provided secret is not a valid hexadecimal string.") return @@ -51,14 +57,29 @@ def generate_secret_key(secret_file): return fernet = Fernet(machine_id) secret_enc = fernet.encrypt(secret) - with open('./ft_otp.key', 'wb') as f: - f.write(secret_enc) + try: + with open('./ft_otp.key', 'wb') as f: + f.write(secret_enc) + print("OTP key generated and saved to ft_otp.key") + except IOError as e: + print(f"Error writing to file: {e}") + return def read_secret_key(keyfile): """Read the secret key from the specified file.""" machine_id = get_machine_hash() - with open(keyfile, 'rb') as f: - secret_enc = f.read().strip() + if machine_id is None: + print("Machine ID could not be retrieved. Exiting.") + return None + try: + with open(keyfile, 'rb') as f: + secret_enc = f.read().strip() + except FileNotFoundError: + print(f"Key file {keyfile} not found. Please provide a valid file.") + return None + if not secret_enc: + print("The provided key file is empty. Please provide a valid key file.") + return None fernet = Fernet(machine_id) secret = fernet.decrypt(secret_enc) return secret @@ -67,10 +88,8 @@ def generate_qr_code(): """Generate a QR code for the OTP key.""" keyfile = './ft_otp.key' secret = read_secret_key(keyfile) - print(f"Secret key read from {keyfile}: {secret.decode()}") base32 = base64.b32encode(base64.b16decode(secret.upper())).decode().strip('=') - print(str(base32)) - otp_uri = f"otpauth://totp/FTOTP?secret={base32}&issuer=FTOTP&algo=SHA1&digits=6&period=30" + otp_uri = f"otpauth://totp/FTOTP?secret={base32}&issuer=whaffman&algo=SHA1&digits=6&period=30" qrcode_terminal.draw(otp_uri) def generate_otp_from_secret_key(keyfile):