Search code examples
pythonpycryptodome

Pycryptodome RSA decryption causes massive performance downgrade (RPS)


I am testing my flask application endpoint and measuring the performance on a single machine. That particular endpoint has a decorator called decrypt_request. The implementation of this decorator looks like this:

1. Read X-Session-Key header (encrypted by public key)
2. Import RSA key
3. Create a cryptor and decrypt the session key (RSA)
4. Read data from the request body (which is encrypted by the above session key)
5. Decrypt the request body using the session key (AES)

The endpoint looks something like that:

@app.route('/test', methods=['POST'])
@decrypt_request
def view_function():
    # do something here

Upon performing some load test I found out that the average RPS lands around 50 (which is definitely not good but the hardware resources are restricted for now). One thing I did was to disable the decorator and I found a huge increase in the RPS (lands around ~500 RPS). Finally I just commented out the public key operations from the decorator i-e: I expect a clean session key in the header and just do the AES operation. Again the RPS lands the same around 500 RPS. This is identified that the public key operations are very slow. The Pycryptodome library that I am using states:

PyCryptodome is not a wrapper to a separate C library like OpenSSL. To the largest possible extent, algorithms are implemented in pure Python. Only the pieces that are extremely critical to performance (e.g. block ciphers) are implemented as C extensions.

And I assume this is the actual reason behind the very slow operations. Is there any way to make these operations blazing fast?


Solution

  • With PyCryptodome, no.

    PyCryptoDome's RSA module is implemented entirely in python, meaning that you do, unfortunately, get a huge performance loss (The pebble-rockslide type). Instead, I'd recommend using the cryptography module, if you want a large performance boost. cryptography wraps OpenSSL's RSA implementation, and is several times faster than PyCryptoDome for RSA.