繁体   English   中英

python 中的列表和 x?

[英]List and x in python?

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM