Pycryptodome Help
Здраствуйте/ помогите новичку Пытаюсь разобраться с шифрованием файлов через python Шифруется хорошо, а при расшифровке выдаем ошибки
> Traceback (most recent call last):
File "/Users/.../decrypt.py", line 31, in <module>
walk(input('DIR: '))
File "/Users/.../decrypt.py", line 28, in walk
decrypt(path)
File "/Users/.../decrypt.py", line 16, in decrypt
session_key = cipher_rsa.decrypt(enc_session_key)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/Crypto/Cipher/PKCS1_OAEP.py", line 193, in decrypt
raise ValueError("Ciphertext with incorrect length.")
ValueError: Ciphertext with incorrect length.
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP
import os, sys
def decrypt(file):
file_in = open(file, "rb")
file_out = open(str(file[:-4]), "wb")
private_key = RSA.import_key(open("cprivate.pem").read())
enc_session_key, nonce, tag, ciphertext = \
[ file_in.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ]
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key)
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
file_out.write(data)
print(file + " decrypt!")
os.remove(file)
def walk(dir):
for name in os.listdir(dir):
path = os.path.join(dir, name)
if os.path.isfile(path):
decrypt(path)
else: walk(path)
walk(input('DIR: '))
print("---" )
Ну и сам шифратор
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP
import os, sys
def crypt(file):
f = open(file, "rb")
data = f.read(); f.close()
file_out = open(str(file)+".crp", "wb")
recipient_key = RSA.import_key(open("receiver.pem").read())
session_key = get_random_bytes(16)
cipher_rsa = PKCS1_OAEP.new(recipient_key)
enc_session_key = cipher_rsa.encrypt(session_key)
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
[ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ]
print(file + " crypt")
os.remove(file)
def walk(dir):
for name in os.listdir(dir):
path = os.path.join(dir, name)
if os.path.isfile(path): crypt(path)
else: walk(path)
walk(input("Dir: "))
print("---" )