Skip to content

Commit f903da0

Browse files
reaperhulkalex
authored andcommitted
fix bug with n % 8 length wrapping on AESKWP (pyca#4160)
* fix bug with n % 8 length wrapping on AESKWP * review feedback
1 parent 79748a9 commit f903da0

2 files changed

Lines changed: 31 additions & 2 deletions

File tree

src/cryptography/hazmat/primitives/keywrap.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,11 +118,16 @@ def aes_key_unwrap_with_padding(wrapping_key, wrapped_key, backend):
118118
b = (8 * n) - mli
119119
if (
120120
not bytes_eq(a[:4], b"\xa6\x59\x59\xa6") or not
121-
8 * (n - 1) < mli <= 8 * n or not bytes_eq(data[-b:], b"\x00" * b)
121+
8 * (n - 1) < mli <= 8 * n or (
122+
b != 0 and not bytes_eq(data[-b:], b"\x00" * b)
123+
)
122124
):
123125
raise InvalidUnwrap()
124126

125-
return data[:-b]
127+
if b == 0:
128+
return data
129+
else:
130+
return data[:-b]
126131

127132

128133
def aes_key_unwrap(wrapping_key, wrapped_key, backend):

tests/hazmat/primitives/test_keywrap.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,18 @@ def test_wrap(self, backend, params):
141141
)
142142
assert params["c"] == binascii.hexlify(wrapped_key)
143143

144+
@pytest.mark.parametrize(
145+
"params",
146+
_load_all_params("keywrap", ["kwp_botan.txt"], load_nist_vectors)
147+
)
148+
def test_wrap_additional_vectors(self, backend, params):
149+
wrapping_key = binascii.unhexlify(params["key"])
150+
key_to_wrap = binascii.unhexlify(params["input"])
151+
wrapped_key = keywrap.aes_key_wrap_with_padding(
152+
wrapping_key, key_to_wrap, backend
153+
)
154+
assert wrapped_key == binascii.unhexlify(params["output"])
155+
144156
@pytest.mark.parametrize(
145157
"params",
146158
_load_all_params(
@@ -163,6 +175,18 @@ def test_unwrap(self, backend, params):
163175
)
164176
assert params["p"] == binascii.hexlify(unwrapped_key)
165177

178+
@pytest.mark.parametrize(
179+
"params",
180+
_load_all_params("keywrap", ["kwp_botan.txt"], load_nist_vectors)
181+
)
182+
def test_unwrap_additional_vectors(self, backend, params):
183+
wrapping_key = binascii.unhexlify(params["key"])
184+
wrapped_key = binascii.unhexlify(params["output"])
185+
unwrapped_key = keywrap.aes_key_unwrap_with_padding(
186+
wrapping_key, wrapped_key, backend
187+
)
188+
assert unwrapped_key == binascii.unhexlify(params["input"])
189+
166190
def test_unwrap_invalid_wrapped_key_length(self, backend):
167191
# Keys to unwrap must be at least 16 bytes
168192
with pytest.raises(ValueError, match='Must be at least 16 bytes'):

0 commit comments

Comments
 (0)