Search code examples
python-3.xlarge-filespycrypto

How to RSA encode large data in python 3


I try to encrypt data with python3.x using pycrypto library. It works fine for short data but not for long arrays. How can I encrypt long data? Should I write a wrapper to split data smaller chunks? Or is there any other crypto library that can handle long data?

from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
publickey = key.publickey() 

"""
Shorter (128 bytes)
"""
msg = b'abcd'*32
print(msg)          # b'abcdabcdabcd...
enc=publickey.encrypt(msg, 32)
print(enc)          # Depends on key. Ex.: (b"hd\n\xbb\xe4\x8b...
dec=key.decrypt(enc)
print(dec)          # b'abcdabcdabcdabcda...

if msg==dec:        # TRUE
    print('TRUE')
else:
    print('FALSE')

"""
LONGER (132 bytes)
"""
msg = b'abcd'*33
print(msg)          # b'abcdabcdabcd...
enc=publickey.encrypt(msg, 32)
print(enc)          # Depends on key. Ex.: (b'\xa2J1;\xd4`\xc5i\x...   
dec=key.decrypt(enc)
print(dec)          # Depends on key. Ex.: b'|*\xb85\\B\\r2\xea\...   

if msg==dec:        # FALSE
    print('TRUE')
else:
    print('FALSE')

Solution

  • This is not the exact answer for the original question but this solved my problem: Based on https://security.stackexchange.com/a/10953

    ... public-key cryptography is expensive for large messages; the public key algorithm is only used to encrypt the symmetric key and to sign a digest of the file.

    So it is not recommended to encrypt large data/files using RSA. Use AES instead:

    from Crypto.Cipher import AES
    obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
    message = "The answer is no"*32
    ciphertext = obj.encrypt(message)
    print(ciphertext)
    # '\xd6\x83\x8dd!VT\x92\xaa`A\x05\xe0\x9b\x8b\xf1'
    obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
    print(obj2.decrypt(ciphertext))
    # 'The answer is no'