diff options
| -rw-r--r-- | cryptography/hazmat/backends/interfaces.py | 6 | ||||
| -rw-r--r-- | cryptography/hazmat/backends/openssl/backend.py | 81 | ||||
| -rw-r--r-- | cryptography/hazmat/bindings/openssl/err.py | 2 | ||||
| -rw-r--r-- | cryptography/hazmat/primitives/asymmetric/rsa.py | 9 | ||||
| -rw-r--r-- | dev-requirements.txt | 3 | ||||
| -rw-r--r-- | docs/hazmat/backends/interfaces.rst | 12 | ||||
| -rw-r--r-- | docs/hazmat/primitives/asymmetric/padding.rst | 6 | ||||
| -rw-r--r-- | docs/hazmat/primitives/asymmetric/rsa.rst | 34 | ||||
| -rw-r--r-- | docs/hazmat/primitives/interfaces.rst | 18 | ||||
| -rw-r--r-- | docs/installation.rst | 17 | ||||
| -rw-r--r-- | setup.py | 2 | ||||
| -rw-r--r-- | tests/hazmat/backends/test_openssl.py | 4 | ||||
| -rw-r--r-- | tests/hazmat/primitives/test_dsa.py | 2 | ||||
| -rw-r--r-- | tests/hazmat/primitives/test_pbkdf2hmac.py | 1 | ||||
| -rw-r--r-- | tests/hazmat/primitives/test_rsa.py | 95 | ||||
| -rw-r--r-- | tests/utils.py | 2 | ||||
| -rw-r--r-- | tox.ini | 7 | ||||
| -rw-r--r-- | vectors/cryptography_vectors/__init__.py | 4 | ||||
| -rw-r--r-- | vectors/setup.py | 2 |
19 files changed, 289 insertions, 18 deletions
diff --git a/cryptography/hazmat/backends/interfaces.py b/cryptography/hazmat/backends/interfaces.py index 92413d8c..677f4c67 100644 --- a/cryptography/hazmat/backends/interfaces.py +++ b/cryptography/hazmat/backends/interfaces.py @@ -117,6 +117,12 @@ class RSABackend(object): Return True if the hash algorithm is supported for MGF1 in PSS. """ + @abc.abstractmethod + def decrypt_rsa(self, private_key, ciphertext, padding): + """ + Returns decrypted bytes. + """ + @six.add_metaclass(abc.ABCMeta) class DSABackend(object): diff --git a/cryptography/hazmat/backends/openssl/backend.py b/cryptography/hazmat/backends/openssl/backend.py index 86fa704b..5e13bfc1 100644 --- a/cryptography/hazmat/backends/openssl/backend.py +++ b/cryptography/hazmat/backends/openssl/backend.py @@ -473,6 +473,87 @@ class Backend(object): y=self._bn_to_int(ctx.pub_key) ) + def decrypt_rsa(self, private_key, ciphertext, padding): + if isinstance(padding, PKCS1v15): + padding_enum = self._lib.RSA_PKCS1_PADDING + else: + raise UnsupportedAlgorithm( + "{0} is not supported by this backend".format( + padding.name + ), + _Reasons.UNSUPPORTED_PADDING + ) + + key_size_bytes = int(math.ceil(private_key.key_size / 8.0)) + if key_size_bytes < len(ciphertext): + raise ValueError("Ciphertext too large for key size") + + if self._lib.Cryptography_HAS_PKEY_CTX: + return self._decrypt_rsa_pkey_ctx(private_key, ciphertext, + padding_enum) + else: + return self._decrypt_rsa_098(private_key, ciphertext, padding_enum) + + def _decrypt_rsa_pkey_ctx(self, private_key, ciphertext, padding_enum): + evp_pkey = self._rsa_private_key_to_evp_pkey(private_key) + pkey_ctx = self._lib.EVP_PKEY_CTX_new( + evp_pkey, self._ffi.NULL + ) + assert pkey_ctx != self._ffi.NULL + pkey_ctx = self._ffi.gc(pkey_ctx, self._lib.EVP_PKEY_CTX_free) + res = self._lib.EVP_PKEY_decrypt_init(pkey_ctx) + assert res == 1 + res = self._lib.EVP_PKEY_CTX_set_rsa_padding( + pkey_ctx, padding_enum) + assert res > 0 + buf_size = self._lib.EVP_PKEY_size(evp_pkey) + assert buf_size > 0 + outlen = self._ffi.new("size_t *", buf_size) + buf = self._ffi.new("char[]", buf_size) + res = self._lib.Cryptography_EVP_PKEY_decrypt( + pkey_ctx, + buf, + outlen, + ciphertext, + len(ciphertext) + ) + if res <= 0: + errors = self._consume_errors() + assert errors + assert errors[0].lib == self._lib.ERR_LIB_RSA + assert ( + errors[0].reason == self._lib.RSA_R_BLOCK_TYPE_IS_NOT_01 or + errors[0].reason == self._lib.RSA_R_BLOCK_TYPE_IS_NOT_02 + ) + raise ValueError("Decryption failed") + + return self._ffi.buffer(buf)[:outlen[0]] + + def _decrypt_rsa_098(self, private_key, ciphertext, padding_enum): + rsa_cdata = self._rsa_cdata_from_private_key(private_key) + rsa_cdata = self._ffi.gc(rsa_cdata, self._lib.RSA_free) + key_size = self._lib.RSA_size(rsa_cdata) + assert key_size > 0 + buf = self._ffi.new("unsigned char[]", key_size) + res = self._lib.RSA_private_decrypt( + len(ciphertext), + ciphertext, + buf, + rsa_cdata, + padding_enum + ) + if res < 0: + errors = self._consume_errors() + assert errors + assert errors[0].lib == self._lib.ERR_LIB_RSA + assert ( + errors[0].reason == self._lib.RSA_R_BLOCK_TYPE_IS_NOT_01 or + errors[0].reason == self._lib.RSA_R_BLOCK_TYPE_IS_NOT_02 + ) + raise ValueError("Decryption failed") + + return self._ffi.buffer(buf)[:res] + class GetCipherByName(object): def __init__(self, fmt): diff --git a/cryptography/hazmat/bindings/openssl/err.py b/cryptography/hazmat/bindings/openssl/err.py index f51393aa..c08c880c 100644 --- a/cryptography/hazmat/bindings/openssl/err.py +++ b/cryptography/hazmat/bindings/openssl/err.py @@ -216,6 +216,8 @@ static const int PEM_R_UNSUPPORTED_ENCRYPTION; static const int RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE; static const int RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY; +static const int RSA_R_BLOCK_TYPE_IS_NOT_01; +static const int RSA_R_BLOCK_TYPE_IS_NOT_02; """ FUNCTIONS = """ diff --git a/cryptography/hazmat/primitives/asymmetric/rsa.py b/cryptography/hazmat/primitives/asymmetric/rsa.py index 5b15350a..cffd4e98 100644 --- a/cryptography/hazmat/primitives/asymmetric/rsa.py +++ b/cryptography/hazmat/primitives/asymmetric/rsa.py @@ -189,6 +189,15 @@ class RSAPrivateKey(object): return backend.create_rsa_signature_ctx(self, padding, algorithm) + def decrypt(self, ciphertext, padding, backend): + if not isinstance(backend, RSABackend): + raise UnsupportedAlgorithm( + "Backend object does not implement RSABackend", + _Reasons.BACKEND_MISSING_INTERFACE + ) + + return backend.decrypt_rsa(self, ciphertext, padding) + @property def key_size(self): return utils.bit_length(self.modulus) diff --git a/dev-requirements.txt b/dev-requirements.txt index 9dabba1b..092b9914 100644 --- a/dev-requirements.txt +++ b/dev-requirements.txt @@ -1,5 +1,6 @@ coverage flake8 +flake8-import-order invoke iso8601 pep8-naming @@ -7,8 +8,8 @@ pretend pytest requests sphinx -sphinxcontrib-spelling sphinx_rtd_theme +sphinxcontrib-spelling tox twine -e . diff --git a/docs/hazmat/backends/interfaces.rst b/docs/hazmat/backends/interfaces.rst index 394d060b..71cd4564 100644 --- a/docs/hazmat/backends/interfaces.rst +++ b/docs/hazmat/backends/interfaces.rst @@ -263,6 +263,18 @@ A specific ``backend`` may provide one or more of these interfaces. :returns: ``True`` if the specified ``algorithm`` is supported by this backend, otherwise ``False``. + .. method:: decrypt_rsa(private_key, ciphertext, padding) + + :param private_key: An instance of an + :class:`~cryptography.hazmat.primitives.interfaces.RSAPrivateKey` + provider. + + :param bytes ciphertext: The ciphertext to decrypt. + + :param padding: An instance of an + :class:`~cryptography.hazmat.primitives.interfaces.AsymmetricPadding` + provider. + .. class:: OpenSSLSerializationBackend diff --git a/docs/hazmat/primitives/asymmetric/padding.rst b/docs/hazmat/primitives/asymmetric/padding.rst index 89af7eaa..f33ca4e2 100644 --- a/docs/hazmat/primitives/asymmetric/padding.rst +++ b/docs/hazmat/primitives/asymmetric/padding.rst @@ -19,7 +19,8 @@ Padding PSS (Probabilistic Signature Scheme) is a signature scheme defined in :rfc:`3447`. It is more complex than PKCS1 but possesses a `security proof`_. - This is the `recommended padding algorithm`_ for RSA signatures. + This is the `recommended padding algorithm`_ for RSA signatures. It cannot + be used with RSA encryption. :param mgf: A mask generation function object. At this time the only supported MGF is :class:`MGF1`. @@ -37,7 +38,8 @@ Padding .. versionadded:: 0.3 PKCS1 v1.5 (also known as simply PKCS1) is a simple padding scheme - developed for use with RSA keys. It is defined in :rfc:`3447`. + developed for use with RSA keys. It is defined in :rfc:`3447`. This padding + can be used for signing and encryption. Mask generation functions ~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/hazmat/primitives/asymmetric/rsa.rst b/docs/hazmat/primitives/asymmetric/rsa.rst index c9de2831..c282d9ef 100644 --- a/docs/hazmat/primitives/asymmetric/rsa.rst +++ b/docs/hazmat/primitives/asymmetric/rsa.rst @@ -116,6 +116,36 @@ RSA :raises ValueError: This is raised when the chosen hash algorithm is too large for the key size. + .. method:: decrypt(ciphertext, padding, backend) + + .. versionadded:: 0.4 + + Decrypt data that was encrypted with the public key. + + :param bytes ciphertext: The ciphertext to decrypt. + + :param padding: An instance of a + :class:`~cryptography.hazmat.primitives.interfaces.AsymmetricPadding` + provider. + + :param backend: A + :class:`~cryptography.hazmat.backends.interfaces.RSABackend` + provider. + + :return bytes: Decrypted data. + + :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if + the provided ``backend`` does not implement + :class:`~cryptography.hazmat.backends.interfaces.RSABackend` or if + the backend does not support the chosen hash or padding algorithm. + + :raises TypeError: This is raised when the padding is not an + :class:`~cryptography.hazmat.primitives.interfaces.AsymmetricPadding` + provider. + + :raises ValueError: This is raised when decryption fails or the chosen + hash algorithm is too large for the key size. + .. class:: RSAPublicKey(public_exponent, modulus) @@ -221,7 +251,7 @@ If you are trying to load RSA private keys yourself you may find that not all parameters required by ``RSAPrivateKey`` are available. In particular the `Chinese Remainder Theorem`_ (CRT) values ``dmp1``, ``dmq1``, ``iqmp`` may be missing or present in a different form. For example `OpenPGP`_ does not include -the ``iqmp``, ``dmp1`` or ``dmq1`` parameters. +the ``iqmp``, ``dmp1`` or ``dmq1`` parameters. The following functions are provided for users who want to work with keys like this without having to do the math themselves. @@ -241,7 +271,7 @@ this without having to do the math themselves. ``p``. .. function:: rsa_crt_dmq1(private_exponent, q) - + .. versionadded:: 0.4 Generates the ``dmq1`` parameter from the RSA private exponent and prime diff --git a/docs/hazmat/primitives/interfaces.rst b/docs/hazmat/primitives/interfaces.rst index 95fd6f9f..3b837a0d 100644 --- a/docs/hazmat/primitives/interfaces.rst +++ b/docs/hazmat/primitives/interfaces.rst @@ -133,6 +133,24 @@ Asymmetric interfaces :returns: :class:`~cryptography.hazmat.primitives.interfaces.AsymmetricSignatureContext` + .. method:: decrypt(ciphertext, padding, backend) + + .. versionadded:: 0.4 + + Decrypt data that was encrypted via the public key. + + :param bytes ciphertext: The ciphertext to decrypt. + + :param padding: An instance of a + :class:`~cryptography.hazmat.primitives.interfaces.AsymmetricPadding` + provider. + + :param backend: A + :class:`~cryptography.hazmat.backends.interfaces.RSABackend` + provider. + + :return bytes: Decrypted data. + .. method:: public_key() :return: :class:`~cryptography.hazmat.primitives.interfaces.RSAPublicKey` diff --git a/docs/installation.rst b/docs/installation.rst index a0dd5f22..3ebbecfd 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -10,16 +10,27 @@ You can install ``cryptography`` with ``pip``: Supported platforms ------------------- -Currently we test ``cryptography`` on Python 2.6, 2.7, 3.2, 3.3 and PyPy on -these operating systems. +Currently we test ``cryptography`` on Python 2.6, 2.7, 3.2, 3.3, 3.4 and PyPy +on these operating systems. -* x86-64 CentOS 6.4 and CentOS 5 +* x86-64 CentOS 6.4 and CentOS 5.x * x86-64 FreeBSD 9.2 and FreeBSD 10 * OS X 10.9 Mavericks, 10.8 Mountain Lion, and 10.7 Lion * x86-64 Ubuntu 12.04 LTS * 32-bit Python on 64-bit Windows Server 2008 * 64-bit Python on 64-bit Windows Server 2012 +We test compiling with ``clang`` as well as ``gcc`` and use the following +OpenSSL releases: + +* ``OpenSSL 0.9.8e-fips-rhel5`` (``RHEL/CentOS 5``) +* ``OpenSSL 0.9.8y`` +* ``OpenSSL 1.0.0-fips`` (``RHEL/CentOS 6.4``) +* ``OpenSSL 1.0.1`` +* ``OpenSSL 1.0.1e-freebsd`` +* ``OpenSSL 1.0.1g`` +* ``OpenSSL 1.0.2 beta`` + On Windows ---------- @@ -14,9 +14,9 @@ from __future__ import absolute_import, division, print_function import os +import subprocess import sys from distutils.command.build import build -import subprocess import pkg_resources diff --git a/tests/hazmat/backends/test_openssl.py b/tests/hazmat/backends/test_openssl.py index 43d28c33..c589506f 100644 --- a/tests/hazmat/backends/test_openssl.py +++ b/tests/hazmat/backends/test_openssl.py @@ -143,8 +143,8 @@ class TestOpenSSL(object): with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH): backend.derive_pbkdf2_hmac(hashes.SHA256(), 10, b"", 1000, b"") - # This test is not in the next class because to check if it's really - # default we don't want to run the setup_method before it + # This test is not in the TestOpenSSLRandomEngine class because to check + # if it's really default we don't want to run the setup_method before it def test_osrandom_engine_is_default(self): e = backend._lib.ENGINE_get_default_RAND() name = backend._lib.ENGINE_get_name(e) diff --git a/tests/hazmat/primitives/test_dsa.py b/tests/hazmat/primitives/test_dsa.py index 2b5d4bb3..bc3b1db6 100644 --- a/tests/hazmat/primitives/test_dsa.py +++ b/tests/hazmat/primitives/test_dsa.py @@ -23,7 +23,7 @@ from cryptography.hazmat.primitives.asymmetric import dsa from cryptography.utils import bit_length from ...utils import ( - load_vectors_from_file, load_fips_dsa_key_pair_vectors, + load_fips_dsa_key_pair_vectors, load_vectors_from_file, raises_unsupported_algorithm ) diff --git a/tests/hazmat/primitives/test_pbkdf2hmac.py b/tests/hazmat/primitives/test_pbkdf2hmac.py index 62ca0921..e928fc6a 100644 --- a/tests/hazmat/primitives/test_pbkdf2hmac.py +++ b/tests/hazmat/primitives/test_pbkdf2hmac.py @@ -14,6 +14,7 @@ from __future__ import absolute_import, division, print_function import pytest + import six from cryptography import utils diff --git a/tests/hazmat/primitives/test_rsa.py b/tests/hazmat/primitives/test_rsa.py index 84d0f805..a5266d57 100644 --- a/tests/hazmat/primitives/test_rsa.py +++ b/tests/hazmat/primitives/test_rsa.py @@ -1225,3 +1225,98 @@ class TestMGF1(object): mgf = padding.MGF1(algorithm, padding.MGF1.MAX_LENGTH) assert mgf._algorithm == algorithm assert mgf._salt_length == padding.MGF1.MAX_LENGTH + + +@pytest.mark.rsa +class TestRSADecryption(object): + @pytest.mark.parametrize( + "vector", + _flatten_pkcs1_examples(load_vectors_from_file( + os.path.join( + "asymmetric", "RSA", "pkcs1v15crypt-vectors.txt"), + load_pkcs1_vectors + )) + ) + def test_decrypt_pkcs1v15_vectors(self, vector, backend): + private, public, example = vector + skey = rsa.RSAPrivateKey( + p=private["p"], + q=private["q"], + private_exponent=private["private_exponent"], + dmp1=private["dmp1"], + dmq1=private["dmq1"], + iqmp=private["iqmp"], + public_exponent=private["public_exponent"], + modulus=private["modulus"] + ) + ciphertext = binascii.unhexlify(example["encryption"]) + assert len(ciphertext) == math.ceil(skey.key_size / 8.0) + message = skey.decrypt( + ciphertext, + padding.PKCS1v15(), + backend + ) + assert message == binascii.unhexlify(example["message"]) + + def test_unsupported_padding(self, backend): + private_key = rsa.RSAPrivateKey.generate( + public_exponent=65537, + key_size=512, + backend=backend + ) + with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_PADDING): + private_key.decrypt(b"somedata", DummyPadding(), backend) + + def test_decrypt_invalid_decrypt(self, backend): + private_key = rsa.RSAPrivateKey.generate( + public_exponent=65537, + key_size=512, + backend=backend + ) + with pytest.raises(ValueError): + private_key.decrypt( + b"\x00" * 64, + padding.PKCS1v15(), + backend + ) + + def test_decrypt_ciphertext_too_large(self, backend): + private_key = rsa.RSAPrivateKey.generate( + public_exponent=65537, + key_size=512, + backend=backend + ) + with pytest.raises(ValueError): + private_key.decrypt( + b"\x00" * 65, + padding.PKCS1v15(), + backend + ) + + def test_decrypt_ciphertext_too_small(self, backend): + private_key = rsa.RSAPrivateKey.generate( + public_exponent=65537, + key_size=512, + backend=backend + ) + ct = binascii.unhexlify( + b"50b4c14136bd198c2f3c3ed243fce036e168d56517984a263cd66492b80804f1" + b"69d210f2b9bdfb48b12f9ea05009c77da257cc600ccefe3a6283789d8ea0" + ) + with pytest.raises(ValueError): + private_key.decrypt( + ct, + padding.PKCS1v15(), + backend + ) + + def test_rsa_decrypt_invalid_backend(self, backend): + pretend_backend = object() + private_key = rsa.RSAPrivateKey.generate(65537, 2048, backend) + + with raises_unsupported_algorithm(_Reasons.BACKEND_MISSING_INTERFACE): + private_key.decrypt( + b"irrelevant", + padding.PKCS1v15(), + pretend_backend + ) diff --git a/tests/utils.py b/tests/utils.py index c38ba7ff..63560395 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -15,8 +15,8 @@ from __future__ import absolute_import, division, print_function import binascii import collections -from contextlib import contextmanager import re +from contextlib import contextmanager import pytest @@ -17,8 +17,8 @@ commands = deps = pyenchant sphinx - sphinxcontrib-spelling sphinx_rtd_theme + sphinxcontrib-spelling basepython = python2.7 commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs docs/_build/html @@ -42,6 +42,7 @@ commands = [testenv:pep8] deps = flake8 + flake8-import-order pep8-naming commands = flake8 . @@ -49,9 +50,11 @@ commands = flake8 . basepython = python3.3 deps = flake8 + flake8-import-order pep8-naming commands = flake8 . [flake8] exclude = .tox,*.egg -select = E,W,F,N +select = E,W,F,N,I +application-import-names = cryptography,cryptography_vectors,tests diff --git a/vectors/cryptography_vectors/__init__.py b/vectors/cryptography_vectors/__init__.py index 02d748df..25df6b3a 100644 --- a/vectors/cryptography_vectors/__init__.py +++ b/vectors/cryptography_vectors/__init__.py @@ -16,8 +16,8 @@ from __future__ import absolute_import, division, print_function import os from cryptography_vectors.__about__ import ( - __title__, __summary__, __uri__, __version__, __author__, __email__, - __license__, __copyright__ + __author__, __copyright__, __email__, __license__, __summary__, __title__, + __uri__, __version__ ) diff --git a/vectors/setup.py b/vectors/setup.py index ce01e132..66841def 100644 --- a/vectors/setup.py +++ b/vectors/setup.py @@ -15,7 +15,7 @@ from __future__ import absolute_import, division, print_function import os -from setuptools import setup, find_packages +from setuptools import find_packages, setup base_dir = os.path.dirname(__file__) |
