cryptography icon indicating copy to clipboard operation
cryptography copied to clipboard

Internal openssl error with too small DH key

Open hannob opened this issue 6 months ago • 4 comments

Importing this key from some older OpenSSL tests results in an internal error: https://github.com/openssl/openssl/blob/8efc4a9c656b8b3eabeac64c54efdeb07dd42f8e/test/recipes/30-test_evp_pkey_provided/DH.priv.pem

Example code:

#!/usr/bin/python3

from cryptography.hazmat.primitives.serialization import load_pem_private_key

x=b"""-----BEGIN PRIVATE KEY-----
MCQCAQAwFwYJKoZIhvcNAQMBMAoCBQCLtF9TAgECBAYCBGZsKwY=
-----END PRIVATE KEY-----
"""

load_pem_private_key(x, password=None)

Error message:

Traceback (most recent call last):
  File "/tmp/foo.py", line 10, in <module>
    load_pem_private_key(x, password=None)
    ~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
cryptography.exceptions.InternalError: Unknown OpenSSL error. This error is commonly encountered
                    when another library is not cleaning up the OpenSSL error
                    stack. If you are using cryptography with another library
                    that uses OpenSSL try disabling it before reporting a bug.
                    Otherwise please file an issue at
                    https://github.com/pyca/cryptography/issues with
                    information on how to reproduce this. (error:0280007E:Diffie-Hellman routines:generate_key:modulus too small:../openssl-3.5.0/crypto/dh/dh_key.c:287:)

hannob avatar Jun 07 '25 08:06 hannob

Additional info: it appears this only happens with rather recent versions of python cryptography. I'm seeing this error on a system with version 45.0.3, but not on a system with version 44.0.3.

hannob avatar Jun 07 '25 08:06 hannob

It's weird that generate_key is in the error, since you're obviously just parsing.

I assume this is a consequence of the change in how we parse private keys, but I have no idea why.

alex avatar Jun 07 '25 12:06 alex

Ahh, because DH_generate_key is the API used to recompute the public key as part of key loading... this is so dumb.

alex avatar Jun 07 '25 12:06 alex

Hmm, but the relevant OpenSSL code path also appears to call DH_generate_key.

alex avatar Jun 10 '25 22:06 alex