Pycryptodome RSA 解密导致大量性能降级 (RPS)

Ahm*_*ani 6 python pycryptodome

我正在测试我的 Flask 应用程序端点并在一台机器上测量性能。该特定端点有一个名为decrypt_request. 这个装饰器的实现看起来像这样:

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)
Run Code Online (Sandbox Code Playgroud)

端点看起来像这样:

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

在执行一些负载测试后,我发现平均 RPS 大约为 50(这绝对不好,但目前硬件资源受到限制)。我做的一件事是禁用装饰器,我发现 RPS 大幅增加(大约 500 RPS)。最后,我刚刚从装饰器中注释掉了公钥操作,即:我希望标头中有一个干净的会话密钥,并且只执行 AES 操作。RPS 再次以 500 RPS 左右的速度着陆。这表明公钥操作非常缓慢。Pycryptodome我正在使用的图书馆指出:

PyCryptodome 不是像 OpenSSL 这样的独立 C 库的包装器。在最大程度上,算法是用纯 Python 实现的。只有对性能极为关键的部分(例如分组密码)才作为 C 扩展实现。

我认为这是操作非常缓慢背后的实际原因。有什么方法可以使这些操作快速进行吗?

Leg*_*ooj 2

对于 PyCryptodome,不会。

PyCryptoDome 的 RSA 模块完全用 python 实现,这意味着不幸的是,您确实会遭受巨大的性能损失(pebble-rockslide 类型)。cryptography相反,如果您想要大幅提升性能,我建议使用该模块。cryptography封装了 OpenSSL 的 RSA 实现,并且比 RSA 的 PyCryptoDome 快几倍。