Skip to content

Commit 44beace

Browse files
authored
chacha20: fix stream ID endianness (#389)
Fixes #388
1 parent 2ab56b0 commit 44beace

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

chacha20/src/rng.rs

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -116,15 +116,15 @@ pub struct StreamId([u32; 3]);
116116

117117
impl From<[u32; 3]> for StreamId {
118118
fn from(value: [u32; 3]) -> Self {
119-
Self(value)
119+
Self([value[0].to_le(), value[1].to_le(), value[2].to_le()])
120120
}
121121
}
122122

123123
impl From<[u8; 12]> for StreamId {
124124
fn from(value: [u8; 12]) -> Self {
125125
let mut result = Self([0u32; 3]);
126126
for (n, chunk) in result.0.iter_mut().zip(value.chunks_exact(4)) {
127-
*n = u32::from_le_bytes(chunk.try_into().unwrap())
127+
*n = u32::from_le_bytes(chunk.try_into().unwrap()).to_le();
128128
}
129129
result
130130
}
@@ -135,7 +135,7 @@ impl From<u128> for StreamId {
135135
let bytes = value.to_le_bytes();
136136
let mut result = Self([0u32; 3]);
137137
for (n, chunk) in result.0.iter_mut().zip(bytes[0..12].chunks_exact(4)) {
138-
*n = u32::from_le_bytes(chunk.try_into().unwrap());
138+
*n = u32::from_le_bytes(chunk.try_into().unwrap()).to_le();
139139
}
140140
result
141141
}
@@ -154,7 +154,7 @@ impl From<u32> for BlockPos {
154154

155155
impl From<[u8; 4]> for BlockPos {
156156
fn from(value: [u8; 4]) -> Self {
157-
Self(u32::from_le_bytes(value))
157+
Self(u32::from_le_bytes(value).to_le())
158158
}
159159
}
160160

@@ -345,6 +345,10 @@ macro_rules! impl_chacha_rng {
345345
#[inline]
346346
fn generate(&mut self, r: &mut Self::Results) {
347347
self.0.generate(&mut r.0);
348+
#[cfg(target_endian = "big")]
349+
for word in r.0.iter_mut() {
350+
*word = word.to_le();
351+
}
348352
}
349353
}
350354

@@ -438,7 +442,7 @@ macro_rules! impl_chacha_rng {
438442
#[inline]
439443
pub fn set_block_pos<B: Into<BlockPos>>(&mut self, block_pos: B) {
440444
self.core.reset();
441-
self.core.core.0.state[12] = block_pos.into().0
445+
self.core.core.0.state[12] = block_pos.into().0.to_le()
442446
}
443447

444448
/// Gets the block pos.
@@ -463,7 +467,7 @@ macro_rules! impl_chacha_rng {
463467
.iter_mut()
464468
.zip(stream.0.iter())
465469
{
466-
*n = *val;
470+
*n = val.to_le();
467471
}
468472
if self.core.index() != BUFFER_SIZE {
469473
self.core.generate_and_set(self.core.index());
@@ -1103,4 +1107,12 @@ pub(crate) mod tests {
11031107
assert_eq!(rng1.next_u64(), rng2.next_u64());
11041108
}
11051109
}
1110+
1111+
#[test]
1112+
fn stream_id_endianness() {
1113+
let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
1114+
rng.set_stream([3, 3333, 333333]);
1115+
let expected = 2059058063;
1116+
assert_eq!(rng.next_u32(), expected);
1117+
}
11061118
}

0 commit comments

Comments
 (0)