From 8fb8bd9735c7dd22200f706ed3898f1764429b19 Mon Sep 17 00:00:00 2001 From: bing Date: Tue, 2 Jul 2024 13:21:45 +0800 Subject: [PATCH 01/15] feat: AES decryption --- src/encryption/symmetric/aes/mod.rs | 173 +++++++++++++++++++++++--- src/encryption/symmetric/aes/sbox.rs | 23 ++++ src/encryption/symmetric/aes/tests.rs | 21 +++- 3 files changed, 193 insertions(+), 24 deletions(-) diff --git a/src/encryption/symmetric/aes/mod.rs b/src/encryption/symmetric/aes/mod.rs index ee14c0e..e430f41 100644 --- a/src/encryption/symmetric/aes/mod.rs +++ b/src/encryption/symmetric/aes/mod.rs @@ -8,7 +8,7 @@ pub mod sbox; #[cfg(test)] pub mod tests; use super::SymmetricEncryption; -use crate::encryption::symmetric::aes::sbox::SBOX; +use crate::encryption::symmetric::aes::sbox::{INVERSE_SBOX, SBOX}; /// A block in AES represents a 128-bit sized message data. pub type Block = [u8; 16]; @@ -72,7 +72,16 @@ where [(); N / 8]: Self::aes_encrypt(plaintext, key, num_rounds) } - fn decrypt(_key: &Self::Key, _ciphertext: &Self::Block) -> Self::Block { unimplemented!() } + fn decrypt(key: &Self::Key, ciphertext: &Self::Block) -> Self::Block { + let num_rounds = match N { + 128 => 10, + 192 => 12, + 256 => 14, + _ => panic!("AES only supports key sizes 128, 192 and 256 bits. You provided: {N}"), + }; + + Self::aes_decrypt(ciphertext, key, num_rounds) + } } /// Contains the values given by [x^(i-1), {00}, {00}, {00}], with x^(i-1) @@ -156,6 +165,50 @@ where [(); N / 8]: state.0.into_iter().flatten().collect::>().try_into().unwrap() } + /// Performs the cipher, with key size of `N` (in bits), as seen in Figure 5 of the document + /// linked in the front-page. + fn aes_decrypt(ciphertext: &[u8; 16], key: &Key, num_rounds: usize) -> Block { + assert!(!key.is_empty(), "Key is not instantiated"); + + let key_len_words = N / 32; + let mut round_keys_words = Vec::with_capacity(key_len_words * (num_rounds + 1)); + Self::key_expansion(*key, &mut round_keys_words, key_len_words, num_rounds); + let mut round_keys = round_keys_words.chunks_exact(4).rev(); + + let mut state = State( + ciphertext + .chunks(4) + .map(|c| c.try_into().unwrap()) + .collect::>() + .try_into() + .unwrap(), + ); + assert!(state != State::default(), "State is not instantiated"); + + // Round 0 - add round key + Self::add_round_key(&mut state, round_keys.next().unwrap()); + + // Rounds 1 to N - 1 + for _ in 1..num_rounds { + Self::inv_shift_rows(&mut state); + Self::inv_sub_bytes(&mut state); + Self::add_round_key(&mut state, round_keys.next().unwrap()); + Self::inv_mix_columns(&mut state); + } + + // Last round - we do not mix columns here. + Self::inv_shift_rows(&mut state); + Self::inv_sub_bytes(&mut state); + Self::add_round_key(&mut state, round_keys.next().unwrap()); + + assert!( + round_keys.next().is_none(), + "Round keys not fully consumed - perhaps check key expansion?" + ); + + state.0.into_iter().flatten().collect::>().try_into().unwrap() + } + /// XOR a round key to its internal state. fn add_round_key(state: &mut State, round_key: &[[u8; 4]]) { for (col, word) in state.0.iter_mut().zip(round_key.iter()) { @@ -165,6 +218,16 @@ where [(); N / 8]: } } + /// Substitutes each byte [s_0, s_1, ..., s_15] with another byte according to a substitution box + /// (usually referred to as an S-box). + fn inv_sub_bytes(state: &mut State) { + for i in 0..4 { + for j in 0..4 { + state.0[i][j] = INVERSE_SBOX[state.0[i][j] as usize]; + } + } + } + /// Substitutes each byte [s_0, s_1, ..., s_15] with another byte according to a substitution box /// (usually referred to as an S-box). fn sub_bytes(state: &mut State) { @@ -190,8 +253,35 @@ where [(); N / 8]: (0..len).map(|_| iters.iter_mut().map(|n| n.next().unwrap()).collect::>()).collect(); for (r, i) in transposed.iter_mut().zip(0..4) { - let (left, right) = r.split_at(i); - *r = [right.to_vec(), left.to_vec()].concat(); + r.rotate_left(i); + } + let mut iters: Vec<_> = transposed.into_iter().map(|n| n.into_iter()).collect(); + + state.0 = (0..len) + .map(|_| iters.iter_mut().map(|n| n.next().unwrap()).collect::>().try_into().unwrap()) + .collect::>() + .try_into() + .unwrap(); + } + + /// The inverse of [`Self::shift_rows`]. + /// + /// Shift i-th row of i positions, for i ranging from 0 to 3. + /// + /// For row 0, no shifting occurs, for row 1, a right shift of 1 index occurs, .. + /// + /// Note that since our state is in column-major form, we transpose the state to a + /// row-major form to make this step simpler. + fn inv_shift_rows(state: &mut State) { + let len = state.0.len(); + let mut iters: Vec<_> = state.0.into_iter().map(|n| n.into_iter()).collect(); + + // Transpose to row-major form + let mut transposed: Vec<_> = + (0..len).map(|_| iters.iter_mut().map(|n| n.next().unwrap()).collect::>()).collect(); + + for (r, i) in transposed.iter_mut().zip(0..4) { + r.rotate_right(i); } let mut iters: Vec<_> = transposed.into_iter().map(|n| n.into_iter()).collect(); @@ -211,27 +301,74 @@ where [(); N / 8]: fn mix_columns(state: &mut State) { for col in state.0.iter_mut() { let tmp = *col; - let mut col_doubled = *col; - - // Perform the matrix multiplication in GF(2^8). - // We process the multiplications first, so we can just do additions later. - for (i, c) in col_doubled.iter_mut().enumerate() { - let hi_bit = col[i] >> 7; - *c = col[i] << 1; - *c ^= hi_bit * 0x1B; // This XOR brings the column back into the field if an - // overflow occurs (ie. hi_bit == 1) - } // Do all additions (XORs) here. // 2a0 + 3a1 + a2 + a3 - col[0] = col_doubled[0] ^ tmp[3] ^ tmp[2] ^ col_doubled[1] ^ tmp[1]; + col[0] = Self::multiply(tmp[0], 2) ^ tmp[3] ^ tmp[2] ^ Self::multiply(tmp[1], 3); // a0 + 2a1 + 3a2 + a3 - col[1] = col_doubled[1] ^ tmp[0] ^ tmp[3] ^ col_doubled[2] ^ tmp[2]; + col[1] = Self::multiply(tmp[1], 2) ^ tmp[0] ^ tmp[3] ^ Self::multiply(tmp[2], 3); // a0 + a1 + 2a2 + 3a3 - col[2] = col_doubled[2] ^ tmp[1] ^ tmp[0] ^ col_doubled[3] ^ tmp[3]; + col[2] = Self::multiply(tmp[2], 2) ^ tmp[1] ^ tmp[0] ^ Self::multiply(tmp[3], 3); // 3a0 + a1 + a2 + 2a3 - col[3] = col_doubled[3] ^ tmp[2] ^ tmp[1] ^ col_doubled[0] ^ tmp[0]; + col[3] = Self::multiply(tmp[3], 2) ^ tmp[2] ^ tmp[1] ^ Self::multiply(tmp[0], 3); + } + } + + /// The inverse of [`Self::mix_columns`]. + /// + /// Applies the same linear transformation to each of the four columns of the state. + /// + /// Mix columns is done as such: + /// + /// Each column of bytes is treated as a 4-term polynomial, multiplied modulo x^4 + 1 with a + /// fixed polynomial a(x) = 3x^3 + x^2 + x + 2. This is done using matrix multiplication. + fn inv_mix_columns(state: &mut State) { + for col in state.0.iter_mut() { + let tmp = *col; + + // Do all additions (XORs) here. + // 2a0 + 3a1 + a2 + a3 + col[0] = Self::multiply(tmp[0], 0x0e) + ^ Self::multiply(tmp[3], 0x09) + ^ Self::multiply(tmp[2], 0x0d) + ^ Self::multiply(tmp[1], 0x0b); + // a0 + 2a1 + 3a2 + a3 + col[1] = Self::multiply(tmp[1], 0x0e) + ^ Self::multiply(tmp[0], 0x09) + ^ Self::multiply(tmp[3], 0x0d) + ^ Self::multiply(tmp[2], 0x0b); + // a0 + a1 + 2a2 + 3a3 + col[2] = Self::multiply(tmp[2], 0x0e) + ^ Self::multiply(tmp[1], 0x09) + ^ Self::multiply(tmp[0], 0x0d) + ^ Self::multiply(tmp[3], 0x0b); + // 3a0 + a1 + a2 + 2a3 + col[3] = Self::multiply(tmp[3], 0x0e) + ^ Self::multiply(tmp[2], 0x09) + ^ Self::multiply(tmp[1], 0x0d) + ^ Self::multiply(tmp[0], 0x0b); + } + } + + fn multiply(col: u8, multiplicant: usize) -> u8 { + let mut product = 0; + let mut col = col; + let mut mult = multiplicant; + + for _ in 0..8 { + if mult & 1 == 1 { + product ^= col; + } + + let hi_bit = col & 0x80; + col <<= 1; + if hi_bit == 0x80 { + col ^= 0x1B; + } + + mult >>= 1; } + return product & 0xFF; } /// In AES, rotword() is just a one-byte left circular shift. diff --git a/src/encryption/symmetric/aes/sbox.rs b/src/encryption/symmetric/aes/sbox.rs index 3fb8d62..8ed8a76 100644 --- a/src/encryption/symmetric/aes/sbox.rs +++ b/src/encryption/symmetric/aes/sbox.rs @@ -37,3 +37,26 @@ pub(crate) const SBOX: [u8; 256] = [ 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16, ]; + +/// An inverse substitution box for an instance of [`AES`](super::AES). +/// +/// Since substitution involves mapping a single byte (m = 8) into another (n = 8), we have a +/// lookup table of size 2^8 = 256 of 8 bits per index, implemented as a linear array. +pub(crate) const INVERSE_SBOX: [u8; 256] = [ + 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, + 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, + 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, + 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, + 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, + 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, + 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, + 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, + 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, + 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, + 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, + 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, + 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, + 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, + 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, + 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d, +]; diff --git a/src/encryption/symmetric/aes/tests.rs b/src/encryption/symmetric/aes/tests.rs index 44203e0..b3e02d7 100644 --- a/src/encryption/symmetric/aes/tests.rs +++ b/src/encryption/symmetric/aes/tests.rs @@ -14,11 +14,14 @@ fn test_aes_128() { let state = AES::encrypt(&key, &plaintext); - let expected_state = Block::from([ + let expected_ciphertext = Block::from([ 0x69, 0xc4, 0xe0, 0xd8, 0x6a, 0x7b, 0x04, 0x30, 0xd8, 0xcd, 0xb7, 0x80, 0x70, 0xb4, 0xc5, 0x5a, ]); - assert_eq!(state, expected_state); + assert_eq!(state, expected_ciphertext); + + let decrypted = AES::decrypt(&key, &state); + assert_eq!(decrypted, plaintext); } #[test] @@ -35,11 +38,14 @@ fn test_aes_192() { let state = AES::encrypt(&key, &plaintext); - let expected_state = Block::from([ + let expected_ciphertext = Block::from([ 0xdd, 0xa9, 0x7c, 0xa4, 0x86, 0x4c, 0xdf, 0xe0, 0x6e, 0xaf, 0x70, 0xa0, 0xec, 0x0d, 0x71, 0x91, ]); - assert_eq!(state, expected_state); + assert_eq!(state, expected_ciphertext); + + let decrypted = AES::decrypt(&key, &state); + assert_eq!(decrypted, plaintext); } #[test] @@ -56,9 +62,12 @@ fn test_aes_256() { let state = AES::encrypt(&key, &plaintext); - let expected_state = Block::from([ + let expected_ciphertext = Block::from([ 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89, ]); - assert_eq!(state, expected_state); + assert_eq!(state, expected_ciphertext); + + let decrypted = AES::decrypt(&key, &state); + assert_eq!(decrypted, plaintext); } From c70b218590c76ce2e816626d629b3db639de1abc Mon Sep 17 00:00:00 2001 From: bing Date: Tue, 2 Jul 2024 14:53:59 +0800 Subject: [PATCH 02/15] cleanup --- src/encryption/symmetric/aes/mod.rs | 55 +++++++++++++++++++++-------- 1 file changed, 40 insertions(+), 15 deletions(-) diff --git a/src/encryption/symmetric/aes/mod.rs b/src/encryption/symmetric/aes/mod.rs index e430f41..352e8f4 100644 --- a/src/encryption/symmetric/aes/mod.rs +++ b/src/encryption/symmetric/aes/mod.rs @@ -72,6 +72,24 @@ where [(); N / 8]: Self::aes_encrypt(plaintext, key, num_rounds) } + /// Decrypt a ciphertext of size [`Block`] with a [`Key`] of size `N`-bits. + /// + /// ## Example + /// ```rust + /// #![feature(generic_const_exprs)] + /// + /// use rand::{thread_rng, Rng}; + /// use ronkathon::encryption::symmetric::{ + /// aes::{Key, AES}, + /// SymmetricEncryption, + /// }; + /// + /// let mut rng = thread_rng(); + /// let key = Key::<128>::new(rng.gen()); + /// let plaintext = rng.gen(); + /// let encrypted = AES::encrypt(&key, &plaintext); + /// let decrypted = AES::decrypt(&key, &plaintext); + /// ``` fn decrypt(key: &Self::Key, ciphertext: &Self::Block) -> Self::Block { let num_rounds = match N { 128 => 10, @@ -165,14 +183,15 @@ where [(); N / 8]: state.0.into_iter().flatten().collect::>().try_into().unwrap() } - /// Performs the cipher, with key size of `N` (in bits), as seen in Figure 5 of the document - /// linked in the front-page. + /// Deciphers a given `ciphertext`, with key size of `N` (in bits), as seen in Figure 5 of the + /// document linked in the front-page. fn aes_decrypt(ciphertext: &[u8; 16], key: &Key, num_rounds: usize) -> Block { assert!(!key.is_empty(), "Key is not instantiated"); let key_len_words = N / 32; let mut round_keys_words = Vec::with_capacity(key_len_words * (num_rounds + 1)); Self::key_expansion(*key, &mut round_keys_words, key_len_words, num_rounds); + // For decryption; we use the round keys from the back, so we iterate from the back here. let mut round_keys = round_keys_words.chunks_exact(4).rev(); let mut state = State( @@ -220,27 +239,30 @@ where [(); N / 8]: /// Substitutes each byte [s_0, s_1, ..., s_15] with another byte according to a substitution box /// (usually referred to as an S-box). - fn inv_sub_bytes(state: &mut State) { + fn sub_bytes(state: &mut State) { for i in 0..4 { for j in 0..4 { - state.0[i][j] = INVERSE_SBOX[state.0[i][j] as usize]; + state.0[i][j] = SBOX[state.0[i][j] as usize]; } } } /// Substitutes each byte [s_0, s_1, ..., s_15] with another byte according to a substitution box /// (usually referred to as an S-box). - fn sub_bytes(state: &mut State) { + /// + /// Note that the only difference here from [`Self::sub_bytes`] is that we use a different + /// substitution box [`INVERSE_SBOX`], which is derived differently. + fn inv_sub_bytes(state: &mut State) { for i in 0..4 { for j in 0..4 { - state.0[i][j] = SBOX[state.0[i][j] as usize]; + state.0[i][j] = INVERSE_SBOX[state.0[i][j] as usize]; } } } /// Shift i-th row of i positions, for i ranging from 0 to 3. /// - /// For row 0, no shifting occurs, for row 1, a left shift of 1 index occurs, .. + /// For row 0, no shifting occurs, for row 1, a **left** shift of 1 index occurs, .. /// /// Note that since our state is in column-major form, we transpose the state to a /// row-major form to make this step simpler. @@ -268,7 +290,7 @@ where [(); N / 8]: /// /// Shift i-th row of i positions, for i ranging from 0 to 3. /// - /// For row 0, no shifting occurs, for row 1, a right shift of 1 index occurs, .. + /// For row 0, no shifting occurs, for row 1, a **right** shift of 1 index occurs, .. /// /// Note that since our state is in column-major form, we transpose the state to a /// row-major form to make this step simpler. @@ -302,7 +324,6 @@ where [(); N / 8]: for col in state.0.iter_mut() { let tmp = *col; - // Do all additions (XORs) here. // 2a0 + 3a1 + a2 + a3 col[0] = Self::multiply(tmp[0], 2) ^ tmp[3] ^ tmp[2] ^ Self::multiply(tmp[1], 3); // a0 + 2a1 + 3a2 + a3 @@ -321,28 +342,32 @@ where [(); N / 8]: /// Mix columns is done as such: /// /// Each column of bytes is treated as a 4-term polynomial, multiplied modulo x^4 + 1 with a - /// fixed polynomial a(x) = 3x^3 + x^2 + x + 2. This is done using matrix multiplication. + /// fixed polynomial a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}, where {xy} represents a + /// hexadecimal number, x being the higher 4 bits, and y being the lower 4 bits. + /// + /// eg: {0b} == 0000_1011 == 11 + /// + /// This is done using matrix multiplication. fn inv_mix_columns(state: &mut State) { for col in state.0.iter_mut() { let tmp = *col; - // Do all additions (XORs) here. - // 2a0 + 3a1 + a2 + a3 + // {0e}a0 + {0b}a1 + {0d}a2 + {09}a3 col[0] = Self::multiply(tmp[0], 0x0e) ^ Self::multiply(tmp[3], 0x09) ^ Self::multiply(tmp[2], 0x0d) ^ Self::multiply(tmp[1], 0x0b); - // a0 + 2a1 + 3a2 + a3 + // {09}a0 + {0e}a1 + {0b}a2 + {0d}a3 col[1] = Self::multiply(tmp[1], 0x0e) ^ Self::multiply(tmp[0], 0x09) ^ Self::multiply(tmp[3], 0x0d) ^ Self::multiply(tmp[2], 0x0b); - // a0 + a1 + 2a2 + 3a3 + // {0d}a0 + {09}a1 + {0e}a2 + {0b}a3 col[2] = Self::multiply(tmp[2], 0x0e) ^ Self::multiply(tmp[1], 0x09) ^ Self::multiply(tmp[0], 0x0d) ^ Self::multiply(tmp[3], 0x0b); - // 3a0 + a1 + a2 + 2a3 + // {0b}3a0 + {0d}a1 + {09}a2 + {0e}a3 col[3] = Self::multiply(tmp[3], 0x0e) ^ Self::multiply(tmp[2], 0x09) ^ Self::multiply(tmp[1], 0x0d) From a87dbcaed94917c562230bf4809013645b87e604 Mon Sep 17 00:00:00 2001 From: bing Date: Tue, 2 Jul 2024 15:19:32 +0800 Subject: [PATCH 03/15] docs: update README for aes decryption --- src/encryption/symmetric/aes/README.md | 41 ++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/src/encryption/symmetric/aes/README.md b/src/encryption/symmetric/aes/README.md index a5f4e39..8c8a2ce 100644 --- a/src/encryption/symmetric/aes/README.md +++ b/src/encryption/symmetric/aes/README.md @@ -14,15 +14,20 @@ Unlike DES, it does not use a Feistel network, and most AES calculations are don ## Algorithm The core encryption algorithm consists of the following routines: -- [KeyExpansion](#KeyExpansion) -- [AddRoundKey](#AddRoundKey) + +- [KeyExpansion][keyexp] +- [AddRoundKey][arc] - [SubBytes](#SubBytes) - [ShiftRows](#ShiftRows) - [MixColumns](#MixColumns) -For decryption, we take the inverses of these routines: +For decryption, we take the inverses of these following routines: + +- [InvSubBytes](#InvSubBytes) +- [InvShiftRows](#InvShiftRows) +- [InvMixColumns](#InvMixColumns) -TODO +Note that we do not need the inverses of [KeyExpansion][keyexp] or [AddRoundKey][arc], since for decryption we're simply using the round keys from the last to the first, and [AddRoundKey][arc] is its own inverse. ### Encryption @@ -75,7 +80,7 @@ Substitutes each byte in the `State` with another byte according to a [substitut #### ShiftRow -Shift i-th row of i positions, for i ranging from 0 to 3, eg. Row 0: no shift occurs, row 1: a left shift of 1 position occurs. +Do a **left** shift i-th row of i positions, for i ranging from 0 to 3, eg. Row 0: no shift occurs, row 1: a left shift of 1 position occurs. #### MixColumns @@ -87,7 +92,29 @@ More details can be found [here][mixcolumns]. ### Decryption -TODO +For decryption, we use the inverses of some of the above routines to decrypt a ciphertext. To reiterate, we do not need the inverses of [KeyExpansion][keyexp] or [AddRoundKey][arc], since for decryption we're simply using the round keys from the last to the first, and [AddRoundKey][arc] is its own inverse. + + +#### InvSubBytes + +Substitutes each byte in the `State` with another byte according to a [substitution box](#substitution-box). Note that the only difference here is that the substitution box used in decryption is derived differently from the version used in encryption. + +#### InvShiftRows + +Do a **right** shift i-th row of i positions, for i ranging from 0 to 3, eg. Row 0: no shift occurs, row 1: a right shift of 1 position occurs. + +Substitutes each byte in the `State` with another byte according to a [substitution box](#substitution-box). Note that the only difference here is that the substitution box used in decryption is derived differently from the version used in encryption. + + +#### InvMixColumns + +Each column of bytes is treated as a 4-term polynomial, multiplied modulo x^4 + 1 with the inverse of the fixed polynomial +a(x) = 3x^3 + x^2 + x + 2 found in the [MixColumns] step. The inverse of a(x) is a^-1(x) = 11x^3 + 13x^2 + 9x + 14. + +This is multiplication is done using matrix multiplication. + +More details can be found [here][mixcolumns]. + ## Substitution Box @@ -117,6 +144,8 @@ In production-level AES code, fast AES software uses special techniques called t [des]: ../des/README.md [spn]: https://en.wikipedia.org/wiki/Substitution%E2%80%93permutation_network [slide attacks]: https://en.wikipedia.org/wiki/Slide_attack +[keyexp]: #KeyExpansion +[arc]: #AddRoundKey [mixcolumns]: https://en.wikipedia.org/wiki/Rijndael_MixColumns [Rijndael ff]: https://en.wikipedia.org/wiki/Finite_field_arithmetic#Rijndael's_(AES)_finite_field [fips197]: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.197-upd1.pdf From 5699eeeae1c56bca073a7a26038198cf15794ea7 Mon Sep 17 00:00:00 2001 From: bing Date: Tue, 2 Jul 2024 15:36:11 +0800 Subject: [PATCH 04/15] remove accidental duplication --- src/encryption/symmetric/aes/README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/encryption/symmetric/aes/README.md b/src/encryption/symmetric/aes/README.md index 8c8a2ce..c8444ff 100644 --- a/src/encryption/symmetric/aes/README.md +++ b/src/encryption/symmetric/aes/README.md @@ -103,9 +103,6 @@ Substitutes each byte in the `State` with another byte according to a [substitut Do a **right** shift i-th row of i positions, for i ranging from 0 to 3, eg. Row 0: no shift occurs, row 1: a right shift of 1 position occurs. -Substitutes each byte in the `State` with another byte according to a [substitution box](#substitution-box). Note that the only difference here is that the substitution box used in decryption is derived differently from the version used in encryption. - - #### InvMixColumns Each column of bytes is treated as a 4-term polynomial, multiplied modulo x^4 + 1 with the inverse of the fixed polynomial From 6d7c553af311d06bb4f0fa42a8912f70dd359244 Mon Sep 17 00:00:00 2001 From: bing Date: Tue, 2 Jul 2024 15:36:54 +0800 Subject: [PATCH 05/15] docs: fix typo in aes decryption example --- src/encryption/symmetric/aes/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/encryption/symmetric/aes/mod.rs b/src/encryption/symmetric/aes/mod.rs index 352e8f4..cb907ac 100644 --- a/src/encryption/symmetric/aes/mod.rs +++ b/src/encryption/symmetric/aes/mod.rs @@ -88,7 +88,7 @@ where [(); N / 8]: /// let key = Key::<128>::new(rng.gen()); /// let plaintext = rng.gen(); /// let encrypted = AES::encrypt(&key, &plaintext); - /// let decrypted = AES::decrypt(&key, &plaintext); + /// let decrypted = AES::decrypt(&key, &encrypted); /// ``` fn decrypt(key: &Self::Key, ciphertext: &Self::Block) -> Self::Block { let num_rounds = match N { From ec3ebd031d5b128ad75df7ad72a555e2c5a93c45 Mon Sep 17 00:00:00 2001 From: bing Date: Tue, 2 Jul 2024 15:37:30 +0800 Subject: [PATCH 06/15] docs: replace hex representation of a^-1(x) with decimal representation --- src/encryption/symmetric/aes/mod.rs | 29 ++--------------------------- 1 file changed, 2 insertions(+), 27 deletions(-) diff --git a/src/encryption/symmetric/aes/mod.rs b/src/encryption/symmetric/aes/mod.rs index cb907ac..2fe1297 100644 --- a/src/encryption/symmetric/aes/mod.rs +++ b/src/encryption/symmetric/aes/mod.rs @@ -342,12 +342,8 @@ where [(); N / 8]: /// Mix columns is done as such: /// /// Each column of bytes is treated as a 4-term polynomial, multiplied modulo x^4 + 1 with a - /// fixed polynomial a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}, where {xy} represents a - /// hexadecimal number, x being the higher 4 bits, and y being the lower 4 bits. - /// - /// eg: {0b} == 0000_1011 == 11 - /// - /// This is done using matrix multiplication. + /// fixed polynomial a^-1(x) = 11x^3 + 13x^2 + 9x + 14, which is the inverse of the polynomial + /// used in [`Self::mix_columns`]. This is done using matrix multiplication. fn inv_mix_columns(state: &mut State) { for col in state.0.iter_mut() { let tmp = *col; @@ -375,27 +371,6 @@ where [(); N / 8]: } } - fn multiply(col: u8, multiplicant: usize) -> u8 { - let mut product = 0; - let mut col = col; - let mut mult = multiplicant; - - for _ in 0..8 { - if mult & 1 == 1 { - product ^= col; - } - - let hi_bit = col & 0x80; - col <<= 1; - if hi_bit == 0x80 { - col ^= 0x1B; - } - - mult >>= 1; - } - return product & 0xFF; - } - /// In AES, rotword() is just a one-byte left circular shift. fn rotate_word(word: &mut [u8; 4]) { word.rotate_left(1) } From b1cf5c4dd0a176a2626a428071377aaac8f8517a Mon Sep 17 00:00:00 2001 From: bing Date: Tue, 2 Jul 2024 15:37:30 +0800 Subject: [PATCH 07/15] feat: better name/code/docs for galois multiplication --- src/encryption/symmetric/aes/mod.rs | 71 +++++++++++++++++++++-------- 1 file changed, 51 insertions(+), 20 deletions(-) diff --git a/src/encryption/symmetric/aes/mod.rs b/src/encryption/symmetric/aes/mod.rs index 2fe1297..8737eab 100644 --- a/src/encryption/symmetric/aes/mod.rs +++ b/src/encryption/symmetric/aes/mod.rs @@ -136,6 +136,33 @@ pub struct AES {} #[derive(Debug, Default, Clone, Copy, PartialEq)] struct State([[u8; 4]; 4]); +/// Multiplies a 8-bit number in the Galois field GF(2^8). This is done using "carry-less +/// multiplication" or "bitwise multiplication", where the binary representation of each +/// element is treated as a polynomial. +/// +/// NOTE: this multiplication is not commutative - ie. A * B may not equal B * A. +fn galois_multiplication(col: u8, multiplicant: usize) -> u8 { + let mut product = 0; + let mut col = col; + let mut mult = multiplicant; + + for _ in 0..8 { + if mult & 1 == 1 { + product ^= col; + } + + let hi_bit = col & 0x80; + col <<= 1; + if hi_bit == 0x80 { + col ^= 0x1B; // This XOR brings the value back into the field if an overflow occurs + // (ie. hi_bit is set) + } + + mult >>= 1; + } + product +} + impl AES where [(); N / 8]: { @@ -325,13 +352,17 @@ where [(); N / 8]: let tmp = *col; // 2a0 + 3a1 + a2 + a3 - col[0] = Self::multiply(tmp[0], 2) ^ tmp[3] ^ tmp[2] ^ Self::multiply(tmp[1], 3); + col[0] = + galois_multiplication(tmp[0], 2) ^ tmp[3] ^ tmp[2] ^ galois_multiplication(tmp[1], 3); // a0 + 2a1 + 3a2 + a3 - col[1] = Self::multiply(tmp[1], 2) ^ tmp[0] ^ tmp[3] ^ Self::multiply(tmp[2], 3); + col[1] = + galois_multiplication(tmp[1], 2) ^ tmp[0] ^ tmp[3] ^ galois_multiplication(tmp[2], 3); // a0 + a1 + 2a2 + 3a3 - col[2] = Self::multiply(tmp[2], 2) ^ tmp[1] ^ tmp[0] ^ Self::multiply(tmp[3], 3); + col[2] = + galois_multiplication(tmp[2], 2) ^ tmp[1] ^ tmp[0] ^ galois_multiplication(tmp[3], 3); // 3a0 + a1 + a2 + 2a3 - col[3] = Self::multiply(tmp[3], 2) ^ tmp[2] ^ tmp[1] ^ Self::multiply(tmp[0], 3); + col[3] = + galois_multiplication(tmp[3], 2) ^ tmp[2] ^ tmp[1] ^ galois_multiplication(tmp[0], 3); } } @@ -349,25 +380,25 @@ where [(); N / 8]: let tmp = *col; // {0e}a0 + {0b}a1 + {0d}a2 + {09}a3 - col[0] = Self::multiply(tmp[0], 0x0e) - ^ Self::multiply(tmp[3], 0x09) - ^ Self::multiply(tmp[2], 0x0d) - ^ Self::multiply(tmp[1], 0x0b); + col[0] = galois_multiplication(tmp[0], 0x0e) + ^ galois_multiplication(tmp[3], 0x09) + ^ galois_multiplication(tmp[2], 0x0d) + ^ galois_multiplication(tmp[1], 0x0b); // {09}a0 + {0e}a1 + {0b}a2 + {0d}a3 - col[1] = Self::multiply(tmp[1], 0x0e) - ^ Self::multiply(tmp[0], 0x09) - ^ Self::multiply(tmp[3], 0x0d) - ^ Self::multiply(tmp[2], 0x0b); + col[1] = galois_multiplication(tmp[1], 0x0e) + ^ galois_multiplication(tmp[0], 0x09) + ^ galois_multiplication(tmp[3], 0x0d) + ^ galois_multiplication(tmp[2], 0x0b); // {0d}a0 + {09}a1 + {0e}a2 + {0b}a3 - col[2] = Self::multiply(tmp[2], 0x0e) - ^ Self::multiply(tmp[1], 0x09) - ^ Self::multiply(tmp[0], 0x0d) - ^ Self::multiply(tmp[3], 0x0b); + col[2] = galois_multiplication(tmp[2], 0x0e) + ^ galois_multiplication(tmp[1], 0x09) + ^ galois_multiplication(tmp[0], 0x0d) + ^ galois_multiplication(tmp[3], 0x0b); // {0b}3a0 + {0d}a1 + {09}a2 + {0e}a3 - col[3] = Self::multiply(tmp[3], 0x0e) - ^ Self::multiply(tmp[2], 0x09) - ^ Self::multiply(tmp[1], 0x0d) - ^ Self::multiply(tmp[0], 0x0b); + col[3] = galois_multiplication(tmp[3], 0x0e) + ^ galois_multiplication(tmp[2], 0x09) + ^ galois_multiplication(tmp[1], 0x0d) + ^ galois_multiplication(tmp[0], 0x0b); } } From 1157672dd6ba5abf81850d85038cb8d4d45bd65c Mon Sep 17 00:00:00 2001 From: bing Date: Tue, 2 Jul 2024 15:54:40 +0800 Subject: [PATCH 08/15] more hex representation replacement --- src/encryption/symmetric/aes/mod.rs | 40 ++++++++++++++--------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/encryption/symmetric/aes/mod.rs b/src/encryption/symmetric/aes/mod.rs index 8737eab..4c606d9 100644 --- a/src/encryption/symmetric/aes/mod.rs +++ b/src/encryption/symmetric/aes/mod.rs @@ -379,26 +379,26 @@ where [(); N / 8]: for col in state.0.iter_mut() { let tmp = *col; - // {0e}a0 + {0b}a1 + {0d}a2 + {09}a3 - col[0] = galois_multiplication(tmp[0], 0x0e) - ^ galois_multiplication(tmp[3], 0x09) - ^ galois_multiplication(tmp[2], 0x0d) - ^ galois_multiplication(tmp[1], 0x0b); - // {09}a0 + {0e}a1 + {0b}a2 + {0d}a3 - col[1] = galois_multiplication(tmp[1], 0x0e) - ^ galois_multiplication(tmp[0], 0x09) - ^ galois_multiplication(tmp[3], 0x0d) - ^ galois_multiplication(tmp[2], 0x0b); - // {0d}a0 + {09}a1 + {0e}a2 + {0b}a3 - col[2] = galois_multiplication(tmp[2], 0x0e) - ^ galois_multiplication(tmp[1], 0x09) - ^ galois_multiplication(tmp[0], 0x0d) - ^ galois_multiplication(tmp[3], 0x0b); - // {0b}3a0 + {0d}a1 + {09}a2 + {0e}a3 - col[3] = galois_multiplication(tmp[3], 0x0e) - ^ galois_multiplication(tmp[2], 0x09) - ^ galois_multiplication(tmp[1], 0x0d) - ^ galois_multiplication(tmp[0], 0x0b); + // 14a0 + 11a1 + 13a2 + 9a3 + col[0] = galois_multiplication(tmp[0], 14) + ^ galois_multiplication(tmp[3], 9) + ^ galois_multiplication(tmp[2], 13) + ^ galois_multiplication(tmp[1], 11); + // 9a0 + 14a1 + 11a2 + 13a3 + col[1] = galois_multiplication(tmp[1], 14) + ^ galois_multiplication(tmp[0], 9) + ^ galois_multiplication(tmp[3], 13) + ^ galois_multiplication(tmp[2], 11); + // 13a0 + 9a1 + 14a2 + 11a3 + col[2] = galois_multiplication(tmp[2], 14) + ^ galois_multiplication(tmp[1], 9) + ^ galois_multiplication(tmp[0], 13) + ^ galois_multiplication(tmp[3], 11); + // 11a0 + 13a1 + 9a2 + 14a3 + col[3] = galois_multiplication(tmp[3], 14) + ^ galois_multiplication(tmp[2], 9) + ^ galois_multiplication(tmp[1], 13) + ^ galois_multiplication(tmp[0], 11); } } From c24fefffd18af66bf5e612cf87018763557913d9 Mon Sep 17 00:00:00 2001 From: bing Date: Tue, 2 Jul 2024 15:58:03 +0800 Subject: [PATCH 09/15] simplify galois_multiplication params --- src/encryption/symmetric/aes/mod.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/encryption/symmetric/aes/mod.rs b/src/encryption/symmetric/aes/mod.rs index 4c606d9..7fba0a9 100644 --- a/src/encryption/symmetric/aes/mod.rs +++ b/src/encryption/symmetric/aes/mod.rs @@ -141,13 +141,11 @@ struct State([[u8; 4]; 4]); /// element is treated as a polynomial. /// /// NOTE: this multiplication is not commutative - ie. A * B may not equal B * A. -fn galois_multiplication(col: u8, multiplicant: usize) -> u8 { +fn galois_multiplication(mut col: u8, mut multiplicant: usize) -> u8 { let mut product = 0; - let mut col = col; - let mut mult = multiplicant; for _ in 0..8 { - if mult & 1 == 1 { + if multiplicant & 1 == 1 { product ^= col; } @@ -158,7 +156,7 @@ fn galois_multiplication(col: u8, multiplicant: usize) -> u8 { // (ie. hi_bit is set) } - mult >>= 1; + multiplicant >>= 1; } product } From 99b02316f64977bdde1520786218df5ab5fc1625 Mon Sep 17 00:00:00 2001 From: bing Date: Tue, 2 Jul 2024 16:01:51 +0800 Subject: [PATCH 10/15] docs: fix typo --- src/encryption/symmetric/aes/README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/encryption/symmetric/aes/README.md b/src/encryption/symmetric/aes/README.md index c8444ff..ea6b346 100644 --- a/src/encryption/symmetric/aes/README.md +++ b/src/encryption/symmetric/aes/README.md @@ -106,9 +106,7 @@ Do a **right** shift i-th row of i positions, for i ranging from 0 to 3, eg. Row #### InvMixColumns Each column of bytes is treated as a 4-term polynomial, multiplied modulo x^4 + 1 with the inverse of the fixed polynomial -a(x) = 3x^3 + x^2 + x + 2 found in the [MixColumns] step. The inverse of a(x) is a^-1(x) = 11x^3 + 13x^2 + 9x + 14. - -This is multiplication is done using matrix multiplication. +a(x) = 3x^3 + x^2 + x + 2 found in the [MixColumns] step. The inverse of a(x) is a^-1(x) = 11x^3 + 13x^2 + 9x + 14. This multiplication is done using matrix multiplication. More details can be found [here][mixcolumns]. From a3b9458c78eb42921a7cddfc7e61767ed32b8792 Mon Sep 17 00:00:00 2001 From: bing Date: Mon, 8 Jul 2024 13:37:15 +0800 Subject: [PATCH 11/15] reimpl: galois multiplication This commit contains 2 main changes: Updates to documentation, Using 7-degree polynomials of `BinaryField`s to represent bytes to do a multiplication instead of doing carry-less multiplication. --- src/encryption/symmetric/aes/mod.rs | 97 +++++++++++++++++++---------- src/field/binary_towers/mod.rs | 4 ++ src/polynomial/mod.rs | 2 +- 3 files changed, 70 insertions(+), 33 deletions(-) diff --git a/src/encryption/symmetric/aes/mod.rs b/src/encryption/symmetric/aes/mod.rs index 7fba0a9..23b1ff8 100644 --- a/src/encryption/symmetric/aes/mod.rs +++ b/src/encryption/symmetric/aes/mod.rs @@ -2,13 +2,19 @@ //! and decryption. #![cfg_attr(not(doctest), doc = include_str!("./README.md"))] +use std::ops::{Mul, Rem}; + use itertools::Itertools; pub mod sbox; #[cfg(test)] pub mod tests; use super::SymmetricEncryption; -use crate::encryption::symmetric::aes::sbox::{INVERSE_SBOX, SBOX}; +use crate::{ + encryption::symmetric::aes::sbox::{INVERSE_SBOX, SBOX}, + field::{binary_towers::BinaryField, FiniteField}, + polynomial::{Monomial, Polynomial}, +}; /// A block in AES represents a 128-bit sized message data. pub type Block = [u8; 16]; @@ -136,29 +142,56 @@ pub struct AES {} #[derive(Debug, Default, Clone, Copy, PartialEq)] struct State([[u8; 4]; 4]); -/// Multiplies a 8-bit number in the Galois field GF(2^8). This is done using "carry-less -/// multiplication" or "bitwise multiplication", where the binary representation of each -/// element is treated as a polynomial. +/// Multiplies a 8-bit number in the Galois field GF(2^8). /// -/// NOTE: this multiplication is not commutative - ie. A * B may not equal B * A. -fn galois_multiplication(mut col: u8, mut multiplicant: usize) -> u8 { - let mut product = 0; - - for _ in 0..8 { - if multiplicant & 1 == 1 { - product ^= col; - } - - let hi_bit = col & 0x80; - col <<= 1; - if hi_bit == 0x80 { - col ^= 0x1B; // This XOR brings the value back into the field if an overflow occurs - // (ie. hi_bit is set) - } - +/// This is defined on two bytes in two steps: +/// +/// 1) The two polynomials that represent the bytes are multiplied as polynomials, +/// 2) The resulting polynomial is reduced modulo the following fixed polynomial: +/// +/// m(x) = x^8 + x^4 + x^3 + x + 1 +/// +/// Note that in most AES implementations, this is done using "carry-less" multiplication - +/// to see how this works in field terms, this implementation uses an actual polynomial +/// implementation (a [`Polynomial`] of [`BinaryField`]s) +fn galois_multiplication(mut col: u8, mut multiplicant: u8) -> u8 { + // Decompose bits into degree-7 polynomials. + let mut col_bits = [BinaryField::new(0); 8]; + let mut mult_bits = [BinaryField::new(0); 8]; + for i in 0..8 { + col_bits[i] = BinaryField::new(col & 1); + mult_bits[i] = BinaryField::new(multiplicant & 1); + col >>= 1; multiplicant >>= 1; } - product + + let col_poly = Polynomial::::new(col_bits); + let mult_poly = Polynomial::::new(mult_bits); + // m(x) = x^8 + x^4 + x^3 + x + 1 + let reducer = Polynomial::::new([ + BinaryField::ONE, + BinaryField::ONE, + BinaryField::ZERO, + BinaryField::ONE, + BinaryField::ONE, + BinaryField::ZERO, + BinaryField::ZERO, + BinaryField::ZERO, + BinaryField::ONE, + ]); + + let res = col_poly.mul(mult_poly); + let result = res.rem(reducer); // reduce resulting polynomial modulo a fixed polynomial + + assert!(result.degree() < 8, "did not get a u8 out of multiplication in GF(2^8)"); + // Recompose polynomial into a u8. + let mut fin: u8 = 0; + for i in 0..8 { + let coeff: u8 = result.coefficients[i].into(); + fin += coeff * (2_i16.pow(i as u32)) as u8; + } + + fin } impl AES @@ -339,12 +372,13 @@ where [(); N / 8]: .unwrap(); } - /// Applies the same linear transformation to each of the four columns of the state. - /// - /// Mix columns is done as such: + /// Mixes the data in each of the 4 columns with a single fixed matrix, with its entries taken + /// from the word [a_0, a_1, a_2, a_3] = [{02}, {01}, {01}, {03}] (hex) (or [2, 1, 1, 3] in + /// decimal). /// - /// Each column of bytes is treated as a 4-term polynomial, multiplied modulo x^4 + 1 with a fixed - /// polynomial a(x) = 3x^3 + x^2 + x + 2. This is done using matrix multiplication. + /// This is done by interpreting both the byte from the state and the byte from the fixed matrix + /// as degree-7 polynomials and doing multiplication in the GF(2^8) field. For details, see + /// [`galois_multiplication`]. fn mix_columns(state: &mut State) { for col in state.0.iter_mut() { let tmp = *col; @@ -366,13 +400,12 @@ where [(); N / 8]: /// The inverse of [`Self::mix_columns`]. /// - /// Applies the same linear transformation to each of the four columns of the state. - /// - /// Mix columns is done as such: + /// Mixes the data in each of the 4 columns with a single fixed matrix, with its entries taken + /// from the word [a_0, a_1, a_2, a_3] = [{0e}, {09}, {0d}, {0b}] (or [14, 9, 13, 11] in decimal). /// - /// Each column of bytes is treated as a 4-term polynomial, multiplied modulo x^4 + 1 with a - /// fixed polynomial a^-1(x) = 11x^3 + 13x^2 + 9x + 14, which is the inverse of the polynomial - /// used in [`Self::mix_columns`]. This is done using matrix multiplication. + /// This is done by interpreting both the byte from the state and the byte from the fixed matrix + /// as degree-7 polynomials and doing multiplication in the GF(2^8) field. For details, see + /// [`galois_multiplication`]. fn inv_mix_columns(state: &mut State) { for col in state.0.iter_mut() { let tmp = *col; diff --git a/src/field/binary_towers/mod.rs b/src/field/binary_towers/mod.rs index 1e9b755..46610e1 100644 --- a/src/field/binary_towers/mod.rs +++ b/src/field/binary_towers/mod.rs @@ -47,6 +47,10 @@ impl From for BinaryField { } } +impl From for u8 { + fn from(value: BinaryField) -> u8 { value.0 } +} + impl Add for BinaryField { type Output = Self; diff --git a/src/polynomial/mod.rs b/src/polynomial/mod.rs index 9118119..583a8e4 100644 --- a/src/polynomial/mod.rs +++ b/src/polynomial/mod.rs @@ -97,7 +97,7 @@ impl Polynomial { pub fn new(coefficients: [F; D]) -> Self { Self { coefficients, basis: Monomial } } /// Helper method to remove leading zeros from coefficients - fn trim_zeros(coefficients: &mut Vec) { + pub fn trim_zeros(coefficients: &mut Vec) { while coefficients.last().cloned() == Some(F::ZERO) { coefficients.pop(); } From d793e1b06eaa8151a8ca14d79f7d01b6b8b83a40 Mon Sep 17 00:00:00 2001 From: bing Date: Mon, 8 Jul 2024 16:25:08 +0800 Subject: [PATCH 12/15] undo pub addition to trim_zeroes --- src/polynomial/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/polynomial/mod.rs b/src/polynomial/mod.rs index 583a8e4..9118119 100644 --- a/src/polynomial/mod.rs +++ b/src/polynomial/mod.rs @@ -97,7 +97,7 @@ impl Polynomial { pub fn new(coefficients: [F; D]) -> Self { Self { coefficients, basis: Monomial } } /// Helper method to remove leading zeros from coefficients - pub fn trim_zeros(coefficients: &mut Vec) { + fn trim_zeros(coefficients: &mut Vec) { while coefficients.last().cloned() == Some(F::ZERO) { coefficients.pop(); } From 02c20ae843cf7b5158169daebb2ce49920be07e4 Mon Sep 17 00:00:00 2001 From: bing Date: Mon, 8 Jul 2024 16:27:41 +0800 Subject: [PATCH 13/15] improve comment for galois_multiplication --- src/encryption/symmetric/aes/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/encryption/symmetric/aes/mod.rs b/src/encryption/symmetric/aes/mod.rs index 23b1ff8..0015534 100644 --- a/src/encryption/symmetric/aes/mod.rs +++ b/src/encryption/symmetric/aes/mod.rs @@ -152,8 +152,8 @@ struct State([[u8; 4]; 4]); /// m(x) = x^8 + x^4 + x^3 + x + 1 /// /// Note that in most AES implementations, this is done using "carry-less" multiplication - -/// to see how this works in field terms, this implementation uses an actual polynomial -/// implementation (a [`Polynomial`] of [`BinaryField`]s) +/// to see how this works in more concretely in field arithmetic, this implementation uses an actual +/// polynomial implementation (a [`Polynomial`] of [`BinaryField`]s). fn galois_multiplication(mut col: u8, mut multiplicant: u8) -> u8 { // Decompose bits into degree-7 polynomials. let mut col_bits = [BinaryField::new(0); 8]; From dfdcd05fe4c8cde38c1621cd91fa37c896bd7b05 Mon Sep 17 00:00:00 2001 From: bing Date: Mon, 8 Jul 2024 16:48:13 +0800 Subject: [PATCH 14/15] feat: introduce GF(2^8) in `field` crate and use in aes impl --- src/encryption/symmetric/aes/mod.rs | 52 +++++------- src/field/binary_towers/mod.rs | 4 - src/field/binary_towers/tests.rs | 123 +--------------------------- src/field/extension/gf_2_8.rs | 121 +++++++++++++++++++++++++++ src/field/extension/mod.rs | 6 ++ src/field/prime/mod.rs | 4 + 6 files changed, 152 insertions(+), 158 deletions(-) create mode 100644 src/field/extension/gf_2_8.rs diff --git a/src/encryption/symmetric/aes/mod.rs b/src/encryption/symmetric/aes/mod.rs index 0015534..2b57f55 100644 --- a/src/encryption/symmetric/aes/mod.rs +++ b/src/encryption/symmetric/aes/mod.rs @@ -2,18 +2,19 @@ //! and decryption. #![cfg_attr(not(doctest), doc = include_str!("./README.md"))] -use std::ops::{Mul, Rem}; +use std::ops::Mul; use itertools::Itertools; +use crate::field::{extension::AESFieldExtension, prime::AESField}; + pub mod sbox; #[cfg(test)] pub mod tests; use super::SymmetricEncryption; use crate::{ encryption::symmetric::aes::sbox::{INVERSE_SBOX, SBOX}, - field::{binary_towers::BinaryField, FiniteField}, - polynomial::{Monomial, Polynomial}, + field::FiniteField, }; /// A block in AES represents a 128-bit sized message data. @@ -147,51 +148,36 @@ struct State([[u8; 4]; 4]); /// This is defined on two bytes in two steps: /// /// 1) The two polynomials that represent the bytes are multiplied as polynomials, -/// 2) The resulting polynomial is reduced modulo the following fixed polynomial: +/// 2) The resulting polynomial is reduced modulo the following fixed polynomial: m(x) = x^8 + x^4 + +/// x^3 + x + 1 /// -/// m(x) = x^8 + x^4 + x^3 + x + 1 +/// Note that you do not see this done here, this is implemented in [`AESFieldExtension`], within +/// the operation traits. /// /// Note that in most AES implementations, this is done using "carry-less" multiplication - /// to see how this works in more concretely in field arithmetic, this implementation uses an actual /// polynomial implementation (a [`Polynomial`] of [`BinaryField`]s). -fn galois_multiplication(mut col: u8, mut multiplicant: u8) -> u8 { +fn galois_multiplication(mut col: u8, mut multiplicand: u8) -> u8 { // Decompose bits into degree-7 polynomials. - let mut col_bits = [BinaryField::new(0); 8]; - let mut mult_bits = [BinaryField::new(0); 8]; + let mut col_bits: [AESField; 8] = [AESField::ZERO; 8]; + let mut mult_bits: [AESField; 8] = [AESField::ZERO; 8]; for i in 0..8 { - col_bits[i] = BinaryField::new(col & 1); - mult_bits[i] = BinaryField::new(multiplicant & 1); + col_bits[i] = AESField::new((col & 1).into()); + mult_bits[i] = AESField::new((multiplicand & 1).into()); col >>= 1; - multiplicant >>= 1; + multiplicand >>= 1; } - let col_poly = Polynomial::::new(col_bits); - let mult_poly = Polynomial::::new(mult_bits); - // m(x) = x^8 + x^4 + x^3 + x + 1 - let reducer = Polynomial::::new([ - BinaryField::ONE, - BinaryField::ONE, - BinaryField::ZERO, - BinaryField::ONE, - BinaryField::ONE, - BinaryField::ZERO, - BinaryField::ZERO, - BinaryField::ZERO, - BinaryField::ONE, - ]); - + let col_poly = AESFieldExtension::new(col_bits); + let mult_poly = AESFieldExtension::new(mult_bits); let res = col_poly.mul(mult_poly); - let result = res.rem(reducer); // reduce resulting polynomial modulo a fixed polynomial - assert!(result.degree() < 8, "did not get a u8 out of multiplication in GF(2^8)"); - // Recompose polynomial into a u8. - let mut fin: u8 = 0; + let mut product: u8 = 0; for i in 0..8 { - let coeff: u8 = result.coefficients[i].into(); - fin += coeff * (2_i16.pow(i as u32)) as u8; + product += res.coeffs[i].value as u8 * 2_u8.pow(i as u32); } - fin + product } impl AES diff --git a/src/field/binary_towers/mod.rs b/src/field/binary_towers/mod.rs index 46610e1..1e9b755 100644 --- a/src/field/binary_towers/mod.rs +++ b/src/field/binary_towers/mod.rs @@ -47,10 +47,6 @@ impl From for BinaryField { } } -impl From for u8 { - fn from(value: BinaryField) -> u8 { value.0 } -} - impl Add for BinaryField { type Output = Self; diff --git a/src/field/binary_towers/tests.rs b/src/field/binary_towers/tests.rs index 0db5bc0..feebcf1 100644 --- a/src/field/binary_towers/tests.rs +++ b/src/field/binary_towers/tests.rs @@ -1,129 +1,10 @@ -use std::array; - use rand::{thread_rng, Rng}; use rstest::rstest; use super::*; -use crate::{ - field::{extension::ExtensionField, prime::PrimeField, GaloisField}, - polynomial::Monomial, - Polynomial, -}; - -pub type TestBinaryField = PrimeField<2>; -pub type TestBinaryExtensionField = GaloisField<8, 2>; - -impl FiniteField for TestBinaryExtensionField { - const ONE: Self = Self::new([ - TestBinaryField::ONE, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - ]); - const ORDER: usize = TestBinaryField::ORDER.pow(8); - const PRIMITIVE_ELEMENT: Self = Self::new([ - TestBinaryField::ONE, - TestBinaryField::ONE, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - TestBinaryField::ONE, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - ]); - const ZERO: Self = Self::new([ - TestBinaryField::ZERO, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - TestBinaryField::ZERO, - ]); - - /// Computes the multiplicative inverse of `a`, i.e. 1 / (a0 + a1 * t). - fn inverse(&self) -> Option { - if *self == Self::ZERO { - return None; - } - - let res = self.pow(Self::ORDER - 2); - Some(res) - } - - fn pow(self, power: usize) -> Self { - if power == 0 { - Self::ONE - } else if power == 1 { - self - } else if power % 2 == 0 { - self.pow(power / 2) * self.pow(power / 2) - } else { - self.pow(power / 2) * self.pow(power / 2) * self - } - } -} - -impl ExtensionField<8, 2> for TestBinaryExtensionField { - const IRREDUCIBLE_POLYNOMIAL_COEFFICIENTS: [TestBinaryField; 9] = [ - TestBinaryField::ONE, // 1 - TestBinaryField::ONE, // a - TestBinaryField::ZERO, // a^2 - TestBinaryField::ONE, // a^3 - TestBinaryField::ONE, // a^4 - TestBinaryField::ZERO, // a^5 - TestBinaryField::ZERO, // a^6 - TestBinaryField::ZERO, // a^7 - TestBinaryField::ONE, // a^8 - ]; -} +use crate::field::prime::PrimeField; -/// Returns the multiplication of two [`Ext<2, GF101>`] elements by reducing result modulo -/// irreducible polynomial. -impl Mul for TestBinaryExtensionField { - type Output = Self; - - fn mul(self, rhs: Self) -> Self::Output { - let poly_self = Polynomial::::from(self); - let poly_rhs = Polynomial::::from(rhs); - let poly_irred = - Polynomial::::from(Self::IRREDUCIBLE_POLYNOMIAL_COEFFICIENTS); - let product = (poly_self * poly_rhs) % poly_irred; - let res: [TestBinaryField; 8] = - array::from_fn(|i| product.coefficients.get(i).cloned().unwrap_or(TestBinaryField::ZERO)); - Self::new(res) - } -} -impl MulAssign for TestBinaryExtensionField { - fn mul_assign(&mut self, rhs: Self) { *self = *self * rhs; } -} -impl Product for TestBinaryExtensionField { - fn product>(iter: I) -> Self { - iter.reduce(|x, y| x * y).unwrap_or(Self::ONE) - } -} - -impl Div for TestBinaryExtensionField { - type Output = Self; - - #[allow(clippy::suspicious_arithmetic_impl)] - fn div(self, rhs: Self) -> Self::Output { self * rhs.inverse().expect("invalid inverse") } -} - -impl DivAssign for TestBinaryExtensionField { - fn div_assign(&mut self, rhs: Self) { *self = *self / rhs } -} - -impl Rem for TestBinaryExtensionField { - type Output = Self; - - fn rem(self, rhs: Self) -> Self::Output { self - (self / rhs) * rhs } -} +type TestBinaryField = PrimeField<2>; pub(super) fn num_digits(n: u64) -> usize { let r = format!("{:b}", n); diff --git a/src/field/extension/gf_2_8.rs b/src/field/extension/gf_2_8.rs new file mode 100644 index 0000000..0fb2f67 --- /dev/null +++ b/src/field/extension/gf_2_8.rs @@ -0,0 +1,121 @@ +//! This module contains an implementation of the quadratic extension field GF(2^8). +//! Elements represented as coefficients of a [`Polynomial`] in the [`Monomial`] basis of degree 1 +//! in form: `a_0 + a_1*t`` where {a_0, a_1} \in \mathhbb{F}. Uses irreducible poly of the form: +//! (X^2-K). +//! +//! This extension field is used for our [AES implementation][`crate::encryption::symmetric::aes`]. +use self::field::prime::AESField; +use super::*; + +impl FiniteField for GaloisField<8, 2> { + const ONE: Self = Self::new([ + AESField::ONE, + AESField::ZERO, + AESField::ZERO, + AESField::ZERO, + AESField::ZERO, + AESField::ZERO, + AESField::ZERO, + AESField::ZERO, + ]); + const ORDER: usize = AESField::ORDER.pow(8); + const PRIMITIVE_ELEMENT: Self = Self::new([ + AESField::ONE, + AESField::ONE, + AESField::ZERO, + AESField::ZERO, + AESField::ONE, + AESField::ZERO, + AESField::ZERO, + AESField::ZERO, + ]); + const ZERO: Self = Self::new([ + AESField::ZERO, + AESField::ZERO, + AESField::ZERO, + AESField::ZERO, + AESField::ZERO, + AESField::ZERO, + AESField::ZERO, + AESField::ZERO, + ]); + + /// Computes the multiplicative inverse of `a`, i.e. 1 / (a0 + a1 * t). + fn inverse(&self) -> Option { + if *self == Self::ZERO { + return None; + } + + let res = self.pow(Self::ORDER - 2); + Some(res) + } + + fn pow(self, power: usize) -> Self { + if power == 0 { + Self::ONE + } else if power == 1 { + self + } else if power % 2 == 0 { + self.pow(power / 2) * self.pow(power / 2) + } else { + self.pow(power / 2) * self.pow(power / 2) * self + } + } +} + +impl ExtensionField<8, 2> for GaloisField<8, 2> { + /// Represents the irreducible polynomial x^8 + x^4 + x^3 + x + 1. + const IRREDUCIBLE_POLYNOMIAL_COEFFICIENTS: [AESField; 9] = [ + AESField::ONE, // 1 + AESField::ONE, // a + AESField::ZERO, // a^2 + AESField::ONE, // a^3 + AESField::ONE, // a^4 + AESField::ZERO, // a^5 + AESField::ZERO, // a^6 + AESField::ZERO, // a^7 + AESField::ONE, // a^8 + ]; +} + +/// Returns the multiplication of two [`Ext<8, GF2>`] elements by reducing result modulo +/// irreducible polynomial. +impl Mul for GaloisField<8, 2> { + type Output = Self; + + fn mul(self, rhs: Self) -> Self::Output { + let poly_self = Polynomial::::from(self); + let poly_rhs = Polynomial::::from(rhs); + let poly_irred = + Polynomial::::from(Self::IRREDUCIBLE_POLYNOMIAL_COEFFICIENTS); + let product = (poly_self * poly_rhs) % poly_irred; + let res: [AESField; 8] = + array::from_fn(|i| product.coefficients.get(i).cloned().unwrap_or(AESField::ZERO)); + Self::new(res) + } +} +impl MulAssign for GaloisField<8, 2> { + fn mul_assign(&mut self, rhs: Self) { *self = *self * rhs; } +} +impl Product for GaloisField<8, 2> { + fn product>(iter: I) -> Self { + iter.reduce(|x, y| x * y).unwrap_or(Self::ONE) + } +} + +impl Div for GaloisField<8, 2> { + type Output = Self; + + #[allow(clippy::suspicious_arithmetic_impl)] + fn div(self, rhs: Self) -> Self::Output { self * rhs.inverse().expect("invalid inverse") } +} + +impl DivAssign for GaloisField<8, 2> { + fn div_assign(&mut self, rhs: Self) { *self = *self / rhs } +} + +impl Rem for GaloisField<8, 2> { + type Output = Self; + + fn rem(self, rhs: Self) -> Self::Output { self - (self / rhs) * rhs } +} diff --git a/src/field/extension/mod.rs b/src/field/extension/mod.rs index 0e01775..1dba586 100644 --- a/src/field/extension/mod.rs +++ b/src/field/extension/mod.rs @@ -13,12 +13,18 @@ use super::*; mod arithmetic; pub mod gf_101_2; +pub mod gf_2_8; /// The [`PlutoBaseFieldExtension`] is a specific instance of the [`GaloisField`] struct with the /// order set to the prime number `101^2`. This is the quadratic extension field over the /// [`PlutoBaseField`] used in the Pluto `ronkathon` system. pub type PlutoBaseFieldExtension = GaloisField<2, 101>; +/// The [`AESFieldExtension`] is a specific instance of the [`GaloisField`] struct with the +/// order set to the number `2^8`. This is the quadratic extension field over the +/// [`PlutoBaseField`] used in the Pluto `ronkathon` system. +pub type AESFieldExtension = GaloisField<8, 2>; + /// The [`PlutoScalarFieldExtension`] is a specific instance of the [`GaloisField`] struct with the /// order set to the prime number `17^2`. This is the quadratic extension field over the /// [`field::prime::PlutoScalarField`] used in the Pluto `ronkathon` system. diff --git a/src/field/prime/mod.rs b/src/field/prime/mod.rs index 6b9fb55..2c3ad78 100644 --- a/src/field/prime/mod.rs +++ b/src/field/prime/mod.rs @@ -27,6 +27,10 @@ pub type PlutoBaseField = PrimeField<{ PlutoPrime::Base as usize }>; /// to the prime number `17`. This is the scalar field used in the Pluto `ronkathon` system. pub type PlutoScalarField = PrimeField<{ PlutoPrime::Scalar as usize }>; +/// The [`AESField`] is just a field over the prime 2, used within +/// [`AES`][crate::encryption::symmetric::aes] +pub type AESField = PrimeField<2>; + /// The [`PrimeField`] struct represents elements of a field with prime order. The field is defined /// by a prime number `P`, and the elements are integers modulo `P`. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default, PartialOrd)] From 37725b03806205a96068f21aceb02600c70c8581 Mon Sep 17 00:00:00 2001 From: bing Date: Mon, 8 Jul 2024 21:15:45 +0800 Subject: [PATCH 15/15] docs: better doc comments --- src/encryption/symmetric/aes/mod.rs | 5 ++--- src/field/extension/mod.rs | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/encryption/symmetric/aes/mod.rs b/src/encryption/symmetric/aes/mod.rs index 2b57f55..f27efbc 100644 --- a/src/encryption/symmetric/aes/mod.rs +++ b/src/encryption/symmetric/aes/mod.rs @@ -151,12 +151,11 @@ struct State([[u8; 4]; 4]); /// 2) The resulting polynomial is reduced modulo the following fixed polynomial: m(x) = x^8 + x^4 + /// x^3 + x + 1 /// -/// Note that you do not see this done here, this is implemented in [`AESFieldExtension`], within -/// the operation traits. +/// The above steps are implemented in [`AESFieldExtension`], within the operation traits. /// /// Note that in most AES implementations, this is done using "carry-less" multiplication - /// to see how this works in more concretely in field arithmetic, this implementation uses an actual -/// polynomial implementation (a [`Polynomial`] of [`BinaryField`]s). +/// polynomial implementation. fn galois_multiplication(mut col: u8, mut multiplicand: u8) -> u8 { // Decompose bits into degree-7 polynomials. let mut col_bits: [AESField; 8] = [AESField::ZERO; 8]; diff --git a/src/field/extension/mod.rs b/src/field/extension/mod.rs index 1dba586..583f1dc 100644 --- a/src/field/extension/mod.rs +++ b/src/field/extension/mod.rs @@ -22,7 +22,7 @@ pub type PlutoBaseFieldExtension = GaloisField<2, 101>; /// The [`AESFieldExtension`] is a specific instance of the [`GaloisField`] struct with the /// order set to the number `2^8`. This is the quadratic extension field over the -/// [`PlutoBaseField`] used in the Pluto `ronkathon` system. +/// [`AESField`][crate::field::prime::AESField] used in the Pluto `ronkathon` system. pub type AESFieldExtension = GaloisField<8, 2>; /// The [`PlutoScalarFieldExtension`] is a specific instance of the [`GaloisField`] struct with the