I'm working on a tool that uses hex API keys to log a user into a remote hosted tool. For security purposes, I'm using Fernet to encrypt the keys locally and store them in a text file so the user doesn't have to enter them every time. We need to decrypt the API keys so the user can log in. The issue is that I'm loading the keys in from a text file, and I'm getting the following error when passing the string data back to Fernet:
ValueError: Fernet key must be 32 url-safe base64-encoded bytes.
Any idea what I'm doing wrong? Here are my functions:
# This function generates the local key file
def key_gen(access_key, secret_key):
from os import getcwd
from cryptography.fernet import Fernet
file_data = []
key = Fernet.generate_key()
encrypted_ak = encrypt_data(access_key, key)
encrypted_sk = encrypt_data(secret_key, key)
current_dir = getcwd()
key_file = current_dir + "\\tenableauth.txt"
file_data.append(key)
file_data.append(encrypted_ak)
file_data.append(encrypted_sk)
with open(key_file, 'w') as authentication_file:
for line in file_data:
authentication_file.writelines(str(line) + "\n")
return key_file
# This function reads the local key file, and is where I'm hitting problems. Lots of test code here.
def read_keys(file):
file_lines = []
with open(file, 'r') as authentication_file:
for line in authentication_file:
file_lines.append(line)
encryption_key = file_lines[0]
encryption_key = encryption_key.rstrip()
print(encryption_key)
print(repr(encryption_key))
decrypted_ak = decrypt_data(file_lines[1], encryption_key)
print(decrypted_ak)
def encrypt_data(data, key):
from cryptography.fernet import Fernet
data = data.encode()
encrypted_string = Fernet(key).encrypt(data)
return encrypted_string
def decrypt_data(data, key):
from cryptography.fernet import Fernet
decrypted_string = Fernet(key).decrypt(data)
return decrypted_string