This code is used to encrypt random input using RSA. I understand this line will write the output into a new file but can't grasp the theory of using x and list ([]) in the code.
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("Message encrypted \n")
file_out.close()
The full code is as follows:
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP
key = RSA.generate(2048)
private_key = key.export_key()
file_out = open("private.pem", "wb")
file_out.write(private_key)
file_out.close()
public_key = key.publickey().export_key()
file_out = open("receiver.pem", "wb")
file_out.write(public_key)
file_out.close()
print("Keys Generated \n")
data = input("Insert message to encrypt: ").encode("utf-8")
file_out = open("encrypted_data.bin", "wb")
recipient_key = RSA.import_key(open("receiver.pem").read())
session_key = get_random_bytes(16)
# Encrypt session key (random) guna public key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
enc_session_key = cipher_rsa.encrypt(session_key)
# Encrypt data guna AES 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("Message encrypted \n")
file_out.close()
Any help is appreciated!
The list is unnecessary. They're using a list comprehension, but not saving the list anywhere. So it's equivalent to
for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext):
file_out.write(x)
There isn't even a need for the loop, you can simply concatenate all the variables:
file_out.write(enc_session_key + cipher_aes.nonce + tag + ciphertext)