Skip to content

Commit 8cd3b17

Browse files
authored
Fix PKey.check for some broken keys (#897)
* fix PKey.check for some broken keys RSA_check_key is documented to return 1 for valid keys. It (currently) returns 0 or -1 for invalid ones. The previous code accepted invalid keys if RSA_check_key returns -1! * add test
1 parent 675534c commit 8cd3b17

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/OpenSSL/crypto.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -345,7 +345,7 @@ def check(self):
345345
rsa = _lib.EVP_PKEY_get1_RSA(self._pkey)
346346
rsa = _ffi.gc(rsa, _lib.RSA_free)
347347
result = _lib.RSA_check_key(rsa)
348-
if result:
348+
if result == 1:
349349
return True
350350
_raise_current_error()
351351

tests/test_crypto.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -561,6 +561,12 @@ def normalize_privatekey_pem(pem):
561561
Td8GMrwKz0557OxxtKN6uVVy4ACFMqEw0zN/KJI1vxc9
562562
-----END CERTIFICATE-----"""
563563

564+
rsa_p_not_prime_pem = """
565+
-----BEGIN RSA PRIVATE KEY-----
566+
MBsCAQACAS0CAQcCAQACAQ8CAQMCAQACAQACAQA=
567+
-----END RSA PRIVATE KEY-----
568+
"""
569+
564570

565571
@pytest.fixture
566572
def x509_data():
@@ -966,6 +972,14 @@ def test_check_public_key(self):
966972
with pytest.raises(TypeError):
967973
pub.check()
968974

975+
def test_check_pr_897(self):
976+
"""
977+
`PKey.check` raises `OpenSSL.crypto.Error` if provided with broken key
978+
"""
979+
pkey = load_privatekey(FILETYPE_PEM, rsa_p_not_prime_pem)
980+
with pytest.raises(Error):
981+
pkey.check()
982+
969983

970984
def x509_name(**attrs):
971985
"""

0 commit comments

Comments
 (0)