diff options
-rw-r--r-- | .coveragerc | 1 | ||||
-rw-r--r-- | cryptography/exceptions.py | 16 | ||||
-rw-r--r-- | cryptography/hazmat/bindings/openssl/backend.py | 10 | ||||
-rw-r--r-- | cryptography/hazmat/primitives/hashes.py | 59 | ||||
-rw-r--r-- | cryptography/hazmat/primitives/hmac.py | 38 | ||||
-rw-r--r-- | cryptography/hazmat/primitives/interfaces.py | 46 | ||||
-rw-r--r-- | docs/community.rst | 5 | ||||
-rw-r--r-- | docs/conf.py | 4 | ||||
-rw-r--r-- | docs/exceptions.rst | 9 | ||||
-rw-r--r-- | docs/glossary.rst | 30 | ||||
-rw-r--r-- | docs/hazmat/primitives/cryptographic-hashes.rst | 29 | ||||
-rw-r--r-- | docs/hazmat/primitives/hmac.rst | 23 | ||||
-rw-r--r-- | docs/hazmat/primitives/symmetric-encryption.rst | 18 | ||||
-rw-r--r-- | docs/index.rst | 2 | ||||
-rw-r--r-- | tests/hazmat/primitives/test_block.py | 11 | ||||
-rw-r--r-- | tests/hazmat/primitives/test_hash_vectors.py | 20 | ||||
-rw-r--r-- | tests/hazmat/primitives/test_hashes.py | 39 | ||||
-rw-r--r-- | tests/hazmat/primitives/test_hmac.py | 21 | ||||
-rw-r--r-- | tests/hazmat/primitives/test_hmac_vectors.py | 14 | ||||
-rw-r--r-- | tests/hazmat/primitives/utils.py | 46 |
20 files changed, 285 insertions, 156 deletions
diff --git a/.coveragerc b/.coveragerc index b891cb7c..20e3224e 100644 --- a/.coveragerc +++ b/.coveragerc @@ -4,3 +4,4 @@ branch = True [report] exclude_lines = @abc.abstractmethod + @abc.abstractproperty diff --git a/cryptography/exceptions.py b/cryptography/exceptions.py new file mode 100644 index 00000000..391bed82 --- /dev/null +++ b/cryptography/exceptions.py @@ -0,0 +1,16 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +class UnsupportedAlgorithm(Exception): + pass diff --git a/cryptography/hazmat/bindings/openssl/backend.py b/cryptography/hazmat/bindings/openssl/backend.py index fc73dd39..32adfed9 100644 --- a/cryptography/hazmat/bindings/openssl/backend.py +++ b/cryptography/hazmat/bindings/openssl/backend.py @@ -18,6 +18,7 @@ import sys import cffi +from cryptography.exceptions import UnsupportedAlgorithm from cryptography.hazmat.primitives import interfaces from cryptography.hazmat.primitives.block.ciphers import ( AES, Blowfish, Camellia, CAST5, TripleDES, @@ -128,9 +129,12 @@ class _CipherContext(object): ctx = self._backend.ffi.gc(ctx, self._backend.lib.EVP_CIPHER_CTX_free) registry = self._backend.ciphers._cipher_registry - evp_cipher = registry[type(cipher), type(mode)]( - self._backend, cipher, mode - ) + try: + adapter = registry[type(cipher), type(mode)] + except KeyError: + raise UnsupportedAlgorithm + + evp_cipher = adapter(self._backend, cipher, mode) assert evp_cipher != self._backend.ffi.NULL if isinstance(mode, interfaces.ModeWithInitializationVector): iv_nonce = mode.initialization_vector diff --git a/cryptography/hazmat/primitives/hashes.py b/cryptography/hazmat/primitives/hashes.py index 3ccb59d1..bdad5e16 100644 --- a/cryptography/hazmat/primitives/hashes.py +++ b/cryptography/hazmat/primitives/hashes.py @@ -13,89 +13,94 @@ from __future__ import absolute_import, division, print_function -import abc +import six -import binascii +from cryptography.hazmat.primitives import interfaces -import six +@interfaces.register(interfaces.HashContext) +class Hash(object): + def __init__(self, algorithm, backend=None, ctx=None): + if not isinstance(algorithm, interfaces.HashAlgorithm): + raise TypeError("Expected instance of interfaces.HashAlgorithm.") + self.algorithm = algorithm -class BaseHash(six.with_metaclass(abc.ABCMeta)): - def __init__(self, data=None, backend=None, ctx=None): if backend is None: from cryptography.hazmat.bindings import _default_backend backend = _default_backend + self._backend = backend + if ctx is None: - self._ctx = self._backend.hashes.create_ctx(self) + self._ctx = self._backend.hashes.create_ctx(self.algorithm) else: self._ctx = None - if data is not None: - self.update(data) - def update(self, data): if isinstance(data, six.text_type): raise TypeError("Unicode-objects must be encoded before hashing") self._backend.hashes.update_ctx(self._ctx, data) def copy(self): - return self.__class__(backend=self._backend, ctx=self._copy_ctx()) - - def digest(self): - return self._backend.hashes.finalize_ctx(self._copy_ctx(), - self.digest_size) - - def hexdigest(self): - return str(binascii.hexlify(self.digest()).decode("ascii")) + return self.__class__(self.algorithm, backend=self._backend, + ctx=self._backend.hashes.copy_ctx(self._ctx)) - def _copy_ctx(self): - return self._backend.hashes.copy_ctx(self._ctx) + def finalize(self): + return self._backend.hashes.finalize_ctx(self._ctx, + self.algorithm.digest_size) -class SHA1(BaseHash): +@interfaces.register(interfaces.HashAlgorithm) +class SHA1(object): name = "sha1" digest_size = 20 block_size = 64 -class SHA224(BaseHash): +@interfaces.register(interfaces.HashAlgorithm) +class SHA224(object): name = "sha224" digest_size = 28 block_size = 64 -class SHA256(BaseHash): +@interfaces.register(interfaces.HashAlgorithm) +class SHA256(object): name = "sha256" digest_size = 32 block_size = 64 -class SHA384(BaseHash): +@interfaces.register(interfaces.HashAlgorithm) +class SHA384(object): name = "sha384" digest_size = 48 block_size = 128 -class SHA512(BaseHash): +@interfaces.register(interfaces.HashAlgorithm) +class SHA512(object): name = "sha512" digest_size = 64 block_size = 128 -class RIPEMD160(BaseHash): +@interfaces.register(interfaces.HashAlgorithm) +class RIPEMD160(object): name = "ripemd160" digest_size = 20 block_size = 64 -class Whirlpool(BaseHash): +@interfaces.register(interfaces.HashAlgorithm) +class Whirlpool(object): name = "whirlpool" digest_size = 64 block_size = 64 -class MD5(BaseHash): +@interfaces.register(interfaces.HashAlgorithm) +class MD5(object): name = "md5" digest_size = 16 block_size = 64 diff --git a/cryptography/hazmat/primitives/hmac.py b/cryptography/hazmat/primitives/hmac.py index 4da0cc3f..1457ed78 100644 --- a/cryptography/hazmat/primitives/hmac.py +++ b/cryptography/hazmat/primitives/hmac.py @@ -13,47 +13,39 @@ from __future__ import absolute_import, division, print_function -import binascii - import six +from cryptography.hazmat.primitives import interfaces + +@interfaces.register(interfaces.HashContext) class HMAC(object): - def __init__(self, key, msg=None, digestmod=None, ctx=None, backend=None): + def __init__(self, key, algorithm, ctx=None, backend=None): super(HMAC, self).__init__() + if not isinstance(algorithm, interfaces.HashAlgorithm): + raise TypeError("Expected instance of interfaces.HashAlgorithm.") + self.algorithm = algorithm + if backend is None: from cryptography.hazmat.bindings import _default_backend backend = _default_backend - if digestmod is None: - raise TypeError("digestmod is a required argument") - self._backend = backend - self.digestmod = digestmod - self.key = key + self._key = key if ctx is None: - self._ctx = self._backend.hmacs.create_ctx(key, self.digestmod) + self._ctx = self._backend.hmacs.create_ctx(key, self.algorithm) else: self._ctx = ctx - if msg is not None: - self.update(msg) - def update(self, msg): if isinstance(msg, six.text_type): raise TypeError("Unicode-objects must be encoded before hashing") self._backend.hmacs.update_ctx(self._ctx, msg) def copy(self): - return self.__class__(self.key, digestmod=self.digestmod, - backend=self._backend, ctx=self._copy_ctx()) - - def digest(self): - return self._backend.hmacs.finalize_ctx(self._copy_ctx(), - self.digestmod.digest_size) - - def hexdigest(self): - return str(binascii.hexlify(self.digest()).decode("ascii")) + return self.__class__(self._key, self.algorithm, backend=self._backend, + ctx=self._backend.hmacs.copy_ctx(self._ctx)) - def _copy_ctx(self): - return self._backend.hmacs.copy_ctx(self._ctx) + def finalize(self): + return self._backend.hmacs.finalize_ctx(self._ctx, + self.algorithm.digest_size) diff --git a/cryptography/hazmat/primitives/interfaces.py b/cryptography/hazmat/primitives/interfaces.py index 217490fd..ebf5e31e 100644 --- a/cryptography/hazmat/primitives/interfaces.py +++ b/cryptography/hazmat/primitives/interfaces.py @@ -59,3 +59,49 @@ class PaddingContext(six.with_metaclass(abc.ABCMeta)): """ finalize return bytes """ + + +class HashAlgorithm(six.with_metaclass(abc.ABCMeta)): + @abc.abstractproperty + def name(self): + """ + A string naming this algorithm. (ex. sha256, md5) + """ + + @abc.abstractproperty + def digest_size(self): + """ + The size of the resulting digest in bytes. + """ + + @abc.abstractproperty + def block_size(self): + """ + The internal block size of the hash algorithm in bytes. + """ + + +class HashContext(six.with_metaclass(abc.ABCMeta)): + @abc.abstractproperty + def algorithm(self): + """ + A HashAlgorithm that will be used by this context. + """ + + @abc.abstractmethod + def update(self, data): + """ + hash data as bytes + """ + + @abc.abstractmethod + def finalize(self): + """ + finalize this copy of the hash and return the digest as bytes. + """ + + @abc.abstractmethod + def copy(self): + """ + return a HashContext that is a copy of the current context. + """ diff --git a/docs/community.rst b/docs/community.rst index 552318da..bf1cd1c7 100644 --- a/docs/community.rst +++ b/docs/community.rst @@ -9,7 +9,12 @@ You can find ``cryptography`` all over the web: * `Documentation`_ * IRC: ``#cryptography-dev`` on ``irc.freenode.net`` +Wherever we interact, we strive to follow the `Python Community Code of +Conduct`_. + + .. _`Mailing list`: https://mail.python.org/mailman/listinfo/cryptography-dev .. _`Source code`: https://github.com/pyca/cryptography .. _`Issue tracker`: https://github.com/pyca/cryptography/issues .. _`Documentation`: https://cryptography.io/ +.. _`Python Community Code of Conduct`: http://www.python.org/psf/codeofconduct/ diff --git a/docs/conf.py b/docs/conf.py index 8e0fc7be..69be32e9 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -252,7 +252,3 @@ texinfo_documents = [ # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None} - - -# Enable the new ReadTheDocs theme -RTD_NEW_THEME = True diff --git a/docs/exceptions.rst b/docs/exceptions.rst new file mode 100644 index 00000000..6ac11b3c --- /dev/null +++ b/docs/exceptions.rst @@ -0,0 +1,9 @@ +Exceptions +========== + +.. currentmodule:: cryptography.exceptions + +.. class:: UnsupportedAlgorithm + + This is raised when a backend doesn't support the requested algorithm (or + combination of algorithms). diff --git a/docs/glossary.rst b/docs/glossary.rst new file mode 100644 index 00000000..e4fc8283 --- /dev/null +++ b/docs/glossary.rst @@ -0,0 +1,30 @@ +Glossary +======== + +.. glossary:: + + plaintext + User-readable data you care about. + + ciphertext + The encoded data, it's not user readable. Potential attackers are able + to see this. + + encryption + The process of converting plaintext to ciphertext. + + decryption + The process of converting ciphertext to plaintext. + + key + Secret data is encoded with a function using this key. Sometimes + multiple keys are used. These **must** be kept secret, if a key is + exposed to an attacker, any data encrypted with it will be exposed. + + symmetric cryptography + Cryptographic operations where encryption and decryption use the same + key. + + asymmetric cryptography + Cryptographic operations where encryption and decryption use different + keys. There are seperate encryption and decryption keys. diff --git a/docs/hazmat/primitives/cryptographic-hashes.rst b/docs/hazmat/primitives/cryptographic-hashes.rst index c780dcb0..76ca20c0 100644 --- a/docs/hazmat/primitives/cryptographic-hashes.rst +++ b/docs/hazmat/primitives/cryptographic-hashes.rst @@ -5,21 +5,27 @@ Message Digests .. currentmodule:: cryptography.hazmat.primitives.hashes -.. class:: BaseHash(data=None) +.. class:: Hash(algorithm) - Abstract base class that implements a common interface for all hash - algorithms that follow here. + A cryptographic hash function takes an arbitrary block of data and + calculates a fixed-size bit string (a digest), such that different data + results (with a high probability) in different digests. - If ``data`` is provided ``update(data)`` is called upon construction. + This is an implementation of + :class:`cryptography.hazmat.primitives.interfaces.HashContext` meant to + be used with + :class:`cryptography.hazmat.primitives.interfaces.HashAlgorithm` + implementations to provide an incremental interface to calculating + various message digests. .. doctest:: >>> from cryptography.hazmat.primitives import hashes - >>> digest = hashes.SHA256() + >>> digest = hashes.Hash(hashes.SHA256()) >>> digest.update(b"abc") >>> digest.update(b"123") - >>> digest.hexdigest() - '6ca13d52ca70c883e0f0bb101e425a89e8624de51db2d2392593af6a84118090' + >>> digest.finalize() + 'l\xa1=R\xcap\xc8\x83\xe0\xf0\xbb\x10\x1eBZ\x89\xe8bM\xe5\x1d\xb2\xd29%\x93\xafj\x84\x11\x80\x90' .. method:: update(data) @@ -29,13 +35,14 @@ Message Digests :return: a new instance of this object with a copied internal state. - .. method:: digest() + .. method:: finalize() - :return bytes: The message digest as bytes. + Finalize the current context and return the message digest as bytes. + + Once ``finalize`` is called this object can no longer be used. - .. method:: hexdigest() + :return bytes: The message digest as bytes. - :return str: The message digest as hex. SHA-1 ~~~~~ diff --git a/docs/hazmat/primitives/hmac.rst b/docs/hazmat/primitives/hmac.rst index 44cc29fa..bd1a4934 100644 --- a/docs/hazmat/primitives/hmac.rst +++ b/docs/hazmat/primitives/hmac.rst @@ -15,21 +15,23 @@ message authentication codes using a cryptographic hash function coupled with a secret key. You can use an HMAC to verify integrity as well as authenticate a message. -.. class:: HMAC(key, msg=None, digestmod=None) +.. class:: HMAC(key, algorithm) - HMAC objects take a ``key``, a hash class derived from - :class:`~cryptography.primitives.hashes.BaseHash`, and optional message. + HMAC objects take a ``key`` and a provider of + :class:`~cryptography.hazmat.primitives.interfaces.HashAlgorithm`. The ``key`` should be randomly generated bytes and is recommended to be equal in length to the ``digest_size`` of the hash function chosen. You must keep the ``key`` secret. + This is an implementation of :rfc:`2104`. + .. doctest:: >>> from cryptography.hazmat.primitives import hashes, hmac - >>> h = hmac.HMAC(key, digestmod=hashes.SHA256) + >>> h = hmac.HMAC(key, hashes.SHA256()) >>> h.update(b"message to hash") - >>> h.hexdigest() - '...' + >>> h.finalize() + '#F\xdaI\x8b"e\xc4\xf1\xbb\x9a\x8fc\xff\xf5\xdex.\xbc\xcd/+\x8a\x86\x1d\x84\'\xc3\xa6\x1d\xd8J' .. method:: update(msg) @@ -39,11 +41,10 @@ message. :return: a new instance of this object with a copied internal state. - .. method:: digest() - - :return bytes: The message digest as bytes. + .. method:: finalize() - .. method:: hexdigest() + Finalize the current context and return the message digest as bytes. - :return str: The message digest as hex. + Once ``finalize`` is called this object can no longer be used. + :return bytes: The message digest as bytes. diff --git a/docs/hazmat/primitives/symmetric-encryption.rst b/docs/hazmat/primitives/symmetric-encryption.rst index 5852dc21..c1c8d247 100644 --- a/docs/hazmat/primitives/symmetric-encryption.rst +++ b/docs/hazmat/primitives/symmetric-encryption.rst @@ -42,12 +42,21 @@ where the encrypter and decrypter both use the same key. :class:`~cryptography.hazmat.primitives.interfaces.CipherContext` provider. + If the backend doesn't support the requested combination of ``cipher`` + and ``mode`` an :class:`cryptography.exceptions.UnsupportedAlgorithm` + will be raised. + .. method:: decryptor() :return: A decrypting :class:`~cryptography.hazmat.primitives.interfaces.CipherContext` provider. + If the backend doesn't support the requested combination of ``cipher`` + and ``mode`` an :class:`cryptography.exceptions.UnsupportedAlgorithm` + will be raised. + + .. currentmodule:: cryptography.hazmat.primitives.interfaces .. class:: CipherContext @@ -63,6 +72,12 @@ where the encrypter and decrypter both use the same key. :param bytes data: The data you wish to pass into the context. :return bytes: Returns the data that was encrypted or decrypted. + When the ``BlockCipher`` was constructed in a mode turns it into a + stream cipher (e.g. + :class:`cryptography.hazmat.primitives.block.modes.CTR`), this will + return bytes immediately, however in other modes it will return chunks, + whose size is determined by the cipher's block size. + .. method:: finalize() :return bytes: Returns the remainder of the data. @@ -162,7 +177,8 @@ Modes block size of less than 128-bits. CTR (Counter) is a mode of operation for block ciphers. It is considered - cryptographically strong. + cryptographically strong. It transforms a block cipher into a stream + cipher. :param bytes nonce: Should be random bytes. It is critical to never reuse a ``nonce`` with a given key. Any reuse of a nonce diff --git a/docs/index.rst b/docs/index.rst index 4fd5d3be..1b88e24e 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -31,6 +31,8 @@ Contents :maxdepth: 2 architecture + exceptions + glossary contributing security community diff --git a/tests/hazmat/primitives/test_block.py b/tests/hazmat/primitives/test_block.py index e0ed6697..dd9c54c9 100644 --- a/tests/hazmat/primitives/test_block.py +++ b/tests/hazmat/primitives/test_block.py @@ -17,6 +17,7 @@ import binascii import pytest +from cryptography.exceptions import UnsupportedAlgorithm from cryptography.hazmat.primitives import interfaces from cryptography.hazmat.primitives.block import BlockCipher, ciphers, modes @@ -84,3 +85,13 @@ class TestBlockCipherContext(object): assert len(pt) == 80 assert pt == b"a" * 80 decryptor.finalize() + + def test_nonexistant_cipher(self, backend): + cipher = BlockCipher( + object(), object(), backend + ) + with pytest.raises(UnsupportedAlgorithm): + cipher.encryptor() + + with pytest.raises(UnsupportedAlgorithm): + cipher.decryptor() diff --git a/tests/hazmat/primitives/test_hash_vectors.py b/tests/hazmat/primitives/test_hash_vectors.py index 5c3e72d4..fca839c7 100644 --- a/tests/hazmat/primitives/test_hash_vectors.py +++ b/tests/hazmat/primitives/test_hash_vectors.py @@ -29,7 +29,7 @@ class TestSHA1(object): "SHA1LongMsg.rsp", "SHA1ShortMsg.rsp", ], - hashes.SHA1, + hashes.SHA1(), only_if=lambda backend: backend.hashes.supported(hashes.SHA1), skip_message="Does not support SHA1", ) @@ -43,7 +43,7 @@ class TestSHA224(object): "SHA224LongMsg.rsp", "SHA224ShortMsg.rsp", ], - hashes.SHA224, + hashes.SHA224(), only_if=lambda backend: backend.hashes.supported(hashes.SHA224), skip_message="Does not support SHA224", ) @@ -57,7 +57,7 @@ class TestSHA256(object): "SHA256LongMsg.rsp", "SHA256ShortMsg.rsp", ], - hashes.SHA256, + hashes.SHA256(), only_if=lambda backend: backend.hashes.supported(hashes.SHA256), skip_message="Does not support SHA256", ) @@ -71,7 +71,7 @@ class TestSHA384(object): "SHA384LongMsg.rsp", "SHA384ShortMsg.rsp", ], - hashes.SHA384, + hashes.SHA384(), only_if=lambda backend: backend.hashes.supported(hashes.SHA384), skip_message="Does not support SHA384", ) @@ -85,7 +85,7 @@ class TestSHA512(object): "SHA512LongMsg.rsp", "SHA512ShortMsg.rsp", ], - hashes.SHA512, + hashes.SHA512(), only_if=lambda backend: backend.hashes.supported(hashes.SHA512), skip_message="Does not support SHA512", ) @@ -98,13 +98,13 @@ class TestRIPEMD160(object): [ "ripevectors.txt", ], - hashes.RIPEMD160, + hashes.RIPEMD160(), only_if=lambda backend: backend.hashes.supported(hashes.RIPEMD160), skip_message="Does not support RIPEMD160", ) test_RIPEMD160_long_string = generate_long_string_hash_test( - hashes.RIPEMD160, + hashes.RIPEMD160(), "52783243c1697bdbe16d37f97f68f08325dc1528", only_if=lambda backend: backend.hashes.supported(hashes.RIPEMD160), skip_message="Does not support RIPEMD160", @@ -118,13 +118,13 @@ class TestWhirlpool(object): [ "iso-test-vectors.txt", ], - hashes.Whirlpool, + hashes.Whirlpool(), only_if=lambda backend: backend.hashes.supported(hashes.Whirlpool), skip_message="Does not support Whirlpool", ) test_whirlpool_long_string = generate_long_string_hash_test( - hashes.Whirlpool, + hashes.Whirlpool(), ("0c99005beb57eff50a7cf005560ddf5d29057fd86b2" "0bfd62deca0f1ccea4af51fc15490eddc47af32bb2b" "66c34ff9ad8c6008ad677f77126953b226e4ed8b01"), @@ -140,7 +140,7 @@ class TestMD5(object): [ "rfc-1321.txt", ], - hashes.MD5, + hashes.MD5(), only_if=lambda backend: backend.hashes.supported(hashes.MD5), skip_message="Does not support MD5", ) diff --git a/tests/hazmat/primitives/test_hashes.py b/tests/hazmat/primitives/test_hashes.py index 797fe4ff..07ab2489 100644 --- a/tests/hazmat/primitives/test_hashes.py +++ b/tests/hazmat/primitives/test_hashes.py @@ -25,39 +25,36 @@ from cryptography.hazmat.primitives import hashes from .utils import generate_base_hash_test -class TestBaseHash(object): - def test_base_hash_reject_unicode(self, backend): - m = hashes.SHA1(backend=backend) +class TestHashContext(object): + def test_hash_reject_unicode(self, backend): + m = hashes.Hash(hashes.SHA1(), backend=backend) with pytest.raises(TypeError): m.update(six.u("\u00FC")) - def test_base_hash_hexdigest_string_type(self, backend): - m = hashes.SHA1(backend=backend, data=b"") - assert isinstance(m.hexdigest(), str) - - -class TestCopyHash(object): def test_copy_backend_object(self): pretend_hashes = pretend.stub(copy_ctx=lambda a: "copiedctx") pretend_backend = pretend.stub(hashes=pretend_hashes) pretend_ctx = pretend.stub() - h = hashes.SHA1(backend=pretend_backend, ctx=pretend_ctx) + h = hashes.Hash(hashes.SHA1(), backend=pretend_backend, + ctx=pretend_ctx) assert h._backend is pretend_backend assert h.copy()._backend is h._backend - -class TestDefaultBackendSHA1(object): def test_default_backend_creation(self): """ This test assumes the presence of SHA1 in the default backend. """ - h = hashes.SHA1() + h = hashes.Hash(hashes.SHA1()) assert h._backend is _default_backend + def test_hash_algorithm_instance(self): + with pytest.raises(TypeError): + hashes.Hash(hashes.SHA1) + class TestSHA1(object): test_SHA1 = generate_base_hash_test( - hashes.SHA1, + hashes.SHA1(), digest_size=20, block_size=64, only_if=lambda backend: backend.hashes.supported(hashes.SHA1), @@ -67,7 +64,7 @@ class TestSHA1(object): class TestSHA224(object): test_SHA224 = generate_base_hash_test( - hashes.SHA224, + hashes.SHA224(), digest_size=28, block_size=64, only_if=lambda backend: backend.hashes.supported(hashes.SHA224), @@ -77,7 +74,7 @@ class TestSHA224(object): class TestSHA256(object): test_SHA256 = generate_base_hash_test( - hashes.SHA256, + hashes.SHA256(), digest_size=32, block_size=64, only_if=lambda backend: backend.hashes.supported(hashes.SHA256), @@ -87,7 +84,7 @@ class TestSHA256(object): class TestSHA384(object): test_SHA384 = generate_base_hash_test( - hashes.SHA384, + hashes.SHA384(), digest_size=48, block_size=128, only_if=lambda backend: backend.hashes.supported(hashes.SHA384), @@ -97,7 +94,7 @@ class TestSHA384(object): class TestSHA512(object): test_SHA512 = generate_base_hash_test( - hashes.SHA512, + hashes.SHA512(), digest_size=64, block_size=128, only_if=lambda backend: backend.hashes.supported(hashes.SHA512), @@ -107,7 +104,7 @@ class TestSHA512(object): class TestRIPEMD160(object): test_RIPEMD160 = generate_base_hash_test( - hashes.RIPEMD160, + hashes.RIPEMD160(), digest_size=20, block_size=64, only_if=lambda backend: backend.hashes.supported(hashes.RIPEMD160), @@ -117,7 +114,7 @@ class TestRIPEMD160(object): class TestWhirlpool(object): test_Whirlpool = generate_base_hash_test( - hashes.Whirlpool, + hashes.Whirlpool(), digest_size=64, block_size=64, only_if=lambda backend: backend.hashes.supported(hashes.Whirlpool), @@ -127,7 +124,7 @@ class TestWhirlpool(object): class TestMD5(object): test_MD5 = generate_base_hash_test( - hashes.MD5, + hashes.MD5(), digest_size=16, block_size=64, only_if=lambda backend: backend.hashes.supported(hashes.MD5), diff --git a/tests/hazmat/primitives/test_hmac.py b/tests/hazmat/primitives/test_hmac.py index 42726a7c..a44838cf 100644 --- a/tests/hazmat/primitives/test_hmac.py +++ b/tests/hazmat/primitives/test_hmac.py @@ -26,32 +26,25 @@ from .utils import generate_base_hmac_test class TestHMAC(object): test_copy = generate_base_hmac_test( - hashes.MD5, + hashes.MD5(), only_if=lambda backend: backend.hashes.supported(hashes.MD5), skip_message="Does not support MD5", ) def test_hmac_reject_unicode(self, backend): - h = hmac.HMAC(key=b"mykey", digestmod=hashes.SHA1, backend=backend) + h = hmac.HMAC(b"mykey", hashes.SHA1(), backend=backend) with pytest.raises(TypeError): h.update(six.u("\u00FC")) - def test_base_hash_hexdigest_string_type(self, backend): - h = hmac.HMAC(key=b"mykey", digestmod=hashes.SHA1, backend=backend, - msg=b"") - assert isinstance(h.hexdigest(), str) - - def test_hmac_no_digestmod(self): - with pytest.raises(TypeError): - hmac.HMAC(key=b"shortkey") - - -class TestCopyHMAC(object): def test_copy_backend_object(self): pretend_hmac = pretend.stub(copy_ctx=lambda a: True) pretend_backend = pretend.stub(hmacs=pretend_hmac) pretend_ctx = pretend.stub() - h = hmac.HMAC(b"key", digestmod=hashes.SHA1, backend=pretend_backend, + h = hmac.HMAC(b"key", hashes.SHA1(), backend=pretend_backend, ctx=pretend_ctx) assert h._backend is pretend_backend assert h.copy()._backend is pretend_backend + + def test_hmac_algorithm_instance(self): + with pytest.raises(TypeError): + hmac.HMAC(b"key", hashes.SHA1) diff --git a/tests/hazmat/primitives/test_hmac_vectors.py b/tests/hazmat/primitives/test_hmac_vectors.py index 27b45012..52d592b6 100644 --- a/tests/hazmat/primitives/test_hmac_vectors.py +++ b/tests/hazmat/primitives/test_hmac_vectors.py @@ -26,7 +26,7 @@ class TestHMAC_MD5(object): [ "rfc-2202-md5.txt", ], - hashes.MD5, + hashes.MD5(), only_if=lambda backend: backend.hashes.supported(hashes.MD5), skip_message="Does not support MD5", ) @@ -39,7 +39,7 @@ class TestHMAC_SHA1(object): [ "rfc-2202-sha1.txt", ], - hashes.SHA1, + hashes.SHA1(), only_if=lambda backend: backend.hashes.supported(hashes.SHA1), skip_message="Does not support SHA1", ) @@ -52,7 +52,7 @@ class TestHMAC_SHA224(object): [ "rfc-4231-sha224.txt", ], - hashes.SHA224, + hashes.SHA224(), only_if=lambda backend: backend.hashes.supported(hashes.SHA224), skip_message="Does not support SHA224", ) @@ -65,7 +65,7 @@ class TestHMAC_SHA256(object): [ "rfc-4231-sha256.txt", ], - hashes.SHA256, + hashes.SHA256(), only_if=lambda backend: backend.hashes.supported(hashes.SHA256), skip_message="Does not support SHA256", ) @@ -78,7 +78,7 @@ class TestHMAC_SHA384(object): [ "rfc-4231-sha384.txt", ], - hashes.SHA384, + hashes.SHA384(), only_if=lambda backend: backend.hashes.supported(hashes.SHA384), skip_message="Does not support SHA384", ) @@ -91,7 +91,7 @@ class TestHMAC_SHA512(object): [ "rfc-4231-sha512.txt", ], - hashes.SHA512, + hashes.SHA512(), only_if=lambda backend: backend.hashes.supported(hashes.SHA512), skip_message="Does not support SHA512", ) @@ -104,7 +104,7 @@ class TestHMAC_RIPEMD160(object): [ "rfc-2286-ripemd160.txt", ], - hashes.RIPEMD160, + hashes.RIPEMD160(), only_if=lambda backend: backend.hashes.supported(hashes.RIPEMD160), skip_message="Does not support RIPEMD160", ) diff --git a/tests/hazmat/primitives/utils.py b/tests/hazmat/primitives/utils.py index c51fef52..b4a8a3e6 100644 --- a/tests/hazmat/primitives/utils.py +++ b/tests/hazmat/primitives/utils.py @@ -4,6 +4,7 @@ import os import pytest from cryptography.hazmat.bindings import _ALL_BACKENDS +from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import hmac from cryptography.hazmat.primitives.block import BlockCipher @@ -65,26 +66,25 @@ def generate_hash_test(param_loader, path, file_names, hash_cls, return test_hash -def hash_test(backend, hash_cls, params, only_if, skip_message): +def hash_test(backend, algorithm, params, only_if, skip_message): if only_if is not None and not only_if(backend): pytest.skip(skip_message) msg = params[0] md = params[1] - m = hash_cls(backend=backend) + m = hashes.Hash(algorithm, backend=backend) m.update(binascii.unhexlify(msg)) - assert m.hexdigest() == md.replace(" ", "").lower() - digst = hash_cls(backend=backend, data=binascii.unhexlify(msg)).hexdigest() - assert digst == md.replace(" ", "").lower() + expected_md = md.replace(" ", "").lower().encode("ascii") + assert m.finalize() == binascii.unhexlify(expected_md) -def generate_base_hash_test(hash_cls, digest_size, block_size, +def generate_base_hash_test(algorithm, digest_size, block_size, only_if=None, skip_message=None): def test_base_hash(self): for backend in _ALL_BACKENDS: yield ( base_hash_test, backend, - hash_cls, + algorithm, digest_size, block_size, only_if, @@ -93,13 +93,14 @@ def generate_base_hash_test(hash_cls, digest_size, block_size, return test_base_hash -def base_hash_test(backend, digestmod, digest_size, block_size, only_if, +def base_hash_test(backend, algorithm, digest_size, block_size, only_if, skip_message): if only_if is not None and not only_if(backend): pytest.skip(skip_message) - m = digestmod(backend=backend) - assert m.digest_size == digest_size - assert m.block_size == block_size + + m = hashes.Hash(algorithm, backend=backend) + assert m.algorithm.digest_size == digest_size + assert m.algorithm.block_size == block_size m_copy = m.copy() assert m != m_copy assert m._ctx != m_copy._ctx @@ -120,15 +121,15 @@ def generate_long_string_hash_test(hash_factory, md, only_if=None, return test_long_string_hash -def long_string_hash_test(backend, hash_factory, md, only_if, skip_message): +def long_string_hash_test(backend, algorithm, md, only_if, skip_message): if only_if is not None and not only_if(backend): pytest.skip(skip_message) - m = hash_factory(backend=backend) + m = hashes.Hash(algorithm, backend=backend) m.update(b"a" * 1000000) - assert m.hexdigest() == md.lower() + assert m.finalize() == binascii.unhexlify(md.lower().encode("ascii")) -def generate_hmac_test(param_loader, path, file_names, digestmod, +def generate_hmac_test(param_loader, path, file_names, algorithm, only_if=None, skip_message=None): def test_hmac(self): for backend in _ALL_BACKENDS: @@ -137,7 +138,7 @@ def generate_hmac_test(param_loader, path, file_names, digestmod, yield ( hmac_test, backend, - digestmod, + algorithm, params, only_if, skip_message @@ -145,18 +146,15 @@ def generate_hmac_test(param_loader, path, file_names, digestmod, return test_hmac -def hmac_test(backend, digestmod, params, only_if, skip_message): +def hmac_test(backend, algorithm, params, only_if, skip_message): if only_if is not None and not only_if(backend): pytest.skip(skip_message) msg = params[0] md = params[1] key = params[2] - h = hmac.HMAC(binascii.unhexlify(key), digestmod=digestmod) + h = hmac.HMAC(binascii.unhexlify(key), algorithm) h.update(binascii.unhexlify(msg)) - assert h.hexdigest() == md - digest = hmac.HMAC(binascii.unhexlify(key), digestmod=digestmod, - msg=binascii.unhexlify(msg)).hexdigest() - assert digest == md + assert h.finalize() == binascii.unhexlify(md.encode("ascii")) def generate_base_hmac_test(hash_cls, only_if=None, skip_message=None): @@ -172,11 +170,11 @@ def generate_base_hmac_test(hash_cls, only_if=None, skip_message=None): return test_base_hmac -def base_hmac_test(backend, digestmod, only_if, skip_message): +def base_hmac_test(backend, algorithm, only_if, skip_message): if only_if is not None and not only_if(backend): pytest.skip(skip_message) key = b"ab" - h = hmac.HMAC(binascii.unhexlify(key), digestmod=digestmod) + h = hmac.HMAC(binascii.unhexlify(key), algorithm) h_copy = h.copy() assert h != h_copy assert h._ctx != h_copy._ctx |