我使用python包" pycryptodome"使用混合密码RSA + AES发送加密数据。
但是在加密消息之后我遇到了一个问题,这个代码将加密数据存储在名为" encrypted_data.bin"的文件中。其中包含数据+标签+ nonce。所以我想将此文件发送到另一端,以便接收方可以解密它。在我发送的每条消息中,我应该签名并将消息存储在文件中吗? 这是我的代码:
from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES, PKCS1_OAEP
def encrypt(msg):
file_out = open("encrypted_data.bin", "wb")
f = open("public_key.pem")
recipient_key = RSA.import_key(f.read())
f.close()
session_key = get_random_bytes(16)
# Encrypt the session key with the reciever's public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
file_out.write(cipher_rsa.encrypt(session_key))
# Encrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(msg)
print(ciphertext)
[ file_out.write(x) for x in (cipher_aes.nonce, tag, ciphertext) ]
#add the cipherText to the encrypted_data.bin file
file_out.close()
encrypt(b'This is my secret message')