So I'm implementing RSA encryption. I'm processing input in chunks of known constant size (depends on modulus) but the last chunk might be smaller so I save its size in plaintext at the end of output file. Is that safe?
1 Answer
If you use naive RSA encryption without padding (aka “textbook RSA”), this is vulnerable to brute-force attacks and therefore not secure at all.
In general, it makes little sense to encrypt bulk data directly with RSA. The common solution is to use hybrid encryption: Generate a random symmetric key, encrypt the bulk data with this key and then encrypt the symmetric key with RSA. Since symmetric keys are relatively short (e.g., 256 bits), they easily fit into the limits of RSA encryption with padding. Variable-sized inputs will be handled by the symmetric algorithm. Stream ciphers and some block cipher modes of operation support them natively. Otherwise, there are symmetric padding schemes like the one from PKCS #7 to fill up the last block with clearly identifiable padding data.
Also note that you should never use home-grown cryptographic implementations in a production environment. Experimenting with RSA for fun or educational purposes is great, but the result will never be secure enough for protection of any serious data.