Как заставить fernet принимать введенный ключ?

Я пытаюсь сделать код, который автоматически устанавливает пароль и шифрует архив, после чего шифрует ключи в AES и отправляет его по ftp на другой компьютер. Когда компьютер получает это, он запрашивает пароль Fernet и просто пароль для архива, который был дан. Но дело в том, что, похоже, есть проблема: когда я пытаюсь ввести пароль, который был дан, Fernet говорит, что что-то не так. Код:

Код шифрования:

x = os.urandom(16)
y = Fernet.generate_key()
try:
    with pyzipper.AESZipFile(archname, 'w', compression=pyzipper.ZIP_LZMA) as zip_file:
        # Adding files to the archive
        zip_file.write(filename, arcname=os.path.basename(filename))

        # Setting the password
        zip_file.setpassword(x)  # Устанавливаем пароль
        zip_file.setencryption(pyzipper.WZ_AES, nbits=256)  # Настраиваем AES-шифрование (256 бит)

    print(f"File {filename} successfully added to the archive.")
except Exception as e:
    print(f"An error occured: {e}")
    exit(1)

# Cipher (archive)
print("Шифровка: 7/10")
try:
    cipher_suite = Fernet(y)
    with open(archname, 'rb') as file:
        file_data = file.read()
        encrypted_data = cipher_suite.encrypt(file_data)

    with open(archname, 'wb') as afile:
        afile.write(encrypted_data)

    print("Archive is successfully encrypted.")
except Exception as e:
    print(f"An error occured: {e}")
    exit(1)
# Cipher (passwords)
key = os.urandom(32)  # 32-byte key for AES-256
iv = os.urandom(16)  # 16-byte IV


cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
aesx = cipher.encryptor().update(x) + cipher.encryptor().finalize()
aesy = cipher.encryptor().update(y) + cipher.encryptor().finalize()

# Printing out them:
print("aesx:", base64.b64encode(aesx).decode())
print("aesy:", base64.b64encode(aesy).decode())
print("key:", base64.b64encode(key).decode())
print("iv:", base64.b64encode(iv).decode())

Код расшифровки:

def decrypt_data(aesx, aesy, key, iv):
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv))

    # Decoding aesx
    decryptor_for_data = cipher.decryptor()
    x = decryptor_for_data.update(aesx) + decryptor_for_data.finalize()

    # Decoding aesy
    decryptor_for_key = cipher.decryptor()
    y = decryptor_for_key.update(aesy) + decryptor_for_key.finalize()

    return x, y
aesx = base64.b64decode(input("aesx: "))
aesy = base64.b64decode(input("aesy: "))
key = base64.b64decode(input("key: "))
iv = base64.b64decode(input("iv: "))
x, y = decrypt_data(aesx, aesy, key, iv)
try:

    print("Decoded key (y):", y)
    print("Length of y:", len(y))

    y_base64 = base64.urlsafe_b64encode(y).decode('utf-8')
    print("Key (y) in URL-safe Base64 format:", y_base64)
    print("Length of key (y) in Base64 format:", len(y_base64))

    y_decoded = base64.urlsafe_b64decode(y_base64)
    print("Key (y) after decoding in bytes:", y_decoded)
    print("The length of key (y):", len(y_decoded))

    if y == y_decoded:
        print("Key wasn't modified")
    else:
        print("The key was modified!!")

    cipher_suite = Fernet(y_decoded)
    with open(archname, 'rb') as encrypted_file:
        encrypted_data = encrypted_file.read()
        decrypted_data = cipher_suite.decrypt(encrypted_data)

    with open(archname, 'wb') as decrypted_file:
        decrypted_file.write(decrypted_data)

    print("Archive was successfully decoded")
except Exception as e:
    print("An error occured: " + e)
    exit(1)

Ошибка:

Decoded key (y): b'PRBKYlmNXOmuhmJiyyZXcnwcictI9LcQ'
Length of y: 32
Key (y) in URL-safe Base64 format: UFJCS1lsbU5YT211aG1KaXl5WlhjbndjaWN0STlMY1E=
Length of key (y) in Base64 format: 44
Key (y) after decoding in bytes: b'PRBKYlmNXOmuhmJiyyZXcnwcictI9LcQ'
The length of key (y): 32
Key wasn't modified
An error occured: Fernet key must be 32 url-safe base64-encoded bytes.

Я пытался сделать много вещей, например, не кодировать его в base64 или просто дать ключ y, а не aesy, но это не помогло.

Все, что я хочу знать, что я сделал не так :)


Ответы (0 шт):