Skip to content

Commit 83a4889

Browse files
Ensure that secretbox can accept any bytes-like object as parameter
1 parent 7752341 commit 83a4889

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/nacl/bindings/crypto_secretbox.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,9 @@ def crypto_secretbox(message: bytes, nonce: bytes, key: bytes) -> bytes:
4444
if len(nonce) != crypto_secretbox_NONCEBYTES:
4545
raise exc.ValueError("Invalid nonce")
4646

47+
nonce = ffi.from_buffer(nonce)
48+
key = ffi.from_buffer(key)
49+
4750
padded = b"\x00" * crypto_secretbox_ZEROBYTES + message
4851
ciphertext = ffi.new("unsigned char[]", len(padded))
4952

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

78+
nonce = ffi.from_buffer(nonce)
79+
key = ffi.from_buffer(key)
80+
7581
padded = b"\x00" * crypto_secretbox_BOXZEROBYTES + ciphertext
7682
plaintext = ffi.new("unsigned char[]", len(padded))
7783

tests/test_bindings.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,25 @@ def test_secretbox_easy():
9494
)
9595

9696

97+
@pytest.mark.parametrize(
98+
("encoder", "decoder"),
99+
[
100+
[bytes, bytearray],
101+
[bytearray, bytes],
102+
[bytearray, bytearray],
103+
],
104+
)
105+
def test_secretbox_bytearray(encoder, decoder):
106+
key = b"\x00" * c.crypto_secretbox_KEYBYTES
107+
msg = b"message"
108+
nonce = b"\x01" * c.crypto_secretbox_NONCEBYTES
109+
ct = c.crypto_secretbox(encoder(msg), encoder(nonce), encoder(key))
110+
assert len(ct) == len(msg) + c.crypto_secretbox_BOXZEROBYTES
111+
assert tohex(ct) == "3ae84dfb89728737bd6e2c8cacbaf8af3d34cc1666533a"
112+
msg2 = c.crypto_secretbox_open(decoder(ct), decoder(nonce), decoder(key))
113+
assert msg2 == msg
114+
115+
97116
def test_secretbox_wrong_length():
98117
with pytest.raises(ValueError):
99118
c.crypto_secretbox(b"", b"", b"")

0 commit comments

Comments
 (0)