From 31a163a29b6fee4185112f406afc35ef79db002b Mon Sep 17 00:00:00 2001 From: Tony Arcieri Date: Wed, 15 Jan 2020 07:10:31 -0800 Subject: [PATCH] chacha20: simplify software implementation The original implementation was unnecessarily complicated. This removes a bunch of needlessly complex code. This has no measurable effect on performance. --- chacha20/src/block/mod.rs | 70 +++++++++------------------------------ 1 file changed, 16 insertions(+), 54 deletions(-) diff --git a/chacha20/src/block/mod.rs b/chacha20/src/block/mod.rs index 80477767..d23a3de3 100644 --- a/chacha20/src/block/mod.rs +++ b/chacha20/src/block/mod.rs @@ -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] { 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 }