Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

padding: Tip-toe around bytes subclasses. #5548

Merged
merged 1 commit into from
Nov 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/cryptography/hazmat/primitives/padding.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,10 @@ def _byte_padding_update(buffer_, data, block_size):

utils._check_byteslike("data", data)

buffer_ += bytes(data)
# six.PY2: Only coerce non-bytes objects to avoid triggering bad behavior
# of future's newbytes type. Unconditionally call bytes() after Python 2
# support is gone.
buffer_ += data if isinstance(data, bytes) else bytes(data)

finished_blocks = len(buffer_) // (block_size // 8)

Expand All @@ -66,7 +69,10 @@ def _byte_unpadding_update(buffer_, data, block_size):

utils._check_byteslike("data", data)

buffer_ += bytes(data)
# six.PY2: Only coerce non-bytes objects to avoid triggering bad behavior
# of future's newbytes type. Unconditionally call bytes() after Python 2
# support is gone.
buffer_ += data if isinstance(data, bytes) else bytes(data)

finished_blocks = max(len(buffer_) // (block_size // 8) - 1, 0)

Expand Down
24 changes: 24 additions & 0 deletions tests/hazmat/primitives/test_padding.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ def test_non_bytes(self):
with pytest.raises(TypeError):
unpadder.update(u"abc")

def test_zany_py2_bytes_subclass(self):
class mybytes(bytes): # noqa: N801
def __str__(self):
return "broken"

str(mybytes())
padder = padding.PKCS7(128).padder()
padder.update(mybytes(b"abc"))
unpadder = padding.PKCS7(128).unpadder()
unpadder.update(mybytes(padder.finalize()))
assert unpadder.finalize() == b"abc"

@pytest.mark.parametrize(
("size", "unpadded", "padded"),
[
Expand Down Expand Up @@ -154,6 +166,18 @@ def test_non_bytes(self):
with pytest.raises(TypeError):
unpadder.update(u"abc")

def test_zany_py2_bytes_subclass(self):
class mybytes(bytes): # noqa: N801
def __str__(self):
return "broken"

str(mybytes())
padder = padding.ANSIX923(128).padder()
padder.update(mybytes(b"abc"))
unpadder = padding.ANSIX923(128).unpadder()
unpadder.update(mybytes(padder.finalize()))
assert unpadder.finalize() == b"abc"

@pytest.mark.parametrize(
("size", "unpadded", "padded"),
[
Expand Down