Can some please help me I tried googling this error but could not understand why it is being raised. Can you point out the problem in my code I am fairly new to encryption this is my first time trying to use it.
session_key = cipher_rsa.decrypt(enc_session_key) , ValueError("Ciphertext with incorrect length."), ValueError: Ciphertext with incorrect length.
Encryption code
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.Random import get_random_bytes
random_generator = Random.new().read
print (random_generator,"HI")
key = RSA.generate(1024, random_generator)
print(key)
code = 'totalyundetectable' #******************important ****************
encrypted_key = key.exportKey(format='PEM', passphrase=code, pkcs=8,
protection="scryptAndAES128-CBC")
with open('C:/Users/Arnav/Documents/Project/my_private_key.bin', 'wb') as f:
f.write(encrypted_key)
with open('C:/Users/Arnav/Documents/Project/my_rsa_public.pem', 'wb') as f:
f.write(key.publickey().exportKey())
with open('C:/Users/Arnav/Documents/Project/encrypted_data.bin', 'wb') as out_file:
recipient_key = RSA.import_key(
open('C:/Users/Arnav/Documents/Project/my_rsa_public.pem').read())
session_key = get_random_bytes(16)
cipher_rsa = PKCS1_OAEP.new(recipient_key)
out_file.write(cipher_rsa.encrypt(session_key))
cipher_aes = AES.new(session_key, AES.MODE_EAX)
data = b'blah blah bl'
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
out_file.write(cipher_aes.nonce)
out_file.write(tag)
out_file.write(ciphertext)
code = 'totalyundetectable'
Decryption code
with open('C:/Users/Arnav/Documents/Project/encrypted_data.bin', 'rb') as fobj:
private_key = RSA.import_key(
open('C:/Users/Arnav/Documents/Project/my_private_key.bin','rb').read(),
passphrase=code)
enc_session_key, nonce, tag, ciphertext = [fobj.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)
print(data)