How to Encrypt Large Data
Encrypt files or data larger than the RSA key size using hybrid (envelope) encryption.
Problem
You need to encrypt a large file but RSA can only encrypt a few hundred bytes, and you want the security of public-key encryption.
Prerequisites
- Understanding of AES and RSA
- Knowledge of hybrid encryption
Steps
-
1. Generate a random symmetric key
Generate a fresh random AES key (256 bits). This key will encrypt the large data. It is called the session key or data encryption key (DEK). A new DEK should be generated for each file.
Inputrandom AES-256 keyOutput32 random bytes -
2. Encrypt the data with AES
Encrypt the large file using AES-GCM with the session key and a fresh IV. AES can handle data of any size efficiently. Store the IV and authentication tag with the ciphertext.
Inputlarge file + AES keyOutputAES ciphertext + IV + tag -
3. Encrypt the session key with RSA
Encrypt the small AES session key using the recipient's RSA public key with OAEP padding. Store the RSA-encrypted session key alongside the AES ciphertext. The recipient decrypts the session key with their private key, then decrypts the file with AES.
InputAES key + RSA public keyOutputRSA-encrypted session key
Expected result
A hybrid-encrypted package: large data encrypted with AES, and the AES key encrypted with RSA, combining the strengths of both.
Common errors
- Trying to encrypt the large file directly with RSA
- RSA can only encrypt data up to key_size - padding bytes. Use hybrid encryption for anything larger.
- Reusing the AES session key across files
- Generate a fresh session key for each encryption. Reusing it with the same IV breaks security.
Troubleshooting
- If the RSA step fails with 'message too long', the session key exceeds the RSA limit. This should not happen with a 32-byte key and 2048+ bit RSA.
- Verify the GCM tag after AES decryption before using the data.
Security limits
- Hybrid encryption is the standard for TLS, PGP, and S/MIME. It provides public-key security with symmetric-key performance.
- All encryption is local; no keys or data are transmitted.
Related tools
Related tasks
Ready to run it?