From 0317b04b119ceb55e11cf1be28c5223bad240c26 Mon Sep 17 00:00:00 2001 From: Paul Kehrer Date: Mon, 28 Oct 2013 17:34:27 -0500 Subject: HMAC support Conflicts: docs/primitives/index.rst tests/hazmat/primitives/utils.py --- cryptography/hazmat/bindings/openssl/backend.py | 40 +++++++++ cryptography/hazmat/primitives/hmac.py | 55 ++++++++++++ docs/hazmat/primitives/hmac.rst | 50 +++++++++++ docs/hazmat/primitives/index.rst | 1 + tests/hazmat/primitives/test_hmac.py | 53 +++++++++++ tests/hazmat/primitives/test_hmac_vectors.py | 114 ++++++++++++++++++++++++ tests/hazmat/primitives/test_utils.py | 25 +++++- tests/hazmat/primitives/utils.py | 55 ++++++++++++ tests/test_utils.py | 16 ++++ tests/utils.py | 12 ++- 10 files changed, 418 insertions(+), 3 deletions(-) create mode 100644 cryptography/hazmat/primitives/hmac.py create mode 100644 docs/hazmat/primitives/hmac.rst create mode 100644 tests/hazmat/primitives/test_hmac.py create mode 100644 tests/hazmat/primitives/test_hmac_vectors.py diff --git a/cryptography/hazmat/bindings/openssl/backend.py b/cryptography/hazmat/bindings/openssl/backend.py index 494430ba..300495cb 100644 --- a/cryptography/hazmat/bindings/openssl/backend.py +++ b/cryptography/hazmat/bindings/openssl/backend.py @@ -96,6 +96,7 @@ class Backend(object): self.ciphers = Ciphers(self) self.hashes = Hashes(self) + self.hmacs = HMACs(self) def openssl_version_text(self): """ @@ -259,4 +260,43 @@ class Hashes(object): return copied_ctx +class HMACs(object): + def __init__(self, backend): + super(HMACs, self).__init__() + self._backend = backend + + def create_ctx(self, key, hash_cls): + ctx = self._backend.ffi.new("HMAC_CTX *") + self._backend.lib.HMAC_CTX_init(ctx) + ctx = self._backend.ffi.gc(ctx, self._backend.lib.HMAC_CTX_cleanup) + evp_md = self._backend.lib.EVP_get_digestbyname( + hash_cls.name.encode('ascii')) + assert evp_md != self._backend.ffi.NULL + res = self._backend.lib.HMAC_Init_ex(ctx, key, len(key), evp_md, + self._backend.ffi.NULL) + assert res != 0 + return ctx + + def update_ctx(self, ctx, data): + res = self._backend.lib.HMAC_Update(ctx, data, len(data)) + assert res != 0 + + def finalize_ctx(self, ctx, digest_size): + buf = self._backend.ffi.new("unsigned char[]", digest_size) + buflen = self._backend.ffi.new("unsigned int *") + buflen[0] = digest_size + res = self._backend.lib.HMAC_Final(ctx, buf, buflen) + assert res != 0 + return self._backend.ffi.buffer(buf)[:digest_size] + + def copy_ctx(self, ctx): + copied_ctx = self._backend.ffi.new("HMAC_CTX *") + self._backend.lib.HMAC_CTX_init(copied_ctx) + copied_ctx = self._backend.ffi.gc(copied_ctx, + self._backend.lib.HMAC_CTX_cleanup) + res = self._backend.lib.HMAC_CTX_copy(copied_ctx, ctx) + assert res != 0 + return copied_ctx + + backend = Backend() diff --git a/cryptography/hazmat/primitives/hmac.py b/cryptography/hazmat/primitives/hmac.py new file mode 100644 index 00000000..f635e36e --- /dev/null +++ b/cryptography/hazmat/primitives/hmac.py @@ -0,0 +1,55 @@ +# 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. + +from __future__ import absolute_import, division, print_function + +import binascii + +import six + + +class HMAC(object): + def __init__(self, key, hash_cls, data=None, ctx=None, backend=None): + super(HMAC, self).__init__() + if backend is None: + from cryptography.hazmat.bindings import _default_backend + backend = _default_backend + self._backend = backend + self.hash_cls = hash_cls + self.key = key + if ctx is None: + self._ctx = self._backend.hmacs.create_ctx(key, self.hash_cls) + else: + self._ctx = ctx + + 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.hmacs.update_ctx(self._ctx, data) + + def copy(self): + return self.__class__(self.key, hash_cls=self.hash_cls, + backend=self._backend, ctx=self._copy_ctx()) + + def digest(self): + return self._backend.hmacs.finalize_ctx(self._copy_ctx(), + self.hash_cls.digest_size) + + def hexdigest(self): + return str(binascii.hexlify(self.digest()).decode("ascii")) + + def _copy_ctx(self): + return self._backend.hmacs.copy_ctx(self._ctx) diff --git a/docs/hazmat/primitives/hmac.rst b/docs/hazmat/primitives/hmac.rst new file mode 100644 index 00000000..993e3179 --- /dev/null +++ b/docs/hazmat/primitives/hmac.rst @@ -0,0 +1,50 @@ +.. danger:: + + This is a "Hazardous Materials" module. You should **ONLY** use it if + you're 100% absolutely sure that you know what you're doing because this + module is full of land mines, dragons, and dinosaurs with laser guns. + + +Hash-based Message Authentication Codes +======================================= + +.. testsetup:: + + import binascii + key = binascii.unhexlify(b"0" * 32) + +Hash-based message authentication codes (or HMACs) are a tool for calculating +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:: cryptography.primitives.hmac.HMAC(key, hash_cls, data=None) + + HMAC objects take a ``key``, a hash class derived from :class:`~cryptography.primitives.hashes.BaseHash`, + and optional initial data. The ``key`` should be randomly generated bytes and + the length of the ``block_size`` of the hash. You must keep the ``key`` secret. + + .. doctest:: + + >>> from cryptography.primitives import hashes, hmac + >>> h = hmac.HMAC(key, hashes.SHA1) + >>> h.update(b"message to hash") + >>> h.hexdigest() + '...' + + .. method:: update(data) + + :param bytes data: The bytes you wish to hash. + + .. method:: copy() + + :return: a new instance of this object with a copied internal state. + + .. method:: digest() + + :return bytes: The message digest as bytes. + + .. method:: hexdigest() + + :return str: The message digest as hex. + diff --git a/docs/hazmat/primitives/index.rst b/docs/hazmat/primitives/index.rst index 6ae769a6..3927f3f0 100644 --- a/docs/hazmat/primitives/index.rst +++ b/docs/hazmat/primitives/index.rst @@ -12,4 +12,5 @@ Primitives :maxdepth: 1 cryptographic-hashes + hmac symmetric-encryption diff --git a/tests/hazmat/primitives/test_hmac.py b/tests/hazmat/primitives/test_hmac.py new file mode 100644 index 00000000..e2b517ae --- /dev/null +++ b/tests/hazmat/primitives/test_hmac.py @@ -0,0 +1,53 @@ +# 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. + +from __future__ import absolute_import, division, print_function + +import pretend + +import pytest + +import six + +from cryptography.hazmat.primitives import hashes, hmac + +from .utils import generate_base_hmac_test + + +class TestHMAC(object): + test_copy = generate_base_hmac_test( + 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", hash_cls=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", hash_cls=hashes.SHA1, backend=backend, + data=b"") + assert isinstance(h.hexdigest(), str) + + +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", hashes.SHA1, backend=pretend_backend, + ctx=pretend_ctx) + assert h._backend is pretend_backend + assert h.copy()._backend is pretend_backend diff --git a/tests/hazmat/primitives/test_hmac_vectors.py b/tests/hazmat/primitives/test_hmac_vectors.py new file mode 100644 index 00000000..0754ab5e --- /dev/null +++ b/tests/hazmat/primitives/test_hmac_vectors.py @@ -0,0 +1,114 @@ +# 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. + +from __future__ import absolute_import, division, print_function + +import os + +from cryptography.hazmat.primitives import hashes + +from .utils import generate_hmac_test +from ...utils import load_hash_vectors_from_file + + +#TODO: find HMAC whirlpool vectors? + +class TestHMAC_MD5(object): + test_hmac_md5 = generate_hmac_test( + load_hash_vectors_from_file, + os.path.join("RFC", "HMAC"), + [ + "rfc-2202-md5.txt", + ], + hashes.MD5, + only_if=lambda backend: backend.hashes.supported(hashes.MD5), + skip_message="Does not support MD5", + ) + + +class TestHMAC_SHA1(object): + test_hmac_sha1 = generate_hmac_test( + load_hash_vectors_from_file, + os.path.join("RFC", "HMAC"), + [ + "rfc-2202-sha1.txt", + ], + hashes.SHA1, + only_if=lambda backend: backend.hashes.supported(hashes.SHA1), + skip_message="Does not support SHA1", + ) + + +class TestHMAC_SHA224(object): + test_hmac_sha224 = generate_hmac_test( + load_hash_vectors_from_file, + os.path.join("RFC", "HMAC"), + [ + "rfc-4231-sha224.txt", + ], + hashes.SHA224, + only_if=lambda backend: backend.hashes.supported(hashes.SHA224), + skip_message="Does not support SHA224", + ) + + +class TestHMAC_SHA256(object): + test_hmac_sha256 = generate_hmac_test( + load_hash_vectors_from_file, + os.path.join("RFC", "HMAC"), + [ + "rfc-4231-sha256.txt", + ], + hashes.SHA256, + only_if=lambda backend: backend.hashes.supported(hashes.SHA256), + skip_message="Does not support SHA256", + ) + + +class TestHMAC_SHA384(object): + test_hmac_sha384 = generate_hmac_test( + load_hash_vectors_from_file, + os.path.join("RFC", "HMAC"), + [ + "rfc-4231-sha384.txt", + ], + hashes.SHA384, + only_if=lambda backend: backend.hashes.supported(hashes.SHA384), + skip_message="Does not support SHA384", + ) + + +class TestHMAC_SHA512(object): + test_hmac_sha512 = generate_hmac_test( + load_hash_vectors_from_file, + os.path.join("RFC", "HMAC"), + [ + "rfc-4231-sha512.txt", + ], + hashes.SHA512, + only_if=lambda backend: backend.hashes.supported(hashes.SHA512), + skip_message="Does not support SHA512", + ) + + +class TestHMAC_RIPEMD160(object): + test_hmac_ripemd160 = generate_hmac_test( + load_hash_vectors_from_file, + os.path.join("RFC", "HMAC"), + [ + "rfc-2286-ripemd160.txt", + ], + hashes.RIPEMD160, + only_if=lambda backend: backend.hashes.supported(hashes.RIPEMD160), + skip_message="Does not support RIPEMD160", + ) diff --git a/tests/hazmat/primitives/test_utils.py b/tests/hazmat/primitives/test_utils.py index b7fa3d35..d7247e67 100644 --- a/tests/hazmat/primitives/test_utils.py +++ b/tests/hazmat/primitives/test_utils.py @@ -1,7 +1,8 @@ import pytest from .utils import ( - base_hash_test, encrypt_test, hash_test, long_string_hash_test + base_hash_test, encrypt_test, hash_test, long_string_hash_test, + base_hmac_test, hmac_test ) @@ -47,3 +48,25 @@ class TestLongHashTest(object): skip_message="message!" ) assert exc_info.value.args[0] == "message!" + + +class TestHMACTest(object): + def test_skips_if_only_if_returns_false(self): + with pytest.raises(pytest.skip.Exception) as exc_info: + hmac_test( + None, None, None, + only_if=lambda backend: False, + skip_message="message!" + ) + assert exc_info.value.args[0] == "message!" + + +class TestBaseHMACTest(object): + def test_skips_if_only_if_returns_false(self): + with pytest.raises(pytest.skip.Exception) as exc_info: + base_hmac_test( + None, None, + only_if=lambda backend: False, + skip_message="message!" + ) + assert exc_info.value.args[0] == "message!" diff --git a/tests/hazmat/primitives/utils.py b/tests/hazmat/primitives/utils.py index fabdca01..73a2469a 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 hmac from cryptography.hazmat.primitives.block import BlockCipher @@ -125,3 +126,57 @@ def long_string_hash_test(backend, hash_factory, md, only_if, skip_message): m = hash_factory(backend=backend) m.update(b"a" * 1000000) assert m.hexdigest() == md.lower() + + +def generate_hmac_test(param_loader, path, file_names, hash_cls, + only_if=None, skip_message=None): + def test_hmac(self): + for backend in _ALL_BACKENDS: + for file_name in file_names: + for params in param_loader(os.path.join(path, file_name)): + yield ( + hmac_test, + backend, + hash_cls, + params, + only_if, + skip_message + ) + return test_hmac + + +def hmac_test(backend, hash_cls, 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), hash_cls) + h.update(binascii.unhexlify(msg)) + assert h.hexdigest() == md + digest = hmac.HMAC(binascii.unhexlify(key), hash_cls, + data=binascii.unhexlify(msg)).hexdigest() + assert digest == md + + +def generate_base_hmac_test(hash_cls, only_if=None, skip_message=None): + def test_base_hmac(self): + for backend in _ALL_BACKENDS: + yield ( + base_hmac_test, + backend, + hash_cls, + only_if, + skip_message, + ) + return test_base_hmac + + +def base_hmac_test(backend, hash_cls, 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), hash_cls) + h_copy = h.copy() + assert h != h_copy + assert h._ctx != h_copy._ctx diff --git a/tests/test_utils.py b/tests/test_utils.py index f96cf004..db9ac085 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -411,6 +411,22 @@ def test_load_hash_vectors(): ] +def test_load_hmac_vectors(): + vector_data = textwrap.dedent(""" +Len = 224 +# "Jefe" +Key = 4a656665 +# "what do ya want for nothing?" +Msg = 7768617420646f2079612077616e7420666f72206e6f7468696e673f +MD = 750c783e6ab0b503eaa86e310a5db738 + """).splitlines() + assert load_hash_vectors(vector_data) == [ + (b"7768617420646f2079612077616e7420666f72206e6f7468696e673f", + "750c783e6ab0b503eaa86e310a5db738", + b"4a656665"), + ] + + def test_load_hash_vectors_bad_data(): vector_data = textwrap.dedent(""" # http://tools.ietf.org/html/rfc1321 diff --git a/tests/utils.py b/tests/utils.py index 9d01746a..a97cdf7a 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -136,6 +136,11 @@ def load_hash_vectors(vector_data): if line.startswith("Len"): length = int(line.split(" = ")[1]) + elif line.startswith("Key"): + """ + HMAC vectors contain a key attribute. Hash vectors do not. + """ + key = line.split(" = ")[1].encode("ascii") elif line.startswith("Msg"): """ In the NIST vectors they have chosen to represent an empty @@ -145,8 +150,11 @@ def load_hash_vectors(vector_data): msg = line.split(" = ")[1].encode("ascii") if length > 0 else b"" elif line.startswith("MD"): md = line.split(" = ")[1] - # after MD is found the Msg+MD tuple is complete - vectors.append((msg, md)) + # after MD is found the Msg+MD (+ potential key) tuple is complete + try: + vectors.append((msg, md, key)) + except: + vectors.append((msg, md)) else: raise ValueError("Unknown line in hash vector") return vectors -- cgit v1.2.3 From 64cadb367f2a533e828a030481fde9f0a46d7801 Mon Sep 17 00:00:00 2001 From: Paul Kehrer Date: Wed, 23 Oct 2013 00:17:34 -0500 Subject: cleanup context after finalizing --- cryptography/hazmat/bindings/openssl/backend.py | 1 + 1 file changed, 1 insertion(+) diff --git a/cryptography/hazmat/bindings/openssl/backend.py b/cryptography/hazmat/bindings/openssl/backend.py index 300495cb..db5a9e1e 100644 --- a/cryptography/hazmat/bindings/openssl/backend.py +++ b/cryptography/hazmat/bindings/openssl/backend.py @@ -287,6 +287,7 @@ class HMACs(object): buflen[0] = digest_size res = self._backend.lib.HMAC_Final(ctx, buf, buflen) assert res != 0 + self._backend.lib.HMAC_CTX_cleanup(ctx) return self._backend.ffi.buffer(buf)[:digest_size] def copy_ctx(self, ctx): -- cgit v1.2.3 From 6122d129e97efc49390bd2c41f644b85b1056cce Mon Sep 17 00:00:00 2001 From: Paul Kehrer Date: Wed, 23 Oct 2013 00:21:44 -0500 Subject: remove dangling todo --- tests/hazmat/primitives/test_hmac_vectors.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/hazmat/primitives/test_hmac_vectors.py b/tests/hazmat/primitives/test_hmac_vectors.py index 0754ab5e..81fe4d3e 100644 --- a/tests/hazmat/primitives/test_hmac_vectors.py +++ b/tests/hazmat/primitives/test_hmac_vectors.py @@ -21,8 +21,6 @@ from .utils import generate_hmac_test from ...utils import load_hash_vectors_from_file -#TODO: find HMAC whirlpool vectors? - class TestHMAC_MD5(object): test_hmac_md5 = generate_hmac_test( load_hash_vectors_from_file, -- cgit v1.2.3 From 00dd509f180b6229cfd4b913274a94df3bc05a00 Mon Sep 17 00:00:00 2001 From: Paul Kehrer Date: Wed, 23 Oct 2013 09:41:49 -0500 Subject: address initial review comments --- cryptography/hazmat/bindings/openssl/backend.py | 3 +-- tests/utils.py | 5 +++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cryptography/hazmat/bindings/openssl/backend.py b/cryptography/hazmat/bindings/openssl/backend.py index db5a9e1e..635d6a0c 100644 --- a/cryptography/hazmat/bindings/openssl/backend.py +++ b/cryptography/hazmat/bindings/openssl/backend.py @@ -283,8 +283,7 @@ class HMACs(object): def finalize_ctx(self, ctx, digest_size): buf = self._backend.ffi.new("unsigned char[]", digest_size) - buflen = self._backend.ffi.new("unsigned int *") - buflen[0] = digest_size + buflen = self._backend.ffi.new("unsigned int *", digest_size) res = self._backend.lib.HMAC_Final(ctx, buf, buflen) assert res != 0 self._backend.lib.HMAC_CTX_cleanup(ctx) diff --git a/tests/utils.py b/tests/utils.py index a97cdf7a..25291d55 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -127,6 +127,7 @@ def load_openssl_vectors(vector_data): def load_hash_vectors(vector_data): vectors = [] + key, msg, md = None, None, None for line in vector_data: line = line.strip() @@ -151,9 +152,9 @@ def load_hash_vectors(vector_data): elif line.startswith("MD"): md = line.split(" = ")[1] # after MD is found the Msg+MD (+ potential key) tuple is complete - try: + if key is not None: vectors.append((msg, md, key)) - except: + else: vectors.append((msg, md)) else: raise ValueError("Unknown line in hash vector") -- cgit v1.2.3 From 1bb8b710d444012b7218a08f098a85c4a31ca1bc Mon Sep 17 00:00:00 2001 From: Paul Kehrer Date: Sun, 27 Oct 2013 17:00:14 -0500 Subject: clean up loader and make docs default to hmac sha256 --- docs/hazmat/primitives/hmac.rst | 2 +- tests/utils.py | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/hazmat/primitives/hmac.rst b/docs/hazmat/primitives/hmac.rst index 993e3179..47b88030 100644 --- a/docs/hazmat/primitives/hmac.rst +++ b/docs/hazmat/primitives/hmac.rst @@ -27,7 +27,7 @@ message. .. doctest:: >>> from cryptography.primitives import hashes, hmac - >>> h = hmac.HMAC(key, hashes.SHA1) + >>> h = hmac.HMAC(key, hashes.SHA256) >>> h.update(b"message to hash") >>> h.hexdigest() '...' diff --git a/tests/utils.py b/tests/utils.py index 25291d55..ad676c04 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -127,7 +127,9 @@ def load_openssl_vectors(vector_data): def load_hash_vectors(vector_data): vectors = [] - key, msg, md = None, None, None + key = None + msg = None + md = None for line in vector_data: line = line.strip() @@ -154,8 +156,13 @@ def load_hash_vectors(vector_data): # after MD is found the Msg+MD (+ potential key) tuple is complete if key is not None: vectors.append((msg, md, key)) + key = None + msg = None + md = None else: vectors.append((msg, md)) + msg = None + md = None else: raise ValueError("Unknown line in hash vector") return vectors -- cgit v1.2.3 From 2824ab72d30e8423d17496e2c3baa47106505c8c Mon Sep 17 00:00:00 2001 From: Paul Kehrer Date: Mon, 28 Oct 2013 11:06:55 -0500 Subject: make hmac (mostly) compatible with stdlib hmac --- cryptography/hazmat/primitives/hmac.py | 24 ++++++++++++++---------- docs/hazmat/primitives/hmac.rst | 10 +++++----- tests/hazmat/primitives/test_hmac.py | 12 ++++++++---- tests/hazmat/primitives/utils.py | 20 ++++++++++---------- 4 files changed, 37 insertions(+), 29 deletions(-) diff --git a/cryptography/hazmat/primitives/hmac.py b/cryptography/hazmat/primitives/hmac.py index f635e36e..c417cd2e 100644 --- a/cryptography/hazmat/primitives/hmac.py +++ b/cryptography/hazmat/primitives/hmac.py @@ -19,34 +19,38 @@ import six class HMAC(object): - def __init__(self, key, hash_cls, data=None, ctx=None, backend=None): + def __init__(self, key, msg=None, digestmod=None, ctx=None, backend=None): super(HMAC, self).__init__() if backend is None: from cryptography.hazmat.bindings import _default_backend backend = _default_backend + + if digestmod is None: + raise ValueError("digestmod is a required argument") + self._backend = backend - self.hash_cls = hash_cls + self.digestmod = digestmod self.key = key if ctx is None: - self._ctx = self._backend.hmacs.create_ctx(key, self.hash_cls) + self._ctx = self._backend.hmacs.create_ctx(key, self.digestmod) else: self._ctx = ctx - if data is not None: - self.update(data) + if msg is not None: + self.update(msg) - def update(self, data): - if isinstance(data, six.text_type): + 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, data) + self._backend.hmacs.update_ctx(self._ctx, msg) def copy(self): - return self.__class__(self.key, hash_cls=self.hash_cls, + 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.hash_cls.digest_size) + self.digestmod.digest_size) def hexdigest(self): return str(binascii.hexlify(self.digest()).decode("ascii")) diff --git a/docs/hazmat/primitives/hmac.rst b/docs/hazmat/primitives/hmac.rst index 47b88030..76b7e24c 100644 --- a/docs/hazmat/primitives/hmac.rst +++ b/docs/hazmat/primitives/hmac.rst @@ -18,23 +18,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:: cryptography.primitives.hmac.HMAC(key, hash_cls, data=None) +.. class:: cryptography.primitives.hmac.HMAC(key, msg=None, digestmod=None) HMAC objects take a ``key``, a hash class derived from :class:`~cryptography.primitives.hashes.BaseHash`, - and optional initial data. The ``key`` should be randomly generated bytes and + and optional msg. The ``key`` should be randomly generated bytes and the length of the ``block_size`` of the hash. You must keep the ``key`` secret. .. doctest:: >>> from cryptography.primitives import hashes, hmac - >>> h = hmac.HMAC(key, hashes.SHA256) + >>> h = hmac.HMAC(key, digestmod=hashes.SHA256) >>> h.update(b"message to hash") >>> h.hexdigest() '...' - .. method:: update(data) + .. method:: update(msg) - :param bytes data: The bytes you wish to hash. + :param bytes msg The bytes you wish to hash. .. method:: copy() diff --git a/tests/hazmat/primitives/test_hmac.py b/tests/hazmat/primitives/test_hmac.py index e2b517ae..81d9ac86 100644 --- a/tests/hazmat/primitives/test_hmac.py +++ b/tests/hazmat/primitives/test_hmac.py @@ -32,22 +32,26 @@ class TestHMAC(object): ) def test_hmac_reject_unicode(self, backend): - h = hmac.HMAC(key=b"mykey", hash_cls=hashes.SHA1, backend=backend) + h = hmac.HMAC(key=b"mykey", digestmod=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", hash_cls=hashes.SHA1, backend=backend, - data=b"") + 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(ValueError): + 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", hashes.SHA1, backend=pretend_backend, + h = hmac.HMAC(b"key", digestmod=hashes.SHA1, backend=pretend_backend, ctx=pretend_ctx) assert h._backend is pretend_backend assert h.copy()._backend is pretend_backend diff --git a/tests/hazmat/primitives/utils.py b/tests/hazmat/primitives/utils.py index 73a2469a..c51fef52 100644 --- a/tests/hazmat/primitives/utils.py +++ b/tests/hazmat/primitives/utils.py @@ -93,11 +93,11 @@ def generate_base_hash_test(hash_cls, digest_size, block_size, return test_base_hash -def base_hash_test(backend, hash_cls, digest_size, block_size, only_if, +def base_hash_test(backend, digestmod, digest_size, block_size, only_if, skip_message): if only_if is not None and not only_if(backend): pytest.skip(skip_message) - m = hash_cls(backend=backend) + m = digestmod(backend=backend) assert m.digest_size == digest_size assert m.block_size == block_size m_copy = m.copy() @@ -128,7 +128,7 @@ def long_string_hash_test(backend, hash_factory, md, only_if, skip_message): assert m.hexdigest() == md.lower() -def generate_hmac_test(param_loader, path, file_names, hash_cls, +def generate_hmac_test(param_loader, path, file_names, digestmod, only_if=None, skip_message=None): def test_hmac(self): for backend in _ALL_BACKENDS: @@ -137,7 +137,7 @@ def generate_hmac_test(param_loader, path, file_names, hash_cls, yield ( hmac_test, backend, - hash_cls, + digestmod, params, only_if, skip_message @@ -145,17 +145,17 @@ def generate_hmac_test(param_loader, path, file_names, hash_cls, return test_hmac -def hmac_test(backend, hash_cls, params, only_if, skip_message): +def hmac_test(backend, digestmod, 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), hash_cls) + h = hmac.HMAC(binascii.unhexlify(key), digestmod=digestmod) h.update(binascii.unhexlify(msg)) assert h.hexdigest() == md - digest = hmac.HMAC(binascii.unhexlify(key), hash_cls, - data=binascii.unhexlify(msg)).hexdigest() + digest = hmac.HMAC(binascii.unhexlify(key), digestmod=digestmod, + msg=binascii.unhexlify(msg)).hexdigest() assert digest == md @@ -172,11 +172,11 @@ def generate_base_hmac_test(hash_cls, only_if=None, skip_message=None): return test_base_hmac -def base_hmac_test(backend, hash_cls, only_if, skip_message): +def base_hmac_test(backend, digestmod, 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), hash_cls) + h = hmac.HMAC(binascii.unhexlify(key), digestmod=digestmod) h_copy = h.copy() assert h != h_copy assert h._ctx != h_copy._ctx -- cgit v1.2.3 From 30eabddbade7647e0fb53500356e252eed245c6a Mon Sep 17 00:00:00 2001 From: Paul Kehrer Date: Mon, 28 Oct 2013 12:52:47 -0500 Subject: change type of exception raised, fix docs typo --- cryptography/hazmat/primitives/hmac.py | 2 +- docs/hazmat/primitives/hmac.rst | 2 +- tests/hazmat/primitives/test_hmac.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cryptography/hazmat/primitives/hmac.py b/cryptography/hazmat/primitives/hmac.py index c417cd2e..4da0cc3f 100644 --- a/cryptography/hazmat/primitives/hmac.py +++ b/cryptography/hazmat/primitives/hmac.py @@ -26,7 +26,7 @@ class HMAC(object): backend = _default_backend if digestmod is None: - raise ValueError("digestmod is a required argument") + raise TypeError("digestmod is a required argument") self._backend = backend self.digestmod = digestmod diff --git a/docs/hazmat/primitives/hmac.rst b/docs/hazmat/primitives/hmac.rst index 76b7e24c..14aaf19f 100644 --- a/docs/hazmat/primitives/hmac.rst +++ b/docs/hazmat/primitives/hmac.rst @@ -34,7 +34,7 @@ message. .. method:: update(msg) - :param bytes msg The bytes you wish to hash. + :param bytes msg: The bytes you wish to hash. .. method:: copy() diff --git a/tests/hazmat/primitives/test_hmac.py b/tests/hazmat/primitives/test_hmac.py index 81d9ac86..42726a7c 100644 --- a/tests/hazmat/primitives/test_hmac.py +++ b/tests/hazmat/primitives/test_hmac.py @@ -42,7 +42,7 @@ class TestHMAC(object): assert isinstance(h.hexdigest(), str) def test_hmac_no_digestmod(self): - with pytest.raises(ValueError): + with pytest.raises(TypeError): hmac.HMAC(key=b"shortkey") -- cgit v1.2.3 From bf8962a22b18e022085eec797ca64c1242564b21 Mon Sep 17 00:00:00 2001 From: Paul Kehrer Date: Mon, 28 Oct 2013 17:44:42 -0500 Subject: fix hmac docs to point to new hazmat location --- docs/hazmat/primitives/hmac.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/hazmat/primitives/hmac.rst b/docs/hazmat/primitives/hmac.rst index 14aaf19f..702df2c7 100644 --- a/docs/hazmat/primitives/hmac.rst +++ b/docs/hazmat/primitives/hmac.rst @@ -18,7 +18,7 @@ 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:: cryptography.primitives.hmac.HMAC(key, msg=None, digestmod=None) +.. class:: cryptography.hazmat.primitives.hmac.HMAC(key, msg=None, digestmod=None) HMAC objects take a ``key``, a hash class derived from :class:`~cryptography.primitives.hashes.BaseHash`, and optional msg. The ``key`` should be randomly generated bytes and @@ -26,7 +26,7 @@ message. .. doctest:: - >>> from cryptography.primitives import hashes, hmac + >>> from cryptography.hazmat.primitives import hashes, hmac >>> h = hmac.HMAC(key, digestmod=hashes.SHA256) >>> h.update(b"message to hash") >>> h.hexdigest() -- cgit v1.2.3 From ca8ed2953a1602fdceaee86d44b77d27f135926b Mon Sep 17 00:00:00 2001 From: Paul Kehrer Date: Mon, 28 Oct 2013 19:37:39 -0500 Subject: fix indentation error and wrapping in docs --- docs/hazmat/primitives/hmac.rst | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/hazmat/primitives/hmac.rst b/docs/hazmat/primitives/hmac.rst index 702df2c7..aec406b9 100644 --- a/docs/hazmat/primitives/hmac.rst +++ b/docs/hazmat/primitives/hmac.rst @@ -20,9 +20,10 @@ message. .. class:: cryptography.hazmat.primitives.hmac.HMAC(key, msg=None, digestmod=None) - HMAC objects take a ``key``, a hash class derived from :class:`~cryptography.primitives.hashes.BaseHash`, - and optional msg. The ``key`` should be randomly generated bytes and - the length of the ``block_size`` of the hash. You must keep the ``key`` secret. + HMAC objects take a ``key``, a hash class derived from + :class:`~cryptography.primitives.hashes.BaseHash`, and optional msg. The + ``key`` should be randomly generated bytes and the length of the + ``block_size`` of the hash. You must keep the ``key`` secret. .. doctest:: -- cgit v1.2.3 From 50a881572bc7617d4d49c4ae7b200c3bcb7398d9 Mon Sep 17 00:00:00 2001 From: Paul Kehrer Date: Tue, 29 Oct 2013 10:46:05 -0500 Subject: update hmac docs --- docs/hazmat/primitives/hmac.rst | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/hazmat/primitives/hmac.rst b/docs/hazmat/primitives/hmac.rst index aec406b9..bfbe3255 100644 --- a/docs/hazmat/primitives/hmac.rst +++ b/docs/hazmat/primitives/hmac.rst @@ -21,9 +21,10 @@ message. .. class:: cryptography.hazmat.primitives.hmac.HMAC(key, msg=None, digestmod=None) HMAC objects take a ``key``, a hash class derived from - :class:`~cryptography.primitives.hashes.BaseHash`, and optional msg. The - ``key`` should be randomly generated bytes and the length of the - ``block_size`` of the hash. You must keep the ``key`` secret. + :class:`~cryptography.primitives.hashes.BaseHash`, and optional message. + 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. .. doctest:: @@ -35,7 +36,7 @@ message. .. method:: update(msg) - :param bytes msg: The bytes you wish to hash. + :param bytes msg: The bytes to hash and authenticate. .. method:: copy() -- cgit v1.2.3