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 8import os 9 10import pytest 11 12from cryptography.hazmat.backends.interfaces import HashBackend 13from cryptography.hazmat.primitives import hashes 14from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF 15 16from ...doubles import DummyHashAlgorithm 17from ...utils import load_vectors_from_file, load_x963_vectors 18 19 20def _skip_hashfn_unsupported(backend, hashfn): 21 if not backend.hash_supported(hashfn): 22 pytest.skip( 23 "Hash {} is not supported by this backend {}".format( 24 hashfn.name, backend 25 ) 26 ) 27 28 29@pytest.mark.requires_backend_interface(interface=HashBackend) 30class TestX963(object): 31 _algorithms_dict = { 32 "SHA-1": hashes.SHA1, 33 "SHA-224": hashes.SHA224, 34 "SHA-256": hashes.SHA256, 35 "SHA-384": hashes.SHA384, 36 "SHA-512": hashes.SHA512, 37 } 38 39 @pytest.mark.parametrize( 40 ("vector"), 41 load_vectors_from_file( 42 os.path.join("KDF", "ansx963_2001.txt"), load_x963_vectors 43 ), 44 ) 45 def test_x963(self, backend, vector): 46 hashfn = self._algorithms_dict[vector["hash"]] 47 _skip_hashfn_unsupported(backend, hashfn()) 48 49 key = binascii.unhexlify(vector["Z"]) 50 sharedinfo = None 51 if vector["sharedinfo_length"] != 0: 52 sharedinfo = binascii.unhexlify(vector["sharedinfo"]) 53 key_data_len = vector["key_data_length"] // 8 54 key_data = binascii.unhexlify(vector["key_data"]) 55 56 xkdf = X963KDF( 57 algorithm=hashfn(), 58 length=key_data_len, 59 sharedinfo=sharedinfo, 60 backend=backend, 61 ) 62 xkdf.verify(key, key_data) 63 64 def test_unsupported_hash(self, backend): 65 with pytest.raises(pytest.skip.Exception): 66 _skip_hashfn_unsupported(backend, DummyHashAlgorithm()) 67