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

Ensure that secretbox can accept any bytes-like object as parameter #847

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 6 additions & 0 deletions src/nacl/bindings/crypto_secretbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ def crypto_secretbox(message: bytes, nonce: bytes, key: bytes) -> bytes:
if len(nonce) != crypto_secretbox_NONCEBYTES:
raise exc.ValueError("Invalid nonce")

nonce = ffi.from_buffer(nonce)
key = ffi.from_buffer(key)

padded = b"\x00" * crypto_secretbox_ZEROBYTES + message
ciphertext = ffi.new("unsigned char[]", len(padded))

Expand Down Expand Up @@ -72,6 +75,9 @@ def crypto_secretbox_open(
if len(nonce) != crypto_secretbox_NONCEBYTES:
raise exc.ValueError("Invalid nonce")

nonce = ffi.from_buffer(nonce)
key = ffi.from_buffer(key)

padded = b"\x00" * crypto_secretbox_BOXZEROBYTES + ciphertext
plaintext = ffi.new("unsigned char[]", len(padded))

Expand Down
19 changes: 19 additions & 0 deletions tests/test_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,25 @@ def test_secretbox_easy():
)


@pytest.mark.parametrize(
("encoder", "decoder"),
[
[bytes, bytearray],
[bytearray, bytes],
[bytearray, bytearray],
],
)
def test_secretbox_bytearray(encoder, decoder):
key = b"\x00" * c.crypto_secretbox_KEYBYTES
msg = b"message"
nonce = b"\x01" * c.crypto_secretbox_NONCEBYTES
ct = c.crypto_secretbox(encoder(msg), encoder(nonce), encoder(key))
assert len(ct) == len(msg) + c.crypto_secretbox_BOXZEROBYTES
assert tohex(ct) == "3ae84dfb89728737bd6e2c8cacbaf8af3d34cc1666533a"
msg2 = c.crypto_secretbox_open(decoder(ct), decoder(nonce), decoder(key))
assert msg2 == msg


def test_secretbox_wrong_length():
with pytest.raises(ValueError):
c.crypto_secretbox(b"", b"", b"")
Expand Down
Loading