error if the key length for x25519 isn't 32 bytes (#4584)
* error if the key length for x25519 isn't 32 bytes
* also test 33
diff --git a/src/cryptography/hazmat/primitives/asymmetric/x25519.py b/src/cryptography/hazmat/primitives/asymmetric/x25519.py
index e0329f9..f4bdf3d 100644
--- a/src/cryptography/hazmat/primitives/asymmetric/x25519.py
+++ b/src/cryptography/hazmat/primitives/asymmetric/x25519.py
@@ -21,6 +21,10 @@
"X25519 is not supported by this version of OpenSSL.",
_Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM
)
+
+ if len(data) != 32:
+ raise ValueError("An X25519 public key is 32 bytes long")
+
return backend.x25519_load_public_bytes(data)
@abc.abstractmethod
diff --git a/tests/hazmat/primitives/test_x25519.py b/tests/hazmat/primitives/test_x25519.py
index 381be20..0f83eb6 100644
--- a/tests/hazmat/primitives/test_x25519.py
+++ b/tests/hazmat/primitives/test_x25519.py
@@ -135,3 +135,10 @@
key = X25519PrivateKey.generate()
with pytest.raises(TypeError):
key.exchange(object())
+
+ def test_invalid_length_from_public_bytes(self, backend):
+ with pytest.raises(ValueError):
+ X25519PublicKey.from_public_bytes(b"a" * 31)
+
+ with pytest.raises(ValueError):
+ X25519PublicKey.from_public_bytes(b"a" * 33)