From fd73e8b9a3eca60a394fd918c5d79ec4183953f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B2=81=E6=A0=91=E4=BA=BA?= Date: Sun, 15 Sep 2024 22:20:18 +0100 Subject: [PATCH] [kgm] refactor #2: slightly improve performance --- um_crypto/kgm/src/v3.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/um_crypto/kgm/src/v3.rs b/um_crypto/kgm/src/v3.rs index a3cf6da..451ff47 100644 --- a/um_crypto/kgm/src/v3.rs +++ b/um_crypto/kgm/src/v3.rs @@ -29,17 +29,27 @@ impl DecipherV3 { impl Decipher for DecipherV3 { fn decrypt(&self, buffer: &mut [u8], offset: usize) { - let slot_key_stream = self.slot_key.iter().cycle().skip(offset); - let file_key_stream = self.file_key.iter().cycle().skip(offset); + let slot_key_stream = self + .slot_key + .iter() + .cycle() + .skip(offset % self.slot_key.len()); + let file_key_stream = self + .file_key + .iter() + .cycle() + .skip(offset % self.file_key.len()); let mut offset = offset as u32; let key_stream = slot_key_stream.zip(file_key_stream); for (datum, (&slot_key, &file_key)) in buffer.iter_mut().zip(key_stream) { + let offset_key = offset.to_ne_bytes().iter().fold(0, |acc, &x| acc ^ x); + let mut temp = *datum; temp ^= file_key; temp ^= temp.wrapping_shl(4); temp ^= slot_key; - temp ^= offset.to_ne_bytes().iter().fold(0, |acc, &x| acc ^ x); + temp ^= offset_key; *datum = temp; offset = offset.wrapping_add(1);