From 6f54d41c8e1b174ce2c60a48af3d6de6c4dc44a5 Mon Sep 17 00:00:00 2001 From: sangge <2251250136@qq.com> Date: Mon, 14 Jul 2025 23:49:21 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=8C=E5=96=84AES=E5=8A=A0=E5=AF=86?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E5=92=8C=E5=A4=9A=E4=B8=AA=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E7=9A=84=E8=A7=A3=E5=86=B3=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 在common库中添加了完整的AES-128加密解密实现 - 实现了AES-ECB和AES-CBC模式的加密解密函数 - 添加了密钥扩展和所有必要的AES操作函数 - 完成了问题10的AES-CBC模式实现 - 修复了问题11的加密oracle实现,使用正确的ECB检测 - 改进了代码风格,使用现代Rust格式化语法 - 为多个问题添加了common库的依赖 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- Cargo.lock | 21 ++ common/src/lib.rs | 409 +++++++++++++++++++++++++++++++++++++++ problems/p1/src/main.rs | 2 +- problems/p10/10.txt | 64 ++++++ problems/p10/Cargo.toml | 4 + problems/p10/src/main.rs | 142 +++++++++++++- problems/p11/Cargo.toml | 1 + problems/p11/src/main.rs | 16 +- problems/p4/src/main.rs | 2 +- problems/p8/src/main.rs | 4 +- problems/p9/src/main.rs | 2 +- 11 files changed, 653 insertions(+), 14 deletions(-) create mode 100644 problems/p10/10.txt diff --git a/Cargo.lock b/Cargo.lock index 087a9bf..5e4f78c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -72,11 +72,18 @@ dependencies = [ [[package]] name = "p10" version = "0.1.0" +dependencies = [ + "anyhow", + "base64", + "common", + "hex", +] [[package]] name = "p11" version = "0.1.0" dependencies = [ + "common", "rand", ] @@ -99,6 +106,18 @@ dependencies = [ "anyhow", ] +[[package]] +name = "p16" +version = "0.1.0" + +[[package]] +name = "p17" +version = "0.1.0" + +[[package]] +name = "p18" +version = "0.1.0" + [[package]] name = "p2" version = "0.1.0" @@ -145,6 +164,8 @@ name = "p7" version = "0.1.0" dependencies = [ "anyhow", + "base64", + "hex", ] [[package]] diff --git a/common/src/lib.rs b/common/src/lib.rs index 60ce1ae..283c671 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -1,5 +1,414 @@ +use std::collections::HashSet; + use anyhow::{Result, anyhow}; +const SBOX: [u8; 256] = [ + 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, + 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, + 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, + 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, + 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, + 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, + 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, + 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, + 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, + 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, + 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, + 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, + 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, + 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, + 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, +]; + +const INV_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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17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d, +]; + +const RCON: [[u8; 4]; 10] = [ + [0x01, 0x00, 0x00, 0x00], + [0x02, 0x00, 0x00, 0x00], + [0x04, 0x00, 0x00, 0x00], + [0x08, 0x00, 0x00, 0x00], + [0x10, 0x00, 0x00, 0x00], + [0x20, 0x00, 0x00, 0x00], + [0x40, 0x00, 0x00, 0x00], + [0x80, 0x00, 0x00, 0x00], + [0x1b, 0x00, 0x00, 0x00], + [0x36, 0x00, 0x00, 0x00], +]; + +pub fn add_round_key(block: &[u8; 16], round_key: &[u8; 16]) -> [u8; 16] { + std::array::from_fn(|i| block[i] ^ round_key[i]) +} + +pub fn sub_bytes(block: &[u8; 16]) -> [u8; 16] { + std::array::from_fn(|i| SBOX[block[i] as usize]) +} + +pub fn inv_sub_bytes(block: &[u8; 16]) -> [u8; 16] { + std::array::from_fn(|i| INV_SBOX[block[i] as usize]) +} + +pub fn shift_rows(block: &[u8; 16]) -> [u8; 16] { + let mut result = [0u8; 16]; + // Row 0 (no shift) + result[0] = block[0]; + result[4] = block[4]; + result[8] = block[8]; + result[12] = block[12]; + // Row 1 (shift left by 1) + result[1] = block[5]; + result[5] = block[9]; + result[9] = block[13]; + result[13] = block[1]; + // Row 2 (shift left by 2) + result[2] = block[10]; + result[6] = block[14]; + result[10] = block[2]; + result[14] = block[6]; + // Row 3 (shift left by 3) + result[3] = block[15]; + result[7] = block[3]; + result[11] = block[7]; + result[15] = block[11]; + result +} + +pub fn inv_shift_rows(block: &[u8; 16]) -> [u8; 16] { + let mut result = [0u8; 16]; + // Row 0 (no shift) + result[0] = block[0]; + result[4] = block[4]; + result[8] = block[8]; + result[12] = block[12]; + // Row 1 (shift right by 1, equivalent to shift left by 3) + result[1] = block[13]; + result[5] = block[1]; + result[9] = block[5]; + result[13] = block[9]; + // Row 2 (shift right by 2, equivalent to shift left by 2) + result[2] = block[10]; + result[6] = block[14]; + result[10] = block[2]; + result[14] = block[6]; + // Row 3 (shift right by 3, equivalent to shift left by 1) + result[3] = block[7]; + result[7] = block[11]; + result[11] = block[15]; + result[15] = block[3]; + result +} + +fn gf_mul_01(a: u8) -> u8 { + a +} + +fn gf_mul_02(a: u8) -> u8 { + if a & 0x80 != 0 { + (a << 1) ^ 0x1b + } else { + a << 1 + } +} + +fn gf_mul_03(a: u8) -> u8 { + gf_mul_02(a) ^ a +} + +fn gf_mul_0e(a: u8) -> u8 { + gf_mul_02(gf_mul_02(gf_mul_02(a))) ^ gf_mul_04(a) ^ gf_mul_02(a) +} + +fn gf_mul_0b(a: u8) -> u8 { + gf_mul_08(a) ^ gf_mul_02(a) ^ a +} + +fn gf_mul_0d(a: u8) -> u8 { + gf_mul_08(a) ^ gf_mul_04(a) ^ a +} + +fn gf_mul_09(a: u8) -> u8 { + gf_mul_08(a) ^ a +} + +fn gf_mul_04(a: u8) -> u8 { + gf_mul_02(gf_mul_02(a)) +} + +fn gf_mul_08(a: u8) -> u8 { + gf_mul_02(gf_mul_04(a)) +} + +pub fn mix_columns(block: &[u8; 16]) -> [u8; 16] { + // [02 03 01 01] + // [01 02 03 01] + // [01 01 02 03] + // [03 01 01 02] + let mut result = [0u8; 16]; + for i in 0..4 { + let col = [ + block[i * 4], + block[i * 4 + 1], + block[i * 4 + 2], + block[i * 4 + 3], + ]; + result[i * 4] = + gf_mul_02(col[0]) ^ gf_mul_03(col[1]) ^ gf_mul_01(col[2]) ^ gf_mul_01(col[3]); + result[i * 4 + 1] = + gf_mul_01(col[0]) ^ gf_mul_02(col[1]) ^ gf_mul_03(col[2]) ^ gf_mul_01(col[3]); + result[i * 4 + 2] = + gf_mul_01(col[0]) ^ gf_mul_01(col[1]) ^ gf_mul_02(col[2]) ^ gf_mul_03(col[3]); + result[i * 4 + 3] = + gf_mul_03(col[0]) ^ gf_mul_01(col[1]) ^ gf_mul_01(col[2]) ^ gf_mul_02(col[3]); + } + result +} + +pub fn inv_mix_columns(block: &[u8; 16]) -> [u8; 16] { + // [0E 0B 0D 09] + // [09 0E 0B 0D] + // [0D 09 0E 0B] + // [0B 0D 09 0E] + let mut result = [0u8; 16]; + for i in 0..4 { + let col = [ + block[i * 4], + block[i * 4 + 1], + block[i * 4 + 2], + block[i * 4 + 3], + ]; + result[i * 4] = + gf_mul_0e(col[0]) ^ gf_mul_0b(col[1]) ^ gf_mul_0d(col[2]) ^ gf_mul_09(col[3]); + result[i * 4 + 1] = + gf_mul_09(col[0]) ^ gf_mul_0e(col[1]) ^ gf_mul_0b(col[2]) ^ gf_mul_0d(col[3]); + result[i * 4 + 2] = + gf_mul_0d(col[0]) ^ gf_mul_09(col[1]) ^ gf_mul_0e(col[2]) ^ gf_mul_0b(col[3]); + result[i * 4 + 3] = + gf_mul_0b(col[0]) ^ gf_mul_0d(col[1]) ^ gf_mul_09(col[2]) ^ gf_mul_0e(col[3]); + } + result +} + +pub fn expand_key(key: &[u8; 16]) -> [[u8; 16]; 11] { + let mut round_key: [[u8; 16]; 11] = [[0u8; 16]; 11]; + round_key[0] = *key; + + for round in 1..round_key.len() { + let prev_key = round_key[round - 1]; + let mut new_key = [0u8; 16]; + + // 对前一轮密钥的最后4字节进行g变换 + let g_result = g_func(prev_key[12..16].try_into().unwrap(), round - 1); + + // 新密钥的每4字节都要与前面的4字节异或 + for i in 0..4 { + new_key[i] = prev_key[i] ^ g_result[i]; + } + + for i in 4..8 { + new_key[i] = prev_key[i] ^ new_key[i - 4]; + } + + for i in 8..12 { + new_key[i] = prev_key[i] ^ new_key[i - 4]; + } + + for i in 12..16 { + new_key[i] = prev_key[i] ^ new_key[i - 4]; + } + + round_key[round] = new_key; + } + + round_key +} + +fn rot_word(word: [u8; 4]) -> [u8; 4] { + [word[1], word[2], word[3], word[0]] +} + +fn xor_rcon(word: [u8; 4], round: usize) -> [u8; 4] { + let mut result = word; + result[0] ^= RCON[round][0]; // 只对第一个字节进行Rcon异或 + result +} + +fn sub_word(word: [u8; 4]) -> [u8; 4] { + [ + SBOX[word[0] as usize], + SBOX[word[1] as usize], + SBOX[word[2] as usize], + SBOX[word[3] as usize], + ] +} + +fn g_func(word: [u8; 4], round: usize) -> [u8; 4] { + let mut result = rot_word(word); + result = sub_word(result); + result = xor_rcon(result, round); + result +} + +pub fn aes_ecb_enc(input: &[u8], key: &[u8; 16]) -> Result> { + if input.len() % 16 != 0 { + return Err(anyhow!("Invalid input length")); + } + let mut cipher: Vec = Vec::new(); + let round_keys = expand_key(key); + for i in 0..(input.len() / 16) { + let mut block: [u8; 16] = input[(i * 16)..(i * 16 + 16)].try_into()?; + block = add_round_key(&block, &round_keys[0]); + for round_key in round_keys.iter().take(10).skip(1) { + block = sub_bytes(&block); + block = shift_rows(&block); + block = mix_columns(&block); + block = add_round_key(&block, round_key); + } + block = sub_bytes(&block); + block = shift_rows(&block); + block = add_round_key(&block, &round_keys[10]); + cipher.extend(block); + } + + Ok(cipher) +} + +pub fn aes_ecb_dec(input: &[u8], key: &[u8; 16]) -> Result> { + if input.len() % 16 != 0 { + return Err(anyhow!("Invalid input length")); + } + + let mut plaintext: Vec = Vec::new(); + let round_keys = expand_key(key); + + for i in 0..(input.len() / 16) { + let mut block: [u8; 16] = input[(i * 16)..(i * 16 + 16)].try_into()?; + block = add_round_key(&block, &round_keys[10]); + block = inv_shift_rows(&block); + block = inv_sub_bytes(&block); + for j in 0..9 { + block = add_round_key(&block, &round_keys[9 - j]); + block = inv_mix_columns(&block); + block = inv_shift_rows(&block); + block = inv_sub_bytes(&block); + } + block = add_round_key(&block, &round_keys[0]); + plaintext.extend(block); + } + + Ok(plaintext) +} + +pub fn aes_cbc_enc(input: &[u8], key: &[u8; 16], iv: &[u8; 16]) -> Result> { + if input.len() % 16 != 0 { + return Err(anyhow!("Invalid input length")); + } + let mut cipher: Vec = Vec::new(); + let round_keys = expand_key(key); + let mut prev_block = *iv; + for i in 0..(input.len() / 16) { + let mut block: [u8; 16] = input[(i * 16)..(i * 16 + 16)].try_into()?; + block = block + .iter() + .zip(prev_block.iter()) + .map(|(b, iv)| b ^ iv) + .collect::>() + .try_into() + .unwrap(); + block = add_round_key(&block, &round_keys[0]); + for round_key in round_keys.iter().take(10).skip(1) { + block = sub_bytes(&block); + block = shift_rows(&block); + block = mix_columns(&block); + block = add_round_key(&block, round_key); + } + block = sub_bytes(&block); + block = shift_rows(&block); + block = add_round_key(&block, &round_keys[10]); + cipher.extend(block); + prev_block = block; + } + + Ok(cipher) +} + +pub fn aes_cbc_dec(input: &[u8], key: &[u8; 16], iv: &[u8; 16]) -> Result> { + if input.len() % 16 != 0 { + return Err(anyhow!("Invalid input length")); + } + + let mut plaintext: Vec = Vec::new(); + let round_keys = expand_key(key); + let mut prev_block = *iv; + for i in 0..(input.len() / 16) { + let mut block: [u8; 16] = input[(i * 16)..(i * 16 + 16)].try_into()?; + block = add_round_key(&block, &round_keys[10]); + block = inv_shift_rows(&block); + block = inv_sub_bytes(&block); + for j in 0..9 { + block = add_round_key(&block, &round_keys[9 - j]); + block = inv_mix_columns(&block); + block = inv_shift_rows(&block); + block = inv_sub_bytes(&block); + } + block = add_round_key(&block, &round_keys[0]); + block = block + .iter() + .zip(prev_block.iter()) + .map(|(b, iv)| b ^ iv) + .collect::>() + .try_into() + .unwrap(); + plaintext.extend(block); + prev_block = input[(i * 16)..(i * 16 + 16)].try_into()?; + } + + Ok(plaintext) +} + +pub fn pkcs7_padding(data: &mut Vec, block_size: usize) { + if block_size == 0 { + panic!("Block size must be greater than zero"); + } + if block_size > 255 { + panic!("Block size must be less than or equal to 255"); + } + let mut padding_length = block_size - (data.len() % block_size); + if padding_length == 0 { + padding_length = block_size; + } + data.extend(vec![padding_length as u8; padding_length]); +} + +pub fn is_ecb(cipher: &[u8]) -> bool { + // Check if the input is a valid ECB encrypted data + let mut seen_blocks = HashSet::new(); + for chunk in cipher.chunks(16) { + if seen_blocks.contains(chunk) { + return true; // Duplicate block found, indicating ECB mode + } + seen_blocks.insert(chunk); + } + + false +} + pub fn is_valid_english(input_str: &str, ratio: Option) -> bool { let ratio = ratio.unwrap_or(0.6); let mut total_chars = 0; diff --git a/problems/p1/src/main.rs b/problems/p1/src/main.rs index cfacbb2..d7d569b 100644 --- a/problems/p1/src/main.rs +++ b/problems/p1/src/main.rs @@ -9,5 +9,5 @@ fn main() { // 从十六进制字符串解码为原始字节 let hex_str = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"; let base64_str = hex_to_base64(hex_str); - println!("十六进制字符串: {}", base64_str); + println!("十六进制字符串: {base64_str}"); } diff --git a/problems/p10/10.txt b/problems/p10/10.txt new file mode 100644 index 0000000..f0802a5 --- /dev/null +++ b/problems/p10/10.txt @@ -0,0 +1,64 @@ +CRIwqt4+szDbqkNY+I0qbNXPg1XLaCM5etQ5Bt9DRFV/xIN2k8Go7jtArLIy +P605b071DL8C+FPYSHOXPkMMMFPAKm+Nsu0nCBMQVt9mlluHbVE/yl6VaBCj +NuOGvHZ9WYvt51uR/lklZZ0ObqD5UaC1rupZwCEK4pIWf6JQ4pTyPjyiPtKX +g54FNQvbVIHeotUG2kHEvHGS/w2Tt4E42xEwVfi29J3yp0O/TcL7aoRZIcJj +MV4qxY/uvZLGsjo1/IyhtQp3vY0nSzJjGgaLYXpvRn8TaAcEtH3cqZenBoox +BH3MxNjD/TVf3NastEWGnqeGp+0D9bQx/3L0+xTf+k2VjBDrV9HPXNELRgPN +0MlNo79p2gEwWjfTbx2KbF6htgsbGgCMZ6/iCshy3R8/abxkl8eK/VfCGfA6 +bQQkqs91bgsT0RgxXSWzjjvh4eXTSl8xYoMDCGa2opN/b6Q2MdfvW7rEvp5m +wJOfQFDtkv4M5cFEO3sjmU9MReRnCpvalG3ark0XC589rm+42jC4/oFWUdwv +kzGkSeoabAJdEJCifhvtGosYgvQDARUoNTQAO1+CbnwdKnA/WbQ59S9MU61Q +KcYSuk+jK5nAMDot2dPmvxZIeqbB6ax1IH0cdVx7qB/Z2FlJ/U927x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cxa2J9GXEV3kGDiZV90+PCDSVGY4VgF8y7GedI1h diff --git a/problems/p10/Cargo.toml b/problems/p10/Cargo.toml index 41151b3..06ef0c3 100644 --- a/problems/p10/Cargo.toml +++ b/problems/p10/Cargo.toml @@ -4,3 +4,7 @@ version = "0.1.0" edition = "2024" [dependencies] +anyhow = "1.0" +hex = "0.4" +base64 = "0.22" +common = { path = "../../common" } diff --git a/problems/p10/src/main.rs b/problems/p10/src/main.rs index e7a11a9..cf13814 100644 --- a/problems/p10/src/main.rs +++ b/problems/p10/src/main.rs @@ -1,3 +1,141 @@ -fn main() { - println!("Hello, world!"); +#![allow(dead_code)] +use anyhow::{Result, anyhow}; +use base64::{Engine, engine::general_purpose::STANDARD}; +use common::{ + add_round_key, expand_key, inv_mix_columns, inv_shift_rows, inv_sub_bytes, mix_columns, + shift_rows, sub_bytes, +}; +use std::fs::read_to_string; + +fn aes_cbc_enc(input: &[u8], key: &[u8; 16], iv: &[u8; 16]) -> Result> { + if input.len() % 16 != 0 { + return Err(anyhow!("Invalid input length")); + } + let mut cipher: Vec = Vec::new(); + let round_keys = expand_key(key); + let mut prev_block = *iv; + for i in 0..(input.len() / 16) { + let mut block: [u8; 16] = input[(i * 16)..(i * 16 + 16)].try_into()?; + block = block + .iter() + .zip(prev_block.iter()) + .map(|(b, iv)| b ^ iv) + .collect::>() + .try_into() + .unwrap(); + block = add_round_key(&block, &round_keys[0]); + for round_key in round_keys.iter().take(10).skip(1) { + block = sub_bytes(&block); + block = shift_rows(&block); + block = mix_columns(&block); + block = add_round_key(&block, round_key); + } + block = sub_bytes(&block); + block = shift_rows(&block); + block = add_round_key(&block, &round_keys[10]); + cipher.extend(block); + prev_block = block; + } + + Ok(cipher) +} + +fn aes_cbc_dec(input: &[u8], key: &[u8; 16], iv: &[u8; 16]) -> Result> { + if input.len() % 16 != 0 { + return Err(anyhow!("Invalid input length")); + } + + let mut plaintext: Vec = Vec::new(); + let round_keys = expand_key(key); + let mut prev_block = *iv; + for i in 0..(input.len() / 16) { + let mut block: [u8; 16] = input[(i * 16)..(i * 16 + 16)].try_into()?; + block = add_round_key(&block, &round_keys[10]); + block = inv_shift_rows(&block); + block = inv_sub_bytes(&block); + for j in 0..9 { + block = add_round_key(&block, &round_keys[9 - j]); + block = inv_mix_columns(&block); + block = inv_shift_rows(&block); + block = inv_sub_bytes(&block); + } + block = add_round_key(&block, &round_keys[0]); + block = block + .iter() + .zip(prev_block.iter()) + .map(|(b, iv)| b ^ iv) + .collect::>() + .try_into() + .unwrap(); + plaintext.extend(block); + prev_block = input[(i * 16)..(i * 16 + 16)].try_into()?; + } + + Ok(plaintext) +} + +fn main() { + let key = "YELLOW SUBMARINE".as_bytes(); + let iv = [0u8; 16]; + let file_path = "./problems/p10/10.txt"; + let b64_cipher = read_to_string(file_path).expect("Failed to read file"); + let cipher = STANDARD + .decode(b64_cipher.trim().replace('\n', "")) + .expect("Failed to decode base64"); + let key_array: [u8; 16] = key.try_into().expect("Key must be 16 bytes long"); + let decrypted = aes_cbc_dec(&cipher, &key_array, &iv).expect("Decryption failed"); + let decrypted_str = String::from_utf8(decrypted).expect("Failed to convert to string"); + println!("Decrypted text: {decrypted_str}"); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_aes_cbc_enc_dec() { + let key: [u8; 16] = [0x00; 16]; + let iv: [u8; 16] = [0x00; 16]; + let plaintext: Vec = vec![0x01; 32]; // 2 blocks of 16 bytes + + let ciphertext = aes_cbc_enc(&plaintext, &key, &iv).unwrap(); + let decrypted = aes_cbc_dec(&ciphertext, &key, &iv).unwrap(); + assert_eq!(decrypted, plaintext); + } + + #[test] + fn test_aes_cbc_enc_with_openssl_cmd() { + use std::io::Write; + use std::process::{Command, Stdio}; + + let key: [u8; 16] = [0x00; 16]; + let iv: [u8; 16] = [0x00; 16]; + let plaintext: Vec = vec![0x01; 32]; // 2 blocks of 16 bytes + + // Encrypt using our implementation + let ciphertext = aes_cbc_enc(&plaintext, &key, &iv).unwrap(); + + // Call openssl with stdin + let mut child = Command::new("openssl") + .args([ + "enc", + "-aes-128-cbc", + "-K", + &hex::encode(key), + "-iv", + &hex::encode(iv), + "-nopad", + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .expect("failed to execute openssl"); + + let mut stdin = child.stdin.take().expect("failed to get stdin"); + stdin.write_all(&plaintext).unwrap(); + drop(stdin); + + let output = child.wait_with_output().unwrap(); + assert_eq!(ciphertext, output.stdout); + } } diff --git a/problems/p11/Cargo.toml b/problems/p11/Cargo.toml index d45e6b2..7111df7 100644 --- a/problems/p11/Cargo.toml +++ b/problems/p11/Cargo.toml @@ -4,4 +4,5 @@ version = "0.1.0" edition = "2024" [dependencies] +common = { path = "../../common" } rand = "0.9.1" diff --git a/problems/p11/src/main.rs b/problems/p11/src/main.rs index 9918ef3..70ba68e 100644 --- a/problems/p11/src/main.rs +++ b/problems/p11/src/main.rs @@ -1,4 +1,5 @@ -use rand::{Rng, seq::IndexedRandom}; +use common::{aes_cbc_enc, aes_ecb_enc, is_ecb, pkcs7_padding}; +use rand::prelude::*; fn gen_random_key() -> [u8; 16] { let mut rng = rand::rng(); @@ -24,22 +25,23 @@ fn encryption_oracle(plaintext: &[u8]) -> Vec { data.extend(plaintext); data.extend(random_suffix); - pkcs7_padding(&mut data, 16); // in p9 + pkcs7_padding(&mut data, 16); if enc_mode == 0 { // ECB mode in p7 - ecb_encrypt(&data, &key) + println!("Using ECB mode."); + aes_ecb_enc(&data, &key).unwrap() } else { // CBC mode in p10 let iv = [0u8; 16]; - cbc_encrypt(&data, &key, &iv) + println!("Using CBC mode."); + aes_cbc_enc(&data, &key, &iv).unwrap() } - data } fn main() { - let plaintext = b"YELLOW SUBMARINE"; - let encrypted_data = encryption_oracle(plaintext); + let plaintext = b"YELLOW SUBMARINE".repeat(32); + let encrypted_data = encryption_oracle(&plaintext); // in p8 if is_ecb(&encrypted_data) { println!("ECB mode detected."); diff --git a/problems/p4/src/main.rs b/problems/p4/src/main.rs index 82b668a..c5e31d7 100644 --- a/problems/p4/src/main.rs +++ b/problems/p4/src/main.rs @@ -15,7 +15,7 @@ fn main() -> Result<(), Box> { for i in 0..=(plaintext.iter().len() - window_size) { if let Ok(text) = std::str::from_utf8(&plaintext[i..i + window_size]) { if is_valid_english(text, None) { - println!("Found valid sentence with key {key}: {}", text); + println!("Found valid sentence with key {key}: {text}"); } } } diff --git a/problems/p8/src/main.rs b/problems/p8/src/main.rs index b26e8fa..2a39fe3 100644 --- a/problems/p8/src/main.rs +++ b/problems/p8/src/main.rs @@ -14,6 +14,7 @@ fn is_ecb(cipher: &[u8]) -> bool { false } + fn main() { let file_name = "problems/p8/8.txt".to_string(); for line in io::BufReader::new(File::open(file_name).expect("Unable to open file")).lines() { @@ -21,9 +22,8 @@ fn main() { let cipher = hex::decode(&line).expect("Invalid hex string"); if is_ecb(&cipher) { - println!("ECB detected: {}", line); + println!("ECB detected: {line}"); } } println!("Finished checking for ECB mode."); } - diff --git a/problems/p9/src/main.rs b/problems/p9/src/main.rs index dbf1afc..2bbb7f4 100644 --- a/problems/p9/src/main.rs +++ b/problems/p9/src/main.rs @@ -16,7 +16,7 @@ fn main() { let mut plain_text = b"YELLOW SUBMARINE".to_vec(); pkcs7_padding(&mut plain_text, 20); - println!("Padded text: {:?}", plain_text); + println!("Padded text: {plain_text:?}"); } #[cfg(test)]