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.hazmat.backends.interfaces import CipherBackend 12from cryptography.hazmat.primitives import keywrap 13 14 15@pytest.mark.requires_backend_interface(interface=CipherBackend) 16@pytest.mark.wycheproof_tests("kwp_test.json") 17def test_keywrap_with_padding(backend, wycheproof): 18 wrapping_key = binascii.unhexlify(wycheproof.testcase["key"]) 19 key_to_wrap = binascii.unhexlify(wycheproof.testcase["msg"]) 20 expected = binascii.unhexlify(wycheproof.testcase["ct"]) 21 22 result = keywrap.aes_key_wrap_with_padding( 23 wrapping_key, key_to_wrap, backend 24 ) 25 if wycheproof.valid or wycheproof.acceptable: 26 assert result == expected 27 28 if wycheproof.valid or (wycheproof.acceptable and not len(expected) < 16): 29 result = keywrap.aes_key_unwrap_with_padding( 30 wrapping_key, expected, backend 31 ) 32 assert result == key_to_wrap 33 else: 34 with pytest.raises(keywrap.InvalidUnwrap): 35 keywrap.aes_key_unwrap_with_padding( 36 wrapping_key, expected, backend 37 ) 38 39 40@pytest.mark.requires_backend_interface(interface=CipherBackend) 41@pytest.mark.wycheproof_tests("kw_test.json") 42def test_keywrap(backend, wycheproof): 43 wrapping_key = binascii.unhexlify(wycheproof.testcase["key"]) 44 key_to_wrap = binascii.unhexlify(wycheproof.testcase["msg"]) 45 expected = binascii.unhexlify(wycheproof.testcase["ct"]) 46 47 if wycheproof.valid or ( 48 wycheproof.acceptable 49 and wycheproof.testcase["comment"] != "invalid size of wrapped key" 50 ): 51 result = keywrap.aes_key_wrap(wrapping_key, key_to_wrap, backend) 52 assert result == expected 53 54 if wycheproof.valid or wycheproof.acceptable: 55 result = keywrap.aes_key_unwrap(wrapping_key, expected, backend) 56 assert result == key_to_wrap 57 else: 58 with pytest.raises(keywrap.InvalidUnwrap): 59 keywrap.aes_key_unwrap(wrapping_key, expected, backend) 60