Skip to content

Commit 4ea0c72

Browse files
Implement explicit np.uint32 conversions and modular addition using & 0xFFFFFFFF
1 parent 1b82c3d commit 4ea0c72

File tree

1 file changed

+18
-19
lines changed

1 file changed

+18
-19
lines changed

pydatastructs/crypto/ChaCha20.py

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -78,34 +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[bx, by]
81+
state[ax, ay] = ((state[ax, ay].astype(np.uint32) + state[bx, by].astype(np.uint32)) & 0xFFFFFFFF).astype(np.uint32)
8282
state[dx, dy] ^= state[ax, ay]
8383
state[dx, dy] = np.bitwise_or(
84-
np.left_shift(state[dx, dy], 16),
85-
np.right_shift(state[dx, dy], 16)
86-
)
84+
np.left_shift(state[dx, dy].astype(np.uint32), 16) & 0xFFFFFFFF,
85+
np.right_shift(state[dx, dy].astype(np.uint32), 16)
86+
)
8787

88-
state[cx, cy] += state[dx, dy]
88+
state[cx, cy] = ((state[cx, cy].astype(np.uint32) + state[dx, dy].astype(np.uint32)) & 0xFFFFFFFF).astype(np.uint32)
8989
state[bx, by] ^= state[cx, cy]
9090
state[bx, by] = np.bitwise_or(
91-
np.left_shift(state[bx, by], 12),
92-
np.right_shift(state[bx, by], 20)
93-
)
91+
np.left_shift(state[bx, by].astype(np.uint32), 12) & 0xFFFFFFFF,
92+
np.right_shift(state[bx, by].astype(np.uint32), 20)
93+
)
9494

95-
state[ax, ay] += state[bx, by]
96-
state[dx, dy] ^= state[ax, ay]
95+
state[ax, ay] = ((state[ax, ay].astype(np.uint32) + state[bx, by].astype(np.uint32)) & 0xFFFFFFFF).astype(np.uint32)
96+
state[dx, dy] ^= state[ax, ay]
9797
state[dx, dy] = np.bitwise_or(
98-
np.left_shift(state[dx, dy], 8),
99-
np.right_shift(state[dx, dy], 24)
100-
)
98+
np.left_shift(state[dx, dy].astype(np.uint32), 8) & 0xFFFFFFFF,
99+
np.right_shift(state[dx, dy].astype(np.uint32), 24)
100+
)
101101

102-
state[cx, cy] += state[dx, dy]
102+
state[cx, cy] = ((state[cx, cy].astype(np.uint32) + state[dx, dy].astype(np.uint32)) & 0xFFFFFFFF).astype(np.uint32)
103103
state[bx, by] ^= state[cx, cy]
104104
state[bx, by] = np.bitwise_or(
105-
np.left_shift(state[bx, by], 7),
106-
np.right_shift(state[bx, by], 25)
107-
)
108-
105+
np.left_shift(state[bx, by].astype(np.uint32), 7) & 0xFFFFFFFF,
106+
np.right_shift(state[bx, by].astype(np.uint32), 25)
107+
)
109108
def _double_round(self, state: np.ndarray):
110109

111110
self._quarter_round(state, (0, 0), (1, 0), (2, 0), (3, 0))
@@ -136,7 +135,7 @@ def _chacha20_block(self, counter: int) -> bytes:
136135
working_state = dp(state)
137136
for _ in range(10):
138137
self._double_round(working_state)
139-
final_state = (working_state + state) % (2**32)
138+
final_state = np.bitwise_and(working_state + state, np.uint32(0xFFFFFFFF))
140139
return struct.pack('<16I', *final_state.flatten())
141140

142141
def _apply_keystream(self, data: bytes) -> bytes:

0 commit comments

Comments
 (0)