在 python 中列出和 x?

List and x in python?

此代码用于使用 RSA 加密随机输入。我明白这一行会将输出写入一个新文件,但无法理解在代码中使用 x 和列表 ([]) 的理论。

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()

完整代码如下:

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()

感谢任何帮助!

该列表是不必要的。他们正在使用列表理解,但没有在任何地方保存列表。所以相当于

for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext):
    file_out.write(x)

甚至不需要循环,您可以简单地连接所有变量:

file_out.write(enc_session_key + cipher_aes.nonce + tag + ciphertext)