PaxPrz
PaxPrz

Reputation: 1928

How to encrypt message longer than 53 bytes using RSA encryption?

Hey guys I am using rsa module import rsa in python for encrypting message longer than 53 bytes. But seems like the message length limit for rsa.encrypt(message, private_key) is only 53 bytes.

>>> rsa.encrypt(b'A'*53, private_key)
b"(\xe9\xbf\xcc?\x18'\xb4Q@\xce\xb5=\xce#\x91\xb3\xe2+QT\\d\xe4\xaf\x07\xdb\x01\xe2\x83\xc6-\xfe\x03\xa5]\x9a\xad\x90\xb1L\xab\xed\xf3zWw\xccM\xa4.Yw!{\xf4\x08\x95\x9ex7\xbb\x9b\xff"

But for length greater than 53:

>>> rsa.encrypt(b'A'*54, private_key)
Traceback (most recent call last):
  File "<pyshell#216>", line 1, in <module>
    rsa.encrypt(b' '*54, s_pub)
  File "/usr/local/lib/python3.7/dist-packages/rsa/pkcs1.py", line 172, in encrypt
    padded = _pad_for_encryption(message, keylength)
  File "/usr/local/lib/python3.7/dist-packages/rsa/pkcs1.py", line 89, in _pad_for_encryption
    ' space for %i' % (msglength, max_msglength))
OverflowError: 54 bytes needed for message, but there is only space for 53

Is there any way I could encrypt message longer than that?

Upvotes: 0

Views: 2676

Answers (1)

bartonjs
bartonjs

Reputation: 33098

Use a bigger key.

RSA PKCS#1 encryption is limited to ((KeySize/8) - 11) bytes of payload. Based on your numbers you are using RSA-512 (which is “too easy” to break, you should really be using 1024 or 2048-bit RSA).

The most common use for RSA encryption is to encrypt an AES key, and then send the encrypted AES key plus the AES-encrypted message: a scheme known as hybrid encryption. Since AES keys are small (16, 24, or 32 bytes) even small RSA can transport them.

Upvotes: 3

Related Questions