Because RSA cannot encrypt data larger than its key size, you should use Hybrid Encryption. This involves using a symmetric block cipher (like AES) for the actual data and RSA only to protect the symmetric key.
Recommended Workflow:
- Generate a random symmetric key (e.g., using
rsa.randnum.read_random_bits). - Encrypt the large file using the symmetric key and a library like
cryptography or PyCryptodome (Python-RSA does not provide AES/DES3 functionality). - Encrypt the symmetric key using the recipient's RSA public key.
- Send both the encrypted file and the encrypted symmetric key to the recipient.
Note: The VARBLOCK format is deprecated and has been removed in version 4.0 due to security vulnerabilities. Do not use it.
import rsa.randnum
# 1. Generate a random 128-bit key for AES
aes_key = rsa.randnum.read_random_bits(128)
# 2. (User must use an external library like AES to encrypt the file with aes_key)
# ...
# 3. Encrypt the AES key with RSA public key
encrypted_aes_key = rsa.encrypt(aes_key, public_rsa_key)
# 4. Send encrypted_file + encrypted_aes_key