aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSimo Sorce <simo@redhat.com>2015-04-30 14:06:47 -0400
committerSimo Sorce <simo@redhat.com>2015-10-17 11:58:07 -0400
commit9aaeee0dc62189204f38097c815a0913fabe006c (patch)
tree37621d2d6a20898d9665520a30ecb7a68c0db30e
parent7a0ed4a7e9443a0506ae5373a8e5cd1ce3539e97 (diff)
downloadcryptography-9aaeee0dc62189204f38097c815a0913fabe006c.tar.gz
cryptography-9aaeee0dc62189204f38097c815a0913fabe006c.tar.bz2
cryptography-9aaeee0dc62189204f38097c815a0913fabe006c.zip
Add an Elliptic Curve Key Exchange Algorithm(ECDH)
The ECDH Key Exchange algorithm as standardized in NIST publication 800-56A Revision 2 Includes tests with vectors from NIST. Signed-off-by: Simo Sorce <simo@redhat.com>
-rw-r--r--docs/hazmat/primitives/asymmetric/ec.rst44
-rw-r--r--src/cryptography/exceptions.py1
-rw-r--r--src/cryptography/hazmat/backends/interfaces.py6
-rw-r--r--src/cryptography/hazmat/backends/multibackend.py6
-rw-r--r--src/cryptography/hazmat/backends/openssl/backend.py20
-rw-r--r--src/cryptography/hazmat/primitives/asymmetric/ec.py25
-rw-r--r--tests/hazmat/backends/test_multibackend.py12
-rw-r--r--tests/hazmat/backends/test_openssl.py14
-rw-r--r--tests/hazmat/primitives/test_ec.py94
9 files changed, 219 insertions, 3 deletions
diff --git a/docs/hazmat/primitives/asymmetric/ec.rst b/docs/hazmat/primitives/asymmetric/ec.rst
index 6356c278..910ce5d8 100644
--- a/docs/hazmat/primitives/asymmetric/ec.rst
+++ b/docs/hazmat/primitives/asymmetric/ec.rst
@@ -122,6 +122,48 @@ Elliptic Curve Signature Algorithms
:returns: A new instance of a :class:`EllipticCurvePublicKey`
provider.
+Elliptic Curve Key Exchange algorithm
+-------------------------------------
+
+.. class:: ECDH(private_key)
+
+ .. versionadded:: 1.1
+
+ The ECDH Key Exchange algorithm first standardized in NIST publication
+ `800-56A`_, and later in `800-56Ar2`_.
+
+ :param private_key: An instance of :class:`EllipticCurvePrivateKey`.
+
+ .. doctest::
+
+ >>> from cryptography.hazmat.backends import default_backend
+ >>> from cryptography.hazmat.primitives.asymmetric import ec
+ >>> private_key = ec.generate_private_key(
+ ... ec.SECP384R1(), default_backend()
+ ... )
+ >>> peer_public_key = ec.generate_private_key(
+ ... ec.SECP384R1(), default_backend()
+ ... ).public_key()
+ >>> ecdh = ec.ECDH(private_key)
+ >>> sharedkey = ecdh.compute_key(peer_public_key)
+
+ .. attribute:: private_key
+
+ :type: :class:`EllipticCurvePrivateKey`
+
+ The private key associated to this object
+
+ .. method:: public_key()
+
+ The public key associated to the object's private key.
+
+ .. method:: compute_key(peer_public_key)
+
+ :param peer_public_key: A :class:`EllipticCurvePublicKey` object.
+
+ :returns: A ``bytes`` object containing the computed key.
+
+
Elliptic Curves
---------------
@@ -419,6 +461,8 @@ Key Interfaces
.. _`FIPS 186-3`: http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
.. _`FIPS 186-4`: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
+.. _`800-56A`: http://csrc.nist.gov/publications/nistpubs/800-56A/SP800-56A_Revision1_Mar08-2007.pdf
+.. _`800-56Ar2`: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Ar2.pdf
.. _`some concern`: https://crypto.stackexchange.com/questions/10263/should-we-trust-the-nist-recommended-ecc-parameters
.. _`less than 224 bits`: http://www.ecrypt.eu.org/ecrypt2/documents/D.SPA.20.pdf
.. _`elliptic curve diffie-hellman is faster than diffie-hellman`: http://digitalcommons.unl.edu/cgi/viewcontent.cgi?article=1100&context=cseconfwork
diff --git a/src/cryptography/exceptions.py b/src/cryptography/exceptions.py
index 29be22be..3bf8a75b 100644
--- a/src/cryptography/exceptions.py
+++ b/src/cryptography/exceptions.py
@@ -20,6 +20,7 @@ class _Reasons(Enum):
UNSUPPORTED_ELLIPTIC_CURVE = 6
UNSUPPORTED_SERIALIZATION = 7
UNSUPPORTED_X509 = 8
+ UNSUPPORTED_EXCHANGE_ALGORITHM = 9
class UnsupportedAlgorithm(Exception):
diff --git a/src/cryptography/hazmat/backends/interfaces.py b/src/cryptography/hazmat/backends/interfaces.py
index a43621a7..faa0b313 100644
--- a/src/cryptography/hazmat/backends/interfaces.py
+++ b/src/cryptography/hazmat/backends/interfaces.py
@@ -215,6 +215,12 @@ class EllipticCurveBackend(object):
Return an EllipticCurvePublicKey provider using the given numbers.
"""
+ @abc.abstractmethod
+ def elliptic_curve_exchange_algorithm_supported(self):
+ """
+ Returns whether the exchange algorithm is supported by this backend.
+ """
+
@six.add_metaclass(abc.ABCMeta)
class PEMSerializationBackend(object):
diff --git a/src/cryptography/hazmat/backends/multibackend.py b/src/cryptography/hazmat/backends/multibackend.py
index 9db32aa5..77a45ccd 100644
--- a/src/cryptography/hazmat/backends/multibackend.py
+++ b/src/cryptography/hazmat/backends/multibackend.py
@@ -271,6 +271,12 @@ class MultiBackend(object):
_Reasons.UNSUPPORTED_ELLIPTIC_CURVE
)
+ def elliptic_curve_exchange_algorithm_supported(self):
+ return any(
+ b.elliptic_curve_exchange_algorithm_supported()
+ for b in self._filtered_backends(EllipticCurveBackend)
+ )
+
def load_pem_private_key(self, data, password):
for b in self._filtered_backends(PEMSerializationBackend):
return b.load_pem_private_key(data, password)
diff --git a/src/cryptography/hazmat/backends/openssl/backend.py b/src/cryptography/hazmat/backends/openssl/backend.py
index 0d3b3dd4..d82f3834 100644
--- a/src/cryptography/hazmat/backends/openssl/backend.py
+++ b/src/cryptography/hazmat/backends/openssl/backend.py
@@ -1671,6 +1671,26 @@ class Backend(object):
return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey)
+ def elliptic_curve_exchange_algorithm_supported(self):
+ return (self._lib.Cryptography_HAS_EC == 1 and
+ self._lib.Cryptography_HAS_ECDH == 1)
+
+ def ecdh_compute_key(self, private_key, peer_public_key):
+ pri_key = private_key._ec_key
+ pub_key = peer_public_key._ec_key
+
+ group = self._lib.EC_KEY_get0_group(pri_key)
+ z_len = (self._lib.EC_GROUP_get_degree(group) + 7) // 8
+ self.openssl_assert(z_len > 0)
+ z_buf = self._ffi.new("uint8_t[]", z_len)
+ peer_key = self._lib.EC_KEY_get0_public_key(pub_key)
+
+ r = self._lib.ECDH_compute_key(z_buf, z_len,
+ peer_key, pri_key,
+ self._ffi.NULL)
+ self.openssl_assert(r > 0)
+ return self._ffi.buffer(z_buf)[:z_len]
+
def _ec_cdata_to_evp_pkey(self, ec_cdata):
evp_pkey = self._lib.EVP_PKEY_new()
self.openssl_assert(evp_pkey != self._ffi.NULL)
diff --git a/src/cryptography/hazmat/primitives/asymmetric/ec.py b/src/cryptography/hazmat/primitives/asymmetric/ec.py
index f1d39eed..978a7c41 100644
--- a/src/cryptography/hazmat/primitives/asymmetric/ec.py
+++ b/src/cryptography/hazmat/primitives/asymmetric/ec.py
@@ -8,6 +8,7 @@ import abc
import six
+from cryptography import exceptions
from cryptography import utils
@@ -302,3 +303,27 @@ class EllipticCurvePrivateNumbers(object):
def __ne__(self, other):
return not self == other
+
+
+class ECDH(object):
+ def __init__(self, private_key):
+ if not isinstance(private_key, EllipticCurvePrivateKey):
+ raise TypeError("Private Key must be a EllipticCurvePrivateKey")
+ self._private_key = private_key
+ self._backend = private_key._backend
+ if not self._backend.elliptic_curve_exchange_algorithm_supported():
+ raise exceptions.UnsupportedAlgorithm(
+ "This backend does not support the ECDH algorithm.",
+ exceptions._Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM
+ )
+
+ private_key = utils.read_only_property("_private_key")
+
+ def public_key(self):
+ return self._private_key.public_key()
+
+ def compute_key(self, peer_public_key):
+ if not isinstance(peer_public_key, EllipticCurvePublicKey):
+ raise TypeError("Peer Public Key must be a EllipticCurvePublicKey")
+ return self._backend.ecdh_compute_key(self._private_key,
+ peer_public_key)
diff --git a/tests/hazmat/backends/test_multibackend.py b/tests/hazmat/backends/test_multibackend.py
index 4d17cdb0..57aa7f44 100644
--- a/tests/hazmat/backends/test_multibackend.py
+++ b/tests/hazmat/backends/test_multibackend.py
@@ -138,8 +138,9 @@ class DummyCMACBackend(object):
@utils.register_interface(EllipticCurveBackend)
class DummyEllipticCurveBackend(object):
- def __init__(self, supported_curves):
+ def __init__(self, supported_curves, exchange_supported):
self._curves = supported_curves
+ self.exchange_supported = exchange_supported
def elliptic_curve_supported(self, curve):
return any(
@@ -170,6 +171,9 @@ class DummyEllipticCurveBackend(object):
if not self.elliptic_curve_supported(numbers.curve):
raise UnsupportedAlgorithm(_Reasons.UNSUPPORTED_ELLIPTIC_CURVE)
+ def elliptic_curve_exchange_algorithm_supported(self):
+ return self.exchange_supported
+
@utils.register_interface(PEMSerializationBackend)
class DummyPEMSerializationBackend(object):
@@ -400,7 +404,7 @@ class TestMultiBackend(object):
backend = MultiBackend([
DummyEllipticCurveBackend([
ec.SECT283K1
- ])
+ ], True)
])
assert backend.elliptic_curve_supported(ec.SECT283K1()) is True
@@ -462,6 +466,10 @@ class TestMultiBackend(object):
)
)
+ assert backend.elliptic_curve_exchange_algorithm_supported() is True
+ backend2 = MultiBackend([DummyEllipticCurveBackend([], False)])
+ assert backend2.elliptic_curve_exchange_algorithm_supported() is False
+
def test_pem_serialization_backend(self):
backend = MultiBackend([DummyPEMSerializationBackend()])
diff --git a/tests/hazmat/backends/test_openssl.py b/tests/hazmat/backends/test_openssl.py
index 8fd0d711..13162046 100644
--- a/tests/hazmat/backends/test_openssl.py
+++ b/tests/hazmat/backends/test_openssl.py
@@ -534,6 +534,11 @@ class DummyLibrary(object):
Cryptography_HAS_EC = 0
+class DummyLibraryECDH(object):
+ Cryptography_HAS_EC = 1
+ Cryptography_HAS_ECDH = 0
+
+
class TestOpenSSLEllipticCurve(object):
def test_elliptic_curve_supported(self, monkeypatch):
monkeypatch.setattr(backend, "_lib", DummyLibrary())
@@ -551,6 +556,15 @@ class TestOpenSSLEllipticCurve(object):
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_ELLIPTIC_CURVE):
_sn_to_elliptic_curve(backend, b"fake")
+ def test_elliptic_curve_exchange_algorithm_supported(self, monkeypatch):
+ monkeypatch.setattr(backend, "_lib", DummyLibrary())
+
+ assert backend.elliptic_curve_exchange_algorithm_supported() is False
+
+ monkeypatch.setattr(backend, "_lib", DummyLibraryECDH())
+
+ assert backend.elliptic_curve_exchange_algorithm_supported() is False
+
@pytest.mark.requires_backend_interface(interface=RSABackend)
class TestRSAPEMSerialization(object):
diff --git a/tests/hazmat/primitives/test_ec.py b/tests/hazmat/primitives/test_ec.py
index 5467464a..c3a99e5d 100644
--- a/tests/hazmat/primitives/test_ec.py
+++ b/tests/hazmat/primitives/test_ec.py
@@ -7,6 +7,8 @@ from __future__ import absolute_import, division, print_function
import itertools
import os
+from binascii import hexlify
+
import pytest
from cryptography import exceptions, utils
@@ -21,7 +23,8 @@ from cryptography.hazmat.primitives.asymmetric.utils import (
from ...utils import (
load_fips_ecdsa_key_pair_vectors, load_fips_ecdsa_signing_vectors,
- load_vectors_from_file, raises_unsupported_algorithm
+ load_kasvs_ecdh_vectors, load_vectors_from_file,
+ raises_unsupported_algorithm
)
_HASH_TYPES = {
@@ -54,6 +57,15 @@ def _skip_curve_unsupported(backend, curve):
)
+def _skip_exchange_algorithm_unsupported(backend):
+ if not backend.elliptic_curve_exchange_algorithm_supported():
+ pytest.skip(
+ "Exchange algorithm is not supported by this backend {0}".format(
+ backend
+ )
+ )
+
+
@utils.register_interface(ec.EllipticCurve)
class DummyCurve(object):
name = "dummy-curve"
@@ -749,3 +761,83 @@ class TestECDSAVerification(object):
public_key = key.public_key()
with pytest.raises(TypeError):
public_key.verifier(1234, ec.ECDSA(hashes.SHA256()))
+
+
+class DummyECDHBackend(object):
+ @classmethod
+ def elliptic_curve_exchange_algorithm_supported(cls):
+ return False
+
+
+@pytest.mark.requires_backend_interface(interface=EllipticCurveBackend)
+class TestECDHVectors(object):
+
+ def test_unsupported_ecdh_arguments(self, backend):
+ with pytest.raises(TypeError):
+ ec.ECDH(None)
+ curve = ec.SECP521R1
+ _skip_curve_unsupported(backend, curve)
+ prikey = ec.generate_private_key(curve, backend)
+ ecdh = ec.ECDH(prikey)
+ ecdh.compute_key(ecdh.public_key())
+ with pytest.raises(TypeError):
+ ecdh.compute_key(None)
+ with pytest.raises(exceptions.UnsupportedAlgorithm):
+ prikey._backend = DummyECDHBackend()
+ ecdh = ec.ECDH(prikey)
+ _skip_exchange_algorithm_unsupported(DummyECDHBackend())
+
+ def key_exchange(self, backend, vector):
+ key_numbers = vector['IUT']
+ peer_numbers = vector['CAVS']
+
+ prikey = ec.EllipticCurvePrivateNumbers(
+ key_numbers['d'],
+ ec.EllipticCurvePublicNumbers(
+ key_numbers['x'],
+ key_numbers['y'],
+ ec._CURVE_TYPES[vector['curve']]()
+ )
+ ).private_key(backend)
+
+ peerkey = ec.EllipticCurvePrivateNumbers(
+ peer_numbers['d'],
+ ec.EllipticCurvePublicNumbers(
+ peer_numbers['x'],
+ peer_numbers['y'],
+ ec._CURVE_TYPES[vector['curve']]()
+ )
+ ).private_key(backend)
+ peerpubkey = peerkey.public_key()
+
+ ecdh = ec.ECDH(prikey)
+ z = ecdh.compute_key(peerpubkey)
+
+ return int(hexlify(z).decode('ascii'), 16)
+
+ @pytest.mark.parametrize(
+ "vector",
+ load_vectors_from_file(
+ os.path.join(
+ "asymmetric", "ECDH",
+ "KASValidityTest_ECCStaticUnified_NOKC_ZZOnly_init.fax"),
+ load_kasvs_ecdh_vectors
+ )
+ )
+ def test_key_exchange_with_vectors(self, backend, vector):
+ _skip_curve_unsupported(backend, ec._CURVE_TYPES[vector['curve']])
+ _skip_exchange_algorithm_unsupported(backend)
+
+ try:
+ z = self.key_exchange(backend, vector)
+ except ValueError:
+ assert vector['fail'] is True
+
+ if vector['fail']:
+ # Errno 7 denotes a changed private key. Errno 8 denotes a changed
+ # shared key. Both these errors will not cause a failure in the
+ # exchange but should lead to a non-matching derived shared key.
+ if vector['errno'] in [7, 8]:
+ assert z != vector['Z']
+ else:
+ assert z == vector['Z']