Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 16 additions & 54 deletions chacha20/src/block/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,66 +45,28 @@ impl Block {
],
};

block.rounds();
block.finish(key, iv, counter)
block.rounds(20)
}

/// Run the 20 rounds (i.e. 10 double rounds) of ChaCha20
#[inline]
fn rounds(&mut self) {
self.double_round();
self.double_round();
self.double_round();
self.double_round();
self.double_round();

self.double_round();
self.double_round();
self.double_round();
self.double_round();
self.double_round();
}

/// Double round function
#[inline]
fn double_round(&mut self) {
let state = &mut self.state;
quarter_round(0, 4, 8, 12, state);
quarter_round(1, 5, 9, 13, state);
quarter_round(2, 6, 10, 14, state);
quarter_round(3, 7, 11, 15, state);
quarter_round(0, 5, 10, 15, state);
quarter_round(1, 6, 11, 12, state);
quarter_round(2, 7, 8, 13, state);
quarter_round(3, 4, 9, 14, state);
}

/// Finish computing a block
#[inline]
fn finish(
self,
key: &[u32; KEY_WORDS],
iv: [u32; IV_WORDS],
counter: u64,
) -> [u32; STATE_WORDS] {
fn rounds(&mut self, count: usize) -> [u32; STATE_WORDS] {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additionally this parameterizes the number of rounds enabling the implementation of ChaCha8 and ChaCha12. Again, this comes at no cost to performance (or constant-time, as the number of rounds is a constant).

let mut state = self.state;

state[0] = state[0].wrapping_add(CONSTANTS[0]);
state[1] = state[1].wrapping_add(CONSTANTS[1]);
state[2] = state[2].wrapping_add(CONSTANTS[2]);
state[3] = state[3].wrapping_add(CONSTANTS[3]);
state[4] = state[4].wrapping_add(key[0]);
state[5] = state[5].wrapping_add(key[1]);
state[6] = state[6].wrapping_add(key[2]);
state[7] = state[7].wrapping_add(key[3]);
state[8] = state[8].wrapping_add(key[4]);
state[9] = state[9].wrapping_add(key[5]);
state[10] = state[10].wrapping_add(key[6]);
state[11] = state[11].wrapping_add(key[7]);
state[12] = state[12].wrapping_add((counter & 0xffff_ffff) as u32);
state[13] = state[13].wrapping_add(((counter >> 32) & 0xffff_ffff) as u32);
state[14] = state[14].wrapping_add(iv[0]);
state[15] = state[15].wrapping_add(iv[1]);
for _ in 0..(count / 2) {
quarter_round(0, 4, 8, 12, &mut state);
quarter_round(1, 5, 9, 13, &mut state);
quarter_round(2, 6, 10, 14, &mut state);
quarter_round(3, 7, 11, 15, &mut state);
quarter_round(0, 5, 10, 15, &mut state);
quarter_round(1, 6, 11, 12, &mut state);
quarter_round(2, 7, 8, 13, &mut state);
quarter_round(3, 4, 9, 14, &mut state);
}

for i in 0..16 {
state[i] = state[i].wrapping_add(self.state[i]);
}

state
}
Expand Down