Skip to content

Commit 7f084e0

Browse files
Fix ChaCha20 key reuse test by truncating plaintexts to equal length
1 parent 24c4e6a commit 7f084e0

File tree

2 files changed

+7
-0
lines changed

2 files changed

+7
-0
lines changed

pydatastructs/crypto/ChaCha20.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,7 @@ def _apply_keystream(self, data: bytes) -> bytes:
167167
chunk = data[start:start + chunk_size]
168168
start += chunk_size
169169
keystream = self._chacha20_block(self.counter)
170+
170171
self.counter += 1
171172
xor_block = []
172173
for idx in range(len(chunk)):
@@ -188,6 +189,7 @@ def encrypt(self, plaintext: bytes) -> bytes:
188189
Returns:
189190
bytes: The resulting ciphertext.
190191
"""
192+
self.reset(counter=0)
191193
return self._apply_keystream(plaintext)
192194

193195
def decrypt(self, ciphertext: bytes) -> bytes:
@@ -203,6 +205,7 @@ def decrypt(self, ciphertext: bytes) -> bytes:
203205
Returns:
204206
bytes: The resulting plaintext.
205207
"""
208+
self.reset(counter=0)
206209
return self._apply_keystream(ciphertext)
207210

208211
def reset(self, counter: int = 0):

pydatastructs/crypto/tests/test_chacha20.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,10 @@ def test_key_reuse_simple():
9999

100100
plaintext1 = b"Hello, this is message one!"
101101
plaintext2 = b"Hi there, this is message two!"
102+
min_len = min(len(plaintext1), len(plaintext2))
103+
plaintext1 = plaintext1[:min_len]
104+
plaintext2 = plaintext2[:min_len]
105+
102106

103107
ciphertext1 = cipher1.encrypt(plaintext1)
104108
ciphertext2 = cipher2.encrypt(plaintext2)

0 commit comments

Comments
 (0)