Skip to content

Commit 1b82c3d

Browse files
Fix OverflowError in ChaCha20 by using NumPy in-place operations
1 parent 2858fff commit 1b82c3d

File tree

1 file changed

+23
-11
lines changed

1 file changed

+23
-11
lines changed

pydatastructs/crypto/ChaCha20.py

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -78,21 +78,33 @@ def _quarter_round(self, state: np.ndarray, a: tuple, b: tuple, c: tuple, d: tup
7878
cx, cy = c
7979
dx, dy = d
8080

81-
state[ax, ay] = (state[ax, ay] + state[bx, by]) % (2**32)
81+
state[ax, ay] += state[bx, by]
8282
state[dx, dy] ^= state[ax, ay]
83-
state[dx, dy] = ((state[dx, dy] << 16) | (state[dx, dy] >> 16)) % (2**32)
83+
state[dx, dy] = np.bitwise_or(
84+
np.left_shift(state[dx, dy], 16),
85+
np.right_shift(state[dx, dy], 16)
86+
)
8487

85-
state[cx, cy] = (state[cx, cy] + state[dx, dy]) % (2**32)
88+
state[cx, cy] += state[dx, dy]
8689
state[bx, by] ^= state[cx, cy]
87-
state[bx, by] = ((state[bx, by] << 12) | (state[bx, by] >> 20)) % (2**32)
88-
89-
state[ax, ay] = (state[ax, ay] + state[bx, by]) % (2**32)
90-
state[dx, dy] ^= state[ax, ay]
91-
state[dx, dy] = ((state[dx, dy] << 8) | (state[dx, dy] >> 24)) % (2**32)
92-
93-
state[cx, cy] = (state[cx, cy] + state[dx, dy]) % (2**32)
90+
state[bx, by] = np.bitwise_or(
91+
np.left_shift(state[bx, by], 12),
92+
np.right_shift(state[bx, by], 20)
93+
)
94+
95+
state[ax, ay] += state[bx, by]
96+
state[dx, dy] ^= state[ax, ay]
97+
state[dx, dy] = np.bitwise_or(
98+
np.left_shift(state[dx, dy], 8),
99+
np.right_shift(state[dx, dy], 24)
100+
)
101+
102+
state[cx, cy] += state[dx, dy]
94103
state[bx, by] ^= state[cx, cy]
95-
state[bx, by] = ((state[bx, by] << 7) | (state[bx, by] >> 25)) % (2**32)
104+
state[bx, by] = np.bitwise_or(
105+
np.left_shift(state[bx, by], 7),
106+
np.right_shift(state[bx, by], 25)
107+
)
96108

97109
def _double_round(self, state: np.ndarray):
98110

0 commit comments

Comments
 (0)