Как заставить Fernet принять ключ в Python?Python

Программы на Python
Ответить
Anonymous
 Как заставить Fernet принять ключ в Python?

Сообщение Anonymous »

Я пытаюсь сделать код, который автоматически устанавливает пароль и шифрует архив, после этого он шифрует ключи в AES и затем отправляет его по ftp на другой компьютер. Когда компьютер получает это, он запрашивает пароль 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 или просто давать ключ, а не aesy, но это не помогло.
Все, что я хочу, это знать, что я сделал не так :)

Подробнее здесь: https://stackoverflow.com/questions/793 ... -in-python
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»