1# This file is dual licensed under the terms of the Apache License, Version 2# 2.0, and the BSD License. See the LICENSE file in the root of this repository 3# for complete details. 4 5from __future__ import absolute_import, division, print_function 6 7import binascii 8 9import pytest 10 11from cryptography.exceptions import ( 12 AlreadyFinalized, 13 InvalidSignature, 14 _Reasons, 15) 16from cryptography.hazmat.backends.interfaces import HMACBackend 17from cryptography.hazmat.primitives import hashes, hmac 18 19from .utils import generate_base_hmac_test 20from ...doubles import DummyHashAlgorithm 21from ...utils import raises_unsupported_algorithm 22 23 24@pytest.mark.supported( 25 only_if=lambda backend: backend.hmac_supported(hashes.MD5()), 26 skip_message="Does not support MD5", 27) 28@pytest.mark.requires_backend_interface(interface=HMACBackend) 29class TestHMACCopy(object): 30 test_copy = generate_base_hmac_test( 31 hashes.MD5(), 32 ) 33 34 35@pytest.mark.requires_backend_interface(interface=HMACBackend) 36class TestHMAC(object): 37 def test_hmac_reject_unicode(self, backend): 38 h = hmac.HMAC(b"mykey", hashes.SHA1(), backend=backend) 39 with pytest.raises(TypeError): 40 h.update(u"\u00FC") 41 42 def test_hmac_algorithm_instance(self, backend): 43 with pytest.raises(TypeError): 44 hmac.HMAC(b"key", hashes.SHA1, backend=backend) 45 46 def test_raises_after_finalize(self, backend): 47 h = hmac.HMAC(b"key", hashes.SHA1(), backend=backend) 48 h.finalize() 49 50 with pytest.raises(AlreadyFinalized): 51 h.update(b"foo") 52 53 with pytest.raises(AlreadyFinalized): 54 h.copy() 55 56 with pytest.raises(AlreadyFinalized): 57 h.finalize() 58 59 def test_verify(self, backend): 60 h = hmac.HMAC(b"", hashes.SHA1(), backend=backend) 61 digest = h.finalize() 62 63 h = hmac.HMAC(b"", hashes.SHA1(), backend=backend) 64 h.verify(digest) 65 66 with pytest.raises(AlreadyFinalized): 67 h.verify(b"") 68 69 def test_invalid_verify(self, backend): 70 h = hmac.HMAC(b"", hashes.SHA1(), backend=backend) 71 with pytest.raises(InvalidSignature): 72 h.verify(b"") 73 74 with pytest.raises(AlreadyFinalized): 75 h.verify(b"") 76 77 def test_verify_reject_unicode(self, backend): 78 h = hmac.HMAC(b"", hashes.SHA1(), backend=backend) 79 with pytest.raises(TypeError): 80 h.verify(u"") 81 82 def test_unsupported_hash(self, backend): 83 with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH): 84 hmac.HMAC(b"key", DummyHashAlgorithm(), backend) 85 86 def test_buffer_protocol(self, backend): 87 key = bytearray(b"2b7e151628aed2a6abf7158809cf4f3c") 88 h = hmac.HMAC(key, hashes.SHA256(), backend) 89 h.update(bytearray(b"6bc1bee22e409f96e93d7e117393172a")) 90 assert h.finalize() == binascii.unhexlify( 91 b"a1bf7169c56a501c6585190ff4f07cad6e492a3ee187c0372614fb444b9fc3f0" 92 ) 93 94 95def test_invalid_backend(): 96 pretend_backend = object() 97 98 with raises_unsupported_algorithm(_Reasons.BACKEND_MISSING_INTERFACE): 99 hmac.HMAC(b"key", hashes.SHA1(), pretend_backend) 100