• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 InvalidSignature
12from cryptography.hazmat.primitives import hashes, hmac
13
14
15_HMAC_ALGORITHMS = {
16    "HMACSHA1": hashes.SHA1(),
17    "HMACSHA224": hashes.SHA224(),
18    "HMACSHA256": hashes.SHA256(),
19    "HMACSHA384": hashes.SHA384(),
20    "HMACSHA512": hashes.SHA512(),
21    "HMACSHA3-224": hashes.SHA3_224(),
22    "HMACSHA3-256": hashes.SHA3_256(),
23    "HMACSHA3-384": hashes.SHA3_384(),
24    "HMACSHA3-512": hashes.SHA3_512(),
25}
26
27
28@pytest.mark.wycheproof_tests(
29    "hmac_sha1_test.json",
30    "hmac_sha224_test.json",
31    "hmac_sha256_test.json",
32    "hmac_sha384_test.json",
33    "hmac_sha3_224_test.json",
34    "hmac_sha3_256_test.json",
35    "hmac_sha3_384_test.json",
36    "hmac_sha3_512_test.json",
37    "hmac_sha512_test.json",
38)
39def test_hmac(backend, wycheproof):
40    hash_algo = _HMAC_ALGORITHMS[wycheproof.testfiledata["algorithm"]]
41    if wycheproof.testgroup["tagSize"] // 8 != hash_algo.digest_size:
42        pytest.skip("Truncated HMAC not supported")
43    if not backend.hash_supported(hash_algo):
44        pytest.skip("Hash {} not supported".format(hash_algo.name))
45
46    h = hmac.HMAC(
47        key=binascii.unhexlify(wycheproof.testcase["key"]),
48        algorithm=hash_algo,
49        backend=backend,
50    )
51    h.update(binascii.unhexlify(wycheproof.testcase["msg"]))
52
53    if wycheproof.invalid:
54        with pytest.raises(InvalidSignature):
55            h.verify(binascii.unhexlify(wycheproof.testcase["tag"]))
56    else:
57        tag = h.finalize()
58        assert tag == binascii.unhexlify(wycheproof.testcase["tag"])
59
60        h = hmac.HMAC(
61            key=binascii.unhexlify(wycheproof.testcase["key"]),
62            algorithm=hash_algo,
63            backend=backend,
64        )
65        h.update(binascii.unhexlify(wycheproof.testcase["msg"]))
66        h.verify(binascii.unhexlify(wycheproof.testcase["tag"]))
67