I've some clear text which I want to encrypt using RSA_PKCS_V21 (using PolarSSL library). The problem is that I need to know size of cipher text before executing the algorithm (for dynamic memory allocation purpose).
I know RSA key size & clear text length.
I also want to know the limitation on input clear text length.
Any idea?

- 6,958
- 2
- 41
- 59

- 4,772
- 10
- 60
- 87
1 Answers
Just check the RSA PKCS#1 v2.1 standard, chapter 7.2:
RSAES-PKCS1-V1_5-ENCRYPT ((n, e), M)
Input:
- (n, e) recipient's RSA public key (k denotes the length in octets of the modulus n)
- M message to be encrypted, an octet string of length mLen, where mLen <= k - 11
So the input depends on the key size. k
is that key size but in octets. So for a 1024 bit key you have 1024 / 8 - 11 = 117 bytes as maximum plain text.
Note that above is the maximum size for RSA with PKCS#1 v1.5 padding. For the newer OAEP padding the following can be found in chapter 7.1:
RSAES-OAEP-ENCRYPT ((n, e), M, L)
...
Input:
- (n, e) recipient's RSA public key (k denotes the length in octets of the RSA modulus n)
- M message to be encrypted, an octet string of length mLen, where mLen <= k - 2hLen - 2
- L optional label to be associated with the message; the default value for L, if L is not provided, is the empty string
Where hLen is the output size of the hash function used for the mask generation function. If the default SHA-1 hash function is used then the maximum size of the message is k - 42 (as the output size of SHA-1 is 20 bytes, and 2 * 20 + 2 = 42).
Normally a randomly generated secret key is encrypted instead of the message. Then the message is encrypted with that secret key. This allows almost infinitely long messages, and symmetric crypto - such as AES in CBC mode - is much faster than asymmetric crypto. This combination is called hybrid encryption.
The output size for RSA encryption or signature generation with any padding is identical to the size of the modulus in bytes (rounded upwards, of course), so for a 1024 bit key you would expect 1024 / 8 = 128 octets / bytes.
Note that the output array of the calculated size may contain leading bytes set to zero; this should be considered normal.

- 1
- 1

- 90,524
- 13
- 150
- 263
-
1This is a fairly old question, but since I just stumbled upon it while researching part of the question: I think this answer does not answer the entire question, which also asks for the expected size of the *ciphertext*, not only the limitations on the input size. i.e., given a 2048 bit RSA key, how large is the generated *ciphertext* given a specific cleartext message? This question was not addressed by your answer (or I missed it). – malexmave Oct 31 '17 at 18:31
-
1@malexmave Added another section to the answer. Forgot about it as it is kind of obvious. **Warning** the 1024 bit key size is just an example, using a 2048 bit key size or higher is strongly recommended. – Maarten Bodewes Oct 31 '17 at 18:42