From 6d808aef548ab629c63f652ae5535131cdadc338 Mon Sep 17 00:00:00 2001 From: 0xalivecow Date: Tue, 29 Oct 2024 20:22:02 +0100 Subject: [PATCH 01/79] chore: debug official ci --- src/main.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main.rs b/src/main.rs index 5816ecb..59e561b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,8 @@ use std::{ fs, }; +// TESTING + use anyhow::Result; fn main() -> Result<()> { From 84d99f24149559409c084e3e4860b3fe3f99f509 Mon Sep 17 00:00:00 2001 From: 0xalivecow Date: Thu, 7 Nov 2024 22:47:24 +0100 Subject: [PATCH 02/79] fix: performance improvements --- src/tasks/tasks01/pad_oracle.rs | 34 +- test_json/padding_long.json | 1203 +++++++++++++++++++++++++++++++ 2 files changed, 1226 insertions(+), 11 deletions(-) create mode 100644 test_json/padding_long.json diff --git a/src/tasks/tasks01/pad_oracle.rs b/src/tasks/tasks01/pad_oracle.rs index 1a0c144..64eb2d1 100644 --- a/src/tasks/tasks01/pad_oracle.rs +++ b/src/tasks/tasks01/pad_oracle.rs @@ -31,7 +31,7 @@ pub fn padding_oracle(args: &Value) -> Result> { for chunk in &cipher_chunks { let start = Instant::now(); - let mut stream = TcpStream::connect(format!("127.0.0.1:{}", port))?; + let mut stream = TcpStream::connect(format!("{}:{}", hostname, port))?; stream.set_nonblocking(false)?; // Track value sent to server @@ -66,6 +66,7 @@ pub fn padding_oracle(args: &Value) -> Result> { //thread::sleep(Duration::from_millis(1000)); payload.extend(&attack_counter); + //eprintln!("I in q builder {}", i); attack_counter[i as usize] += 1; } //eprintln!("Time for qblocks: {:?}", start.elapsed()); @@ -82,34 +83,44 @@ pub fn padding_oracle(args: &Value) -> Result> { let valid_val = server_q_resp .iter() .position(|&r| r == 0x01) - .expect("No valid found in main loop") as u8; + .unwrap_or(0x00) as u8; + if valid_val == 0x00 { + eprintln!("No valid found in main loop"); + } //eprintln!("Valid value found: {:02X?}", valid_val); // Craft next attack vector padding; 0x01, 0x02, ... attack_counter[i as usize] = valid_val; // Check for edgecase if i == 15 { + let mut l_msg_check: Vec = vec![0x01, 0x00]; let mut check_q_block: Vec = vec![0; 16]; check_q_block[15] = attack_counter[15]; check_q_block[14] = !check_q_block[15]; - stream.write_all(&[0x01, 0x00])?; - stream.write_all(&check_q_block)?; + l_msg_check.extend(check_q_block.as_slice()); + + stream.write_all(&l_msg_check)?; + //stream.write_all(&check_q_block)?; let mut buf = [0u8; 0x01]; stream.read(&mut buf)?; - eprintln!("Buffer from pad check: {:02X?}", buf); + //eprintln!("I = {}", i); + //eprintln!("Buffer from pad check: {:02X?}", buf); if buf == [0x01] { - eprintln!("Valid padding"); + //eprintln!("Valid padding"); } else { - eprintln!("Invalid padding"); + //eprintln!("Invalid padding"); // Search for second hit let valid_val = (255 - server_q_resp .iter() .rev() .position(|&r| r == 0x01) - .expect("No valid found") as u8); - eprintln!("Valid value found: {:02X?}", valid_val); + .unwrap_or(0x00) as u8); + if valid_val == 0x00 { + eprintln!("No valid found"); + } + //eprintln!("Valid value found: {:02X?}", valid_val); // Craft next attack vector padding; 0x01, 0x02, ... attack_counter[i as usize] = valid_val; } @@ -127,7 +138,8 @@ pub fn padding_oracle(args: &Value) -> Result> { plaintext.push(iv[i] ^ (attack_counter[i as usize] ^ (15 - i as u8 + 1))); } //eprintln!("Attack counter after set: {:02X?}", attack_counter); - for pos in i..=15 { + let range = i; + for pos in range..=15 { //eprintln!("i is: {:02X?}", i); //eprintln!("i + 1 is: {:02X?}", ((16 - i) as u8).to_le()); /* @@ -154,7 +166,7 @@ pub fn padding_oracle(args: &Value) -> Result> { stream.flush()?; // break; drop(stream); - eprintln!("Time rest of calc: {:?}", start.elapsed()); + //eprintln!("Time rest of calc: {:?}", start.elapsed()); } plaintext.reverse(); diff --git a/test_json/padding_long.json b/test_json/padding_long.json new file mode 100644 index 0000000..3b37422 --- /dev/null +++ b/test_json/padding_long.json @@ -0,0 +1,1203 @@ +{ + "testcases": { + "2397d270-6a7d-48e8-8a7b-e464bcb00063": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "vm7Urlq3BHFPy34hxIn9yJJ4xKnmJYnkD02uUgznoIw8K+2HxtJLItkOcdXbIk2ADNXgjc3aQiTeCnTX2CJMng==" + } + } + +, + "44c19d5d-2149-400d-ab96-0764c440acac": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "SlelDIsQJ+qLVsVJaAQpyo/kaNAZ54eJrXOYaYqFuvf8SrED9lst6Iv/CdW0ydh76fy8Cf1TJO6M+wzXt8nZZQ==" + } + } + +, + "4a3ecbcb-a8ed-4c46-b63b-09f8fae33371": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "uWkaarF8CoHqIqWtNv5FkIebZ/e4v6QVvH09z2Ew8XehLpc6BgiAB5r3KXtJMuwdJjuaMA0AiQGd8yx5SjLtAw==" + } + } + +, + "ed63e4c3-db96-4d3e-b2b8-91fb78dc970f": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "y1wFLXHmhe2rHDgpeAISDU4kv6cJf77367yods6RxUT/bUuOr5N3u+APaRvZE5PRZrZGhKSbfr3nC2wZ2hOSzw==" + } + } + +, + "5a9de26e-5ad3-42e8-9523-cb5ad069a1db": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "xBVHDKq5LsWkoTaEti6ltXLiBvZAN/LvHWv1N/mFBH8TGZyt84nYHHw0r0cyCrAEC4WRp/iB0Rp7MKpFMQqxGg==" + } + } + +, + "e2fcaa72-d396-4ba9-885d-8c8449e48645": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "F8rc8G3tvt1lUfB664zqmawpXoxzM08hgpyjQnbE7MwW7M3noC9s8ez65PW3s6uYKbDA7asnZffr/uH3tLOqhg==" + } + } + +, + "541dc95b-080c-47a1-8c6f-86063c960ac4": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "0aDij+0vWLj+PfQJhqiLSBynGHhk+IvXw3mfT2YHQsCaRegAHHuWFT16VrHIncQtORnlChdznxM6flOzy53FMw==" + } + } + +, + "0314b333-aaed-4c48-9418-411233140585": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "HFeCxKmP42XhzuY8w0sMamhazEymf3b7EDzP0iskU4FKBKZAzc8tF5fv8YWWqiIZrxqrSsbHJBGQ6/SHlaojBw==" + } + } + +, + "b20e9178-af52-4112-8183-50c0112d0275": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "Z15CHkQ1iOkOwdZ/+TvmAMSS3UITjxaJ5N230T0bKql58C0KLiPqx3TlcKoC281Y6bUgACUr48Fz4XWoAdvMRg==" + } + } + +, + "7ee6d7e7-d4fa-4398-a615-6801555c6406": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "w516YKGlRGANdg+30RBCyGKPnGmv7o/uv567VzbBsNz76Dcv1TZxGlq8rcH9vek5W486Jd4+eBxduKjD/r3oJw==" + } + } + +, + "f590c5e7-52b8-4c5b-916e-ee0d3cd4a867": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "bB5OrSvRcitV8Q6k5IYhxZGHwK7tL6n4pO8mO9qY+lEn8PWUKjN29bVJhqlp6r4nnfr4niE7f/OyTYOrauq/OQ==" + } + } + +, + "382599d8-e079-4dea-a0e2-84349b0836a2": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "Vet2VvnayHeF5OF+FrBBMRZz5FXg+ziTPAWcW4ICYrEl8E8dlGN8Cj7UyUMTgMsXs8FCF59rdQw50MxBEIDKCQ==" + } + } + +, + "c9581cf4-b380-4f19-820b-924a108fdfab": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "/N7OSIyd0rJe+WI2BIgn/C+X9EZ+iGAfgE0CHepbkFSjyf49Dxd4JUMkcj26ggucl+3zNwQfcSNEIHc/uYIKgg==" + } + } + +, + "eecd178c-5d86-47c4-830e-1bf5aed430f9": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "ZQj80wGTXZiBwtoMbC3eRK0awvIdRhcUEzln9qEoWKilGytMXS9a6NlOA6IOxDG4IaQmRlYnU+7eSgagDcQwpg==" + } + } + +, + "4c1501ab-7cae-4567-a576-c359c1e7695e": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "AaG6i5IwVVr9ycYDaTYIw8AcBYEZkSIaqQE7ttR4hqlSfp8Wr1zKV+q965Za3r3o0HGSHKRUw1Htue6UWd689g==" + } + } + +, + "807bdda6-26ef-4e97-b6e9-bf27539187fe": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "fbPGRKxBPpXkqWfQltwOhpXqoWxz3La9rlyf8M3ppfg45jwlWydWlXGHfuXHfq7Rr10xL1AvX5N2g3vnxH6vzw==" + } + } + +, + "829d1b66-700c-458d-8116-b76890e97537": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "r8KymEWRwDRyOj0GB5Pt3swuAJ+Cdi7+DxGSY62R6qOCcg2OnGDEkmvDHTlrSv6qeDoAhJdozZRsxxg7aEr/tA==" + } + } + +, + "caa6a14d-6fe3-427d-a445-c6b15cf8b25c": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "ZTq4Us+pnWzcBFfsNTncXNVR8iVoV2epE1xeP15cJEQDW0erZpZSTJdafN8LnLVc15ZKoW2eW0qQXnndCJy0Qg==" + } + } + +, + "df9ae9f0-51ab-4613-b3c2-56e6f2de74b6": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "D5X0/aOPzv/YnaevH3A0zrrt/MPG68P9+o16Vs9R+Yr0dKbVdx0oCZraoQe9u5iSLvKr33wVIQ+d3qQFvruZjA==" + } + } + +, + "c591b3d2-05b5-4792-a502-da4641461533": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "y2IUs+cKPmUpeY9hdDDSTGatuvZVthvWqmdC5/unBWr5OKFFXuI+9BIv9pRIctmY5iusT1XqN/IVK/OWS3LYhg==" + } + } + +, + "3f5c5abc-81e6-4540-873a-ea5498df297c": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "yDfhetbRPSBFlGvLotAsnD4E4knnUcppjw/gREIy9YHeNOmqoRu3LDsQbRUw6tQHm6XkoKoTvio8FGgXM+rVGQ==" + } + } + +, + "5b6c1490-a77d-4a2a-9976-9d4635cf195c": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "NabDKqpsyhbP+wPVnpDYakbwpyn/z/rJWra2XDUBHRRCkreZR2nODjwKQY47X3i7or66k0xhxwg7DkSMOF95pQ==" + } + } + +, + "852c775a-0bff-42e4-87f4-3991b58eb1dd": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "RCm+XJz0gMd0OCVhrvACw+lpNkiOJEiT0EbZt/cMgToNjqsRM95ncabJZnqKmqiuzOamGzjWbnehzWN4iZqpsA==" + } + } + +, + "a5a86d99-4bfc-42b4-9d8a-07f1a6f6cbba": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "UZRcMpvxPxszgcIYtp9vGbL/f9EQ0AVRaHw5WF3C8EEjo7J68BHKNeoKVA16F/FduyG/cPsZwzPtDlEPeRfwQw==" + } + } + +, + "cb260f8a-508f-428b-a135-00d8b0348832": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "ICiC/LcF4LhQSKrAi7w/HzTef5YyDwE6sjNe+XZeoH/OkclPUsj3mo/xoJuGOSfzBUDERVnA/pyI9aWZhTkm7Q==" + } + } + +, + "e8aa9530-60ae-4c5a-9e0b-93dbfd0d6660": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "5kE3TUL4Lq2jKNgNlVYxqKZ1nM5x2yCx09yrNs9f8fWjBzdEENHczF5uHZ3uKIfoxgU6ThvZ1cpZahif7SiG9g==" + } + } + +, + "7c5067be-0e0e-4b07-bac6-ffdd8652db55": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "6piHQ3VtWEvfOa/zf4VWJS6PH+QWlb7+aZDwyJlcfDIDalbg9+G9WT9YJhcrYix9XV9b6vzptF84XCMVKGItYw==" + } + } + +, + "6ffc6d43-0346-4a7c-a525-c93842ff2074": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "UzXj9SuFBZTpiEEqzw/DVgv1sLzN5ncacQbfK5DbUg91sKz12uzQoBvUTeXIG2qOTbmh/9Hk2aYc0EjnyxtrkA==" + } + } + +, + "b7567d39-e6a8-4259-a292-8e6790df08b1": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "lNc3wjie7beF0ZLOfhzX6Tzosr+02y9idqgrv48u3Yyd0okKnK7AmLQEHAiQe0qGK5WEAJemyZ6zABkKk3tLmA==" + } + } + +, + "c34d7d89-a620-432b-aa98-8f1074c826ba": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "Cg0XaEGegQNznReu8KeQ+NDEArv5nZbYfui2Nny8omXeHofazD2jgDnq0ui8uov9V56K0Mc1qoY+7tfqv7qK4w==" + } + } + +, + "6b823c15-919b-4525-95b6-a64eff1a671b": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "1u2ethWeOGIavEEWsbgSqkUth+0cmPFgN4pYvT67oyxvWk1vGEv28vvDjy1OmPMIB95AZRND//T8x4ovTZjyFg==" + } + } + +, + "72145942-656a-40ff-b981-79b0224ae80b": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "qIv/gRp4qoNhw6d2pZK2NhI3+rXboQ7CUQ7vmFsL8AA67qvcb1OrOxj1Z63cEvmBAfSm1mRboj0f8WKv3xL4nw==" + } + } + +, + "8ade9aa1-7cea-4d1f-ae32-dfa72c3fa322": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "Hn97+gE6oeY1h4W7xN/olVE7koHA/PILlbJk8Vh56c9V/SSSZVRneIUmrl1Z/82JUfQpmG5cbn6CIqtfWv/Mlw==" + } + } + +, + "7e894b2e-d5a0-4590-bc3d-e93672dd9261": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "ttx3yJh+GDifmTwxjCqcv8zUZoi4ExKzogq2ilOTK3ab1agUmk/pRxrMKH1s0Nya0IGlHpFH4EEdyC1/b9DdhA==" + } + } + +, + "d1ce21a1-6295-4729-a9f0-e39cc4aa4f40": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "BqB4yVG2NY2fmvaAGYc6otIgW32JKOaHv86vD8Zz+MNZPz0sR7PR+qsD15vKkE6SxGIwJky72PysB9KZyZBPjA==" + } + } + +, + "f4d6f056-650c-4b6f-ae51-6f44918968c2": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "Ga9utTnt8SCSBV4l2sDJ6n0SLkx6ajuFI5MZU/V4LGl4QYMCuOIeYxPqpLsYaBl+1LqOCLPqF2UU7qG5G2gYYA==" + } + } + +, + "55dc70a5-e5b4-4ada-bab0-0e0f51cdd6e0": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "g+E+xh8lT3kNEC5nC3wEmgaV47JEa0cxVj2XzTLZimbNNhmWAT9Enhe5T5463QOvHqYUnAo3TZgQvUqcOd0CsQ==" + } + } + +, + "db3533ad-300b-4067-a394-4b4506d7e740": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "cMbGvtBs3pEcfs2wmgTfEGwzpuvN+03DVCUXRnuhjXdUhoPSqu/+6nF+7W42f7C/jzCO2KHn9+x2euhsNX+xoQ==" + } + } + +, + "7ba96858-7e5d-4d76-9151-4c24a89f141a": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "S12Mc1V7Q7hPAWPk3JKrOPPWwoJNrhvVQDhQLFMPDUxtrduMRXbAosYcp9zbHK/Zp6zWhk5+yaTBGKLe2Byuxw==" + } + } + +, + "45650223-8b12-43ec-8ba4-5739d7f8e1b7": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "bq0ehniEAiH6yNKeyvCNGmwl6ifyJiWm/Jh3+pgSqJ+oiJ2+GASK20JCQWuOAVXeNSGQtBMMg91FRkRpjQFUwA==" + } + } + +, + "25535889-3ce4-4315-a60c-d17cade233b6": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "G1JIQcHRZeL5vhZOEHk3R+lnnfJKtmW0ehGKo7NNaf3p+muo6B4NSR1ev2z+3BapaUZmouMWBE8aWrpu/dwXtw==" + } + } + +, + "6e48220f-0dbb-4a70-88d5-3843d92beb22": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "03u4zIxW/dc3n+TPZ46nohJwrGUnEr8Kw4pqfc7ewJKmBrMk/AGP35zI7JT96wQZ25e+LvcJhtmbzOmW/usFBw==" + } + } + +, + "c064be77-b978-45e1-8872-12d810f51c7c": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "CUlnUH1Oykz+tVfAx08vx4n1KTfkGix9J7EcHO/UQ/wtRs/qdhLCgGM3QL86K0vAemvC4H0ay4ZkM0W9OStK3g==" + } + } + +, + "daa98c74-3bb6-482b-8515-35130b328a37": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "CujN9/8yzR8n7JjQ6lcWa5FbAjSqYPwnd1htDi7nstjGVQJMD5tSlz8t6FbH73b/WzoPRgSTW5E4Ke1UxO934Q==" + } + } + +, + "faf4fdad-f71e-45e1-8cd9-35ab5c83a94e": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "koNoZ0F+7UP8XGmmGvzqsMxEibKLRKer8j0/HP6N3HaOJ4N7eeyn6sRCNuBC8Q9HCriOcXLkruzDRjPiQfEOWQ==" + } + } + +, + "539aed2a-be20-4837-9571-bf72cbbce7c1": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "P5BRSYQQwC+e3Wr6a0iZmCDOWrwD0Oqbl2nd3CpjCkjQ6rKAPSuusYc8yGVnCQHeo6a/ijYjp7eAOM1nZAkAwA==" + } + } + +, + "5b97b7c1-2ea6-4324-8208-fc8b60421a71": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "GThxMuyHpeSFMuO2E9x6ZLJxY3bqqbSjEFPONgHRbcNIC9qbORFkJhJdzL5SbW7nPLbXkTIZbSAVWcm8UW1v+Q==" + } + } + +, + "a457cfe1-4972-48c1-9ffd-f6cd58259cb4": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "RWZSt4GByw8blm0TPnNJQWx8Z5M7jahfmCuSrXcNdFu+t4kcyeuUSTNGpQsZIQy4iX2EFsLjnU80QqAJGiENpg==" + } + } + +, + "fde675ab-8ceb-461d-b917-752ad5e10683": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "UYnLQHhdhWXjImgi9vj6EECVlol0EFzLojOdD5P0zml4llbHYtxaS2EntJwb31SUsQtbzWnUU01mI7GeGN9Vig==" + } + } + +, + "13f792e3-5f90-4f1a-9f2c-d9ad7546e965": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "iUaOYIKxDD3m1gnBcDqxENggOM8Ct0GZbxgzCcr8+d4SZGsTNTBegtltYyLNIveNqEpmGT44V4TeaWYgziL2kw==" + } + } + +, + "1363c336-61c3-44f2-b034-a7df4f51cac0": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "+8NreDMpSmce1BS0CwlWTe6Fbvh2wGhl7pY5YjfPQ3Y1cCjYYdLGKeadiQMs2UhUzpcl0mrazy/hmYwBL9lJSg==" + } + } + +, + "dacfb5cd-794e-447a-a73f-5727a4be381b": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "aHZaILzJqHrpeagmBOELoHIk4WkMx3Tt+vQ3IQcG48H7Y2GH24+YL6Hnm+24w7nkt8tsjdCHkSmm457vu8O4+g==" + } + } + +, + "8f57a6b7-ae39-4701-82c9-b6b93797e501": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "6sLGtM2rLi1YBtcoHVAhirDLpbl50CNCCKRmxsxLVxJS78+dGozdAsF7zt74sWEJ2ILClxGE1ATGf8vc+7FgFw==" + } + } + +, + "ed4852b2-ae49-471b-aa43-5ca40520f5fb": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "p77RUg7oMOEAmQmWetO3INtX9T4UJCeqNmdILmufV6pCqTmQ7V6oIijdSRrelvw7viU0muZWoSQv2UwY3Zb9JQ==" + } + } + +, + "384ac609-7112-4c25-a1e9-8f470b2998c9": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "VrDXpBoOuWJ2zoJlcmBmj3E1CXm3bOj3Xw6yMZymH0JocA0RqBmHtHaei5tNJlwdYmsAG6MRjrJxmo6ZTiZdAw==" + } + } + +, + "22542b77-5761-427f-b0c0-e04feec5f1b4": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "1iA+cp1BATVWLvJQC8WbYowiGLpvQnmkiNVHy+j+fbid2fwlplsq1Xz3aIB8kLWCdPPxL61TI9N7822Cf5C0nA==" + } + } + +, + "fd978de7-ad93-4f4c-b0fc-53a0cd82aa6c": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "f5M4Cljp9wYiFtLeeY0xullO97md6wc25/IeM//u4luv+xRfwV8uOlTesdGEMsG2KaoZVcpXJzxT2rTThzLAqA==" + } + } + +, + "2cb54cb5-4c3b-49f8-9fd8-5612e062a794": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "h7MAdEyFyMeQkeaST+JzXT9LLoMr1oN0sSbHh99bHv47amSZ0wnob1drT3DRMWcV0X9pk9gB4WlQb0py0jFmCw==" + } + } + +, + "6fa0219c-5b86-44a3-8906-d23b947a2bc4": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "bYC+gQ/FQgTshymtgqKI18BdFGqHddn1kGktLkYnL+Y9aLzwk1X9c45tEiuUdRfkkYqx+phd9HWJaRcpl3UW+g==" + } + } + +, + "413f61b6-4830-4537-aa37-4d7a9217e83e": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "o/ttuaXRBEYcrqRvrO4Rx5iX076H7spBRJGLbYn8o/aUEAAdIPF1V0HPtAooYAfTb2UNFyv5fFFGy7EIK2AGzQ==" + } + } + +, + "c23d0451-e97e-4cb1-89bd-1d0f8c161b84": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "h8Kwck8yxXgGHIRiQpfMeHqaEBEgaZAx8+sEYA2XU4Fe0Ustok2D/8FqtfN6UC86uMVGJ6lFivnGbrDxeVAuJA==" + } + } + +, + "14db3036-ad5b-43b1-b0cd-63c7d275c901": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "n3f2r/oc/F5cRt/KtLRs5oRi92ixYVyq1q4c90K0Eg+jJnb2x4i4JcjAhQxhKtsq5TZ7/MyAsSPPxIAOYiraNA==" + } + } + +, + "495b74a6-84d7-4704-9f2d-d4d02e3b2deb": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "VUDL46a2gYXIzruEzCwoILc8eA4rx0oGDB0rEyR0vj504Pj5RD0RYA474ZH+/lwAkhj18081GGYJP+ST/f5dHg==" + } + } + +, + "09111522-0191-49c1-baee-9e7452ade6d6": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "R7x6DtdfjxMKn7umK1YP6Ih1tmRfXG7Ea7r9/897ELESJQzZTbVgRxHtDIBif3StsvMB00a9aUEW6QmCYX91sw==" + } + } + +, + "04e31e23-bf5b-488d-98ea-0916ea054a57": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "vTpRyVKVxIlBH+SVp/+dGaLnicvNd3OnlzEbYoPv1Y++pZCSjStzPHeAOmOexYut5IidmIYjejpwhD9hncWKsw==" + } + } + +, + "db4e4f3e-af56-4e80-915e-2833e1720152": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "qNJ6UWDZtHbuLU8XJ63XoZx0732T6dXl27+uRiEaUCbKKfW28dBao9fWUxxgNNInpzz4vPrYU6XQ0lYeYzTTOQ==" + } + } + +, + "4c27df40-e586-4454-96fd-bbd38d9c254d": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "3R9meuHw44Q4I7gPKLb9yj/KiixEw50lPXL0Ccad28idMKbspSBcP9msU5G6NW1B7Zir5q4oVTneqFaTuTVsXw==" + } + } + +, + "4bc30fc8-6515-4da4-b9ec-d3659e26977e": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "5cN2IR5Ml/JXaD6GXjdOhWaZj86JypxJgD2Dx82DOd0NfGmgS8tdplA+iOk2qvIVWjRkqkDDVKBXOo3rNarzCw==" + } + } + +, + "30857906-6323-484f-a42e-2a9383a878a5": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "0DQEb9ILeloWef9d4Blr6fmxTBwrW6jkDfBXsrCAHV02UEkMuGFKlq9v6aMZK9EFR11EBrNpQ5Coa+yhGivQGw==" + } + } + +, + "a483d63f-115b-4e15-a8a4-9d6f69c30534": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "HyGdkwKolhIEXPXWdjJ8mWUL1Rlwuvfx8DJss5NM2cNqWLDOF+e0pU5iBF9NgoRGWom9xBzvvaNJZgFdToKFWA==" + } + } + +, + "9c7f225f-0fa8-45aa-8fba-995cc0880827": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "vqwFkwWUqcrca9kLD4GfMQ8Kdi1E3FV5Ar2p9+XrN9FE7R/UUjtcyOFVKDZJrZHa6+wS3lkzVc7mUS00Sq2QxA==" + } + } + +, + "3c531189-5fa2-46fd-a913-c5da0bd26e5b": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "XUNMJYgLjnoUh+RaP7fFjslFehaIteonz5eMQFXeU0BQ48MWYAlOsN1q/0QpxdsNrbnOHGsBR7babvpGKsXaEw==" + } + } + +, + "8fcf110e-7b2f-4bef-bdca-cb3e4e852309": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "gQHsqB57y8oIWZvnO1IXhtV70YGLTgihQ/l338iqqw0eO+oRuOBupNwr9ePqdy+lxFTnG7PoZ6LbL/Dh6Xcuuw==" + } + } + +, + "8369fe41-f1c8-45ac-9823-2eb4d6644e0b": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "KF/IEz9b9JC0H7WmymmXZ6qADb0+wmFvZsB87y4rwqMvmnkcvTJhjgm0WVeFJDJk3gV0FrY6aIgOsFxVhiQzeg==" + } + } + +, + "aac997d9-c874-41ff-b9cb-70c3c966b1d4": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "Tq2DLoykYhAPmjf8Y+G8ADsFvtanTCJHq9bV0iKDM86RwdEvT3m3MYoxQwi6Zm8/CJTcJURxvjeNNUYKuWZuIQ==" + } + } + +, + "571a4cec-707c-49ec-96ad-d1035d212087": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "cd6JdgsmhX4QyBWhRmEFbvnfDLwuoCmgtwTDHtsGVEAnt5Yj/w1pszvu05Djlp33BwebKfQFYLU86taS4Jac6Q==" + } + } + +, + "af25e252-7418-4fa1-a9f4-acde2d55c989": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "yHYApE1BDfVL6EgbDLjXK1mA+godz5Ho1eeCLEGpocxGdlWluJGilib6X8tTL3teKA5Yr7OZq5Ah/lrJUC96QA==" + } + } + +, + "4cb90117-6313-4deb-9ac5-19f81f0fa0d7": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "hYVhDlhDSfGOZrdm/cfQs5+pwgsX6KVssfh3sIHXL59i8PoGk/fxIwyJd8/TL5Gymh73DJj/+CULjXLN0C+QrA==" + } + } + +, + "4a7da8a2-3ed9-4c69-bbc0-84c12d8dda26": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "uOBBTKX9bc9P729W0L6FnlD9JN4gDCPAP5xVN9TrvjJCo+u7J5lNo87BJIxiRxI+vazmsSyRRKXJxSGOYUcTIA==" + } + } + +, + "dc4e9268-1faf-4e59-9bd0-632f98fc54b1": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "/ryLcAF/i4K0Q908nNTVn5ORHINBk3BVcAWfZY04WD0C8X8DpeO0tiUWTzq6zfHCC39yCa7rvbAiEko4uc3w3A==" + } + } + +, + "02b0b683-f7c8-47c6-9d4c-b368ad41c6ac": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "Dh5oC6q/jnBkFSi/pqoD7v+zOm/QZVLGtBkkaBe2yf4FQ+F68esNu4FxJhDK8gjqpnfscPrjBL2GdSMSyfIJ9A==" + } + } + +, + "4acf39d6-d489-45c7-bfcd-6d2e15a634dd": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "c1BvpQp0fAz4FFC7NCEja9iP4oDJb5ihj8ZfG8NZkMNpMfs1cX/6jKv8fRi6ua2SlRX2P3p384qs+HgaubmsjA==" + } + } + +, + "99ed3f0a-2e2f-4779-8afa-cd85b9c4fd0e": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "aTlxJX03/IMHzxK4ox6l7Vx9Y8sFYb63JC0JulVWxaePM/1+zGz47sIBI4gjLz7+qgvwdMdk8ejFBSaKIC8/4A==" + } + } + +, + "073e7165-34c5-4378-b782-571f8f1a68e3": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "vpRYbgOlxfsXgI5E14rtbHOGmA1am/gNNPuJcEI7qHXyeVegrfZeRXKDpPVbZfZEFJpaqqb+V0N1h6H3WGX3Wg==" + } + } + +, + "de43e72c-2c95-43e6-8c2e-357ca7538390": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "bUqEnu51k6UorPZh3coyIpFotnyqQ0NMVJblugfhUYXOsKexkxTkohMDywuHVusDjsiqu5gc7aQUB84JhFbqHQ==" + } + } + +, + "a0d4e7f3-eb77-4a0d-9a20-b2415038b0c7": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "aTDl1UOaGhyfAM/oMIUXOlEsZdQ91ByWbNMZ7DMbx1poVBMWBmkRdAEC8W6W6UkvtY4eHA1hGHIGBvRslelIMQ==" + } + } + +, + "691e973a-3598-45f4-93b1-74348a423bd4": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "dsBQl0VypyGciDcGbFZEsSO9xWarGMwHTlXk+0qgWYQ61Jo931Dy3aLUAWjhq8BUtYOXN9RY+9ul0ARq4qvBSg==" + } + } + +, + "5cbb74c3-b71e-4482-9324-d3ec31944ae1": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "cnWbIbq2LFSyEuVA7CvtaNdEvOGbJtyuArna4Co+d0mSsAWfKPhOk+yEFLsa4bbdSjUIlSPwR5XrgBG5GeG3ww==" + } + } + +, + "5ba9b9a7-b347-4942-8c77-0697328cb6a0": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "q1Aqo8bOgalL5OUeLMOlUFBm1XO9wr+V9uBSS4XZ2aY6SBt3kS1diUGjewx5zYOjqhIWfZolVI9Gp34Oes2CvQ==" + } + } + +, + "6c42e851-cb6f-4c1d-8c17-9bdc8e0e6de7": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "UTmqk0zLVPAXxObZ3mtdE8c0bmys8uC/F9tbOCec474T3Yo2WbWrVBakp4awM3F+Vv+HPFK9olIRoKKEszNwYA==" + } + } + +, + "5c18d55f-a0fd-46a5-a1ac-93a810646e32": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "v8ADatzqlIjOhap07uLTuntszynDas18n19UEI4GyDTqdjjkgJNlvjKuk98yqHIyQtA17oubbLg1qpbdMahzLA==" + } + } + +, + "6b1b291e-8def-4c0f-83e0-6291d4ab240c": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "G/CjHOiAwXTQ3xcS6Db/X7Xqw84UGA26YEcmGfRCWUVcBXe9hwi7ppwcOQeVBlcOJNJ6t4wAsqCbGDwFlgZWEA==" + } + } + +, + "364012fc-464f-438e-ba9f-e63c203887f6": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "uqMG21goTh4x+ZDjcPOKwkbiTUIGSNtLLr9Gr36jFCwS7wwRJGoYNYBg2VNCyyDHEDkBGy9iETOHZNxRQcsh2Q==" + } + } + +, + "f0656f9e-f46a-4839-a370-f62229cfb725": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "cIM41ydOUh6wTFj8wuCFP21NbrtApWsrbpnZYIcLF0jpzkC6/TruFNsPGawOavVvqYZNsPYy5xLcCxyuDWr0cQ==" + } + } + +, + "0c465f36-3609-49ed-97a0-f3f466074014": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "+4M26CAsDZSQGPgauO26O9hRmL8swl4YNW6kqfifk6bHsAb3ti8NpIduNp0ql9FWFBwL/b0nBKKAajOfKZfQSA==" + } + } + +, + "f487be27-8e21-4c99-a0e8-24ccbf91df0c": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "r1Vg5MBZTWUlTSmBZbsZiNxnDA9p9ikQs1ZOeW/JsLetmmVTYjaxcvMU+GPUTnS6k8xoWWk+uHT0EP1h1051pA==" + } + } + +, + "2d8899bf-6130-4211-8df6-331d6d102c76": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "+6/kIzx1obQkV1F0ZeCeif4wxrYER3KUepAbgbakQ69SrXWZaSVrzdMpdNSiy9WRsdV4k2ItYsvULXHWocvUjw==" + } + } + +, + "a321a245-030a-481d-b348-3cc27aecc4a8": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "EMQYQ3iCqrqlYlukmHOuLdBzf9NxziuNRsLjpC494kJMllEtotoFr4Zn7t4pWviK4xRcJ6nSDKmBY+vcKlr5lA==" + } + } + +, + "b378f388-943e-440d-81f5-e15f76f4e68a": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "QFXeShopbJ7B+GS3dv4XJ9tYjJCnJNOl1etTxY9dG/Lhuozib7f27uQBsSCQxCPUEJyB6GS//+jjBbQik8Qiyg==" + } + } + +, + "16d21da6-76af-42bf-a395-4699f8c3fd4f": + { + "action": "padding_oracle", + "arguments": { + "hostname": "localhost", + "port": 1337, + "iv": "AAAAAAAAAAAAAAAAAAAAAA==", + "ciphertext": "WMoU8g20SWQ8N1wBAq9gfa0EhfUnPTS34bY783m/2NFvXHiikuIUx//qRepcHOmdzSF1qJnqHcH47kDoXxzogw==" + } + } + +} +} From 811e2b21f65169d70f360d94b644cfabb7ff99f0 Mon Sep 17 00:00:00 2001 From: 0xalivecow Date: Fri, 8 Nov 2024 13:09:12 +0100 Subject: [PATCH 03/79] feat: Implement field object and addition Starting work on proper field object Polynomial addition working --- src/utils/field.rs | 70 ++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 67 insertions(+), 3 deletions(-) diff --git a/src/utils/field.rs b/src/utils/field.rs index 5645b04..37ceb74 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -1,7 +1,59 @@ -use anyhow::{anyhow, Ok, Result}; -use base64::Engine; +use std::ops::{Add, Mul}; -use super::poly::gfmul; +use anyhow::{anyhow, Ok, Result}; +use base64::prelude::*; + +use super::{math::xor_bytes, poly::gfmul}; + +#[derive(Debug)] +pub struct FieldElement { + polynomial: Vec, +} + +impl FieldElement { + pub const IRREDUCIBLE_POLYNOMIAL: [u8; 17] = [ + 87, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 01, + ]; + + pub const fn new(polynomial: Vec) -> Self { + Self { polynomial } + } + + pub fn mul(&self, poly_a: Vec, poly_b: Vec) -> Result> { + gfmul(poly_a, poly_b, "gcm") + } +} + +impl Mul for FieldElement { + type Output = Self; + + fn mul(self, rhs: Self) -> Self::Output { + FieldElement::new( + gfmul(self.polynomial, rhs.polynomial, "gcm").expect("Error during multiplication"), + ) + } +} + +impl Add for FieldElement { + type Output = Self; + fn add(self, rhs: Self) -> Self::Output { + FieldElement::new(xor_bytes(&self.polynomial, rhs.polynomial).expect("Error in poly add")) + } +} + +impl AsRef<[u8]> for FieldElement { + fn as_ref(&self) -> &[u8] { + &self.polynomial.as_ref() + } +} + +/* +impl From> for FieldElement { + fn from(item: Vec) -> Self { + FieldElement { bytes: item } + } +} +*/ #[derive(Debug)] pub struct ByteArray(pub Vec); @@ -105,6 +157,7 @@ impl ByteArray { #[cfg(test)] mod tests { use super::*; + use base64::prelude::*; use std::fs; #[test] @@ -199,4 +252,15 @@ mod tests { assert_eq!(byte_array.0, vec![0x55, 0x55]); } + + #[test] + fn test_field_add_01() { + let element1: FieldElement = + FieldElement::new(BASE64_STANDARD.decode("NeverGonnaGiveYouUpAAA==").unwrap()); + let element2: FieldElement = + FieldElement::new(BASE64_STANDARD.decode("KryptoanalyseAAAAAAAAA==").unwrap()); + let sum = element2 + element1; + + assert_eq!(BASE64_STANDARD.encode(sum), "H1d3GuyA9/0OxeYouUpAAA=="); + } } From 6e33e2e44c0b3f5592409c633de4a0fd793d2342 Mon Sep 17 00:00:00 2001 From: 0xalivecow Date: Sun, 10 Nov 2024 18:30:41 +0100 Subject: [PATCH 04/79] feat: Initial multiplication working --- src/utils/field.rs | 186 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 179 insertions(+), 7 deletions(-) diff --git a/src/utils/field.rs b/src/utils/field.rs index 37ceb74..f0da8f0 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -1,13 +1,104 @@ -use std::ops::{Add, Mul}; +use std::{ + env::args, + ops::{Add, Mul}, +}; use anyhow::{anyhow, Ok, Result}; use base64::prelude::*; +use serde_json::Value; use super::{math::xor_bytes, poly::gfmul}; +#[derive(Debug)] +pub struct Polynomial { + polynomial: Vec, +} + +impl Polynomial { + pub const fn new(polynomial: Vec) -> Self { + Self { polynomial } + } + + pub fn from_c_array(array: &Value) -> Self { + let mut polynomial: Vec = vec![]; + let c_array: Vec = array + .as_array() + .expect("Input is not an array") + .iter() + .map(|x| { + x.as_str() + .expect("Array element is not a string") + .to_string() + }) + .collect(); + + eprintln!("{:?}", c_array); + + for coefficient in c_array { + polynomial.push(FieldElement::new( + BASE64_STANDARD + .decode(coefficient) + .expect("Error on poly decode:"), + )); + } + Self { polynomial } + } + + pub fn to_c_array(self) -> Vec { + let mut output: Vec = vec![]; + for coeff in self.polynomial { + output.push(BASE64_STANDARD.encode(coeff)); + } + + output + } +} + +impl Mul for Polynomial { + type Output = Self; + + fn mul(self, rhs: Self) -> Self::Output { + let mut polynomial: Vec = + vec![FieldElement::new(vec![0; 16]); self.polynomial.len() + rhs.polynomial.len() - 1]; + for i in 0..self.polynomial.len() { + for j in 0..rhs.polynomial.len() { + polynomial[i + j] = &polynomial[i + j] + + &(self.polynomial.get(i).unwrap() * rhs.polynomial.get(j).unwrap()); + } + } + Polynomial::new(polynomial) + } +} + +impl Add for Polynomial { + type Output = Self; + fn add(self, rhs: Self) -> Self::Output { + FieldElement::new( + xor_bytes(&self.field_element, rhs.field_element).expect("Error in poly add"), + ) + } +} + +/* +impl Add for Polynomial { + type Output = Self; + fn add(self, rhs: Self) -> Self::Output { + FieldElement::new( + xor_bytes(&self.field_element, rhs.field_element).expect("Error in poly add"), + ) + } +} + +impl AsRef<[u8]> for Polynomial { + fn as_ref(&self) -> &[u8] { + &self.field_element.as_ref() + } +} +*/ + #[derive(Debug)] pub struct FieldElement { - polynomial: Vec, + field_element: Vec, } impl FieldElement { @@ -15,8 +106,8 @@ impl FieldElement { 87, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 01, ]; - pub const fn new(polynomial: Vec) -> Self { - Self { polynomial } + pub const fn new(field_element: Vec) -> Self { + Self { field_element } } pub fn mul(&self, poly_a: Vec, poly_b: Vec) -> Result> { @@ -29,7 +120,19 @@ impl Mul for FieldElement { fn mul(self, rhs: Self) -> Self::Output { FieldElement::new( - gfmul(self.polynomial, rhs.polynomial, "gcm").expect("Error during multiplication"), + gfmul(self.field_element, rhs.field_element, "gcm") + .expect("Error during multiplication"), + ) + } +} + +impl Mul for &FieldElement { + type Output = FieldElement; + + fn mul(self, rhs: &FieldElement) -> FieldElement { + FieldElement::new( + gfmul(self.field_element.clone(), rhs.field_element.clone(), "gcm") + .expect("Error during multiplication"), ) } } @@ -37,13 +140,32 @@ impl Mul for FieldElement { impl Add for FieldElement { type Output = Self; fn add(self, rhs: Self) -> Self::Output { - FieldElement::new(xor_bytes(&self.polynomial, rhs.polynomial).expect("Error in poly add")) + FieldElement::new( + xor_bytes(&self.field_element, rhs.field_element).expect("Error in poly add"), + ) + } +} + +impl Add for &FieldElement { + type Output = FieldElement; + fn add(self, rhs: Self) -> Self::Output { + FieldElement::new( + xor_bytes(&self.field_element, rhs.field_element.clone()).expect("Error in poly add"), + ) } } impl AsRef<[u8]> for FieldElement { fn as_ref(&self) -> &[u8] { - &self.polynomial.as_ref() + &self.field_element.as_ref() + } +} + +impl Clone for FieldElement { + fn clone(&self) -> Self { + FieldElement { + field_element: self.field_element.clone(), + } } } @@ -158,6 +280,7 @@ impl ByteArray { mod tests { use super::*; use base64::prelude::*; + use serde_json::json; use std::fs; #[test] @@ -263,4 +386,53 @@ mod tests { assert_eq!(BASE64_STANDARD.encode(sum), "H1d3GuyA9/0OxeYouUpAAA=="); } + + #[test] + fn test_field_add_02() { + let element1: FieldElement = + FieldElement::new(BASE64_STANDARD.decode("NeverGonnaLetYouDownAA==").unwrap()); + let element2: FieldElement = + FieldElement::new(BASE64_STANDARD.decode("DHBWMannheimAAAAAAAAAA==").unwrap()); + let sum = element2 + element1; + + assert_eq!(BASE64_STANDARD.encode(sum), "OZuIncPAGEp4tYouDownAA=="); + } + + #[test] + fn test_field_add_03() { + let json1 = json!([ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ]); + let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let sum = element2 + element1; + + assert_eq!(BASE64_STANDARD.encode(sum), "OZuIncPAGEp4tYouDownAA=="); + } + + #[test] + fn test_field_mul_01() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let json2 = json!(["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + //eprintln!("{:?}", element1); + + let result = element1 * element2; + + eprintln!("Result = {:?}", result.to_c_array()); + + assert!(false); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } } From 6431a6636ed777e190355b36d81d850946b98244 Mon Sep 17 00:00:00 2001 From: 0xalivecow Date: Mon, 11 Nov 2024 10:31:59 +0100 Subject: [PATCH 05/79] feat: start working on add for polynomial --- src/utils/field.rs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/utils/field.rs b/src/utils/field.rs index f0da8f0..63e2230 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -1,6 +1,6 @@ use std::{ env::args, - ops::{Add, Mul}, + ops::{Add, BitXor, Mul}, }; use anyhow::{anyhow, Ok, Result}; @@ -73,9 +73,13 @@ impl Mul for Polynomial { impl Add for Polynomial { type Output = Self; fn add(self, rhs: Self) -> Self::Output { - FieldElement::new( - xor_bytes(&self.field_element, rhs.field_element).expect("Error in poly add"), - ) + for i in 0..self.polynomial.len() { + for j in 0..rhs.polynomial.len() { + polynomial[i + j] = &polynomial[i + j] + + &(self.polynomial.get(i).unwrap() * rhs.polynomial.get(j).unwrap()); + } + } + Polynomial::new(polynomial) } } @@ -169,6 +173,14 @@ impl Clone for FieldElement { } } +/* +impl BitXor for FieldElement { + fn bitxor(self, rhs: Self) -> Self::Output { + FieldElement + } +} +*/ + /* impl From> for FieldElement { fn from(item: Vec) -> Self { From 11916e29f0bbd361d39d7e4c18a8e68325f7c9f7 Mon Sep 17 00:00:00 2001 From: alivecow Date: Tue, 12 Nov 2024 18:58:20 +0100 Subject: [PATCH 06/79] feat: initial pow support working --- src/tasks/tasks01/gfmul.rs | 20 ------ src/utils/field.rs | 141 +++++++++++++++++++++++++++++++++++-- 2 files changed, 135 insertions(+), 26 deletions(-) diff --git a/src/tasks/tasks01/gfmul.rs b/src/tasks/tasks01/gfmul.rs index 01731f6..c4acefe 100644 --- a/src/tasks/tasks01/gfmul.rs +++ b/src/tasks/tasks01/gfmul.rs @@ -108,24 +108,4 @@ mod tests { ); Ok(()) } - - #[test] - fn gfmul_task01_gcm() -> Result<()> { - let args: Value = json!({"a": "AAAAAAAAAAAAAAAQBAAAAA==", "b": "IAAAAAAAAACAAAAAAAAAAA=="}); - - let poly1_text: String = serde_json::from_value(args["a"].clone())?; - let poly_a = BASE64_STANDARD.decode(poly1_text)?; - - let poly2_text: String = serde_json::from_value(args["b"].clone())?; - let poly_b = BASE64_STANDARD.decode(poly2_text)?; - - let result = BASE64_STANDARD.encode(gfmul(poly_a, poly_b, "gcm")?); - - assert_eq!( - result, "hSQAAAAAAAAAAAAAAAAAAA==", - "Failure. Calulated result was: {}", - result - ); - Ok(()) - } } diff --git a/src/utils/field.rs b/src/utils/field.rs index 63e2230..25088cf 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -52,6 +52,42 @@ impl Polynomial { output } + + pub fn pow(&self, mut exponent: u128) -> Polynomial { + if exponent == 0 { + // Return polynomial with coefficient 1 + return Polynomial::new(vec![FieldElement::new(vec![1])]); + } + + let base = self.clone(); + let mut result = base.clone(); + exponent -= 1; // Subtract 1 because we already set result to base + + while exponent > 0 { + result = result * base.clone(); + exponent -= 1; + } + + result + } + /* + pub fn to_b64(&self) -> String { + let mut output: Vec = vec![]; + for coeff in self.polynomial { + output.push(BASE64_STANDARD.encode(coeff)); + } + + output + } + */ +} + +impl Clone for Polynomial { + fn clone(&self) -> Self { + Polynomial { + polynomial: self.polynomial.clone(), + } + } } impl Mul for Polynomial { @@ -70,9 +106,11 @@ impl Mul for Polynomial { } } -impl Add for Polynomial { - type Output = Self; - fn add(self, rhs: Self) -> Self::Output { +impl Mul for &Polynomial { + type Output = Polynomial; + fn mul(self, rhs: Self) -> Self::Output { + let mut polynomial: Vec = + vec![FieldElement::new(vec![0; 16]); self.polynomial.len() + rhs.polynomial.len() - 1]; for i in 0..self.polynomial.len() { for j in 0..rhs.polynomial.len() { polynomial[i + j] = &polynomial[i + j] @@ -83,6 +121,40 @@ impl Add for Polynomial { } } +impl Add for Polynomial { + type Output = Self; + fn add(self, rhs: Self) -> Self::Output { + let mut polynomial: Vec; + + if self.polynomial.len() > rhs.polynomial.len() { + polynomial = self.polynomial.clone(); + for i in 0..rhs.polynomial.len() { + polynomial[i] = polynomial[i].clone() + rhs.polynomial[i].clone(); + } + } else { + polynomial = rhs.polynomial.clone(); + for i in 0..self.polynomial.len() { + polynomial[i] = polynomial[i].clone() + self.polynomial[i].clone(); + } + } + + Polynomial::new(polynomial) + } +} + +impl AsRef<[FieldElement]> for Polynomial { + fn as_ref(&self) -> &[FieldElement] { + &self.polynomial + } +} + +/* +impl AsRef<[u8]> for Polynomial { + fn as_ref(&self) -> &[u8] { + &self.polynomial + } +} +*/ /* impl Add for Polynomial { type Output = Self; @@ -117,6 +189,10 @@ impl FieldElement { pub fn mul(&self, poly_a: Vec, poly_b: Vec) -> Result> { gfmul(poly_a, poly_b, "gcm") } + + pub fn to_b64(&self) -> String { + BASE64_STANDARD.encode(&self.field_element) + } } impl Mul for FieldElement { @@ -173,6 +249,19 @@ impl Clone for FieldElement { } } +impl BitXor for FieldElement { + type Output = Self; + fn bitxor(self, rhs: Self) -> Self::Output { + let result: Vec = self + .field_element + .iter() + .zip(rhs.field_element.iter()) + .map(|(&x1, &x2)| x1 ^ x2) + .collect(); + FieldElement::new(result) + } +} + /* impl BitXor for FieldElement { fn bitxor(self, rhs: Self) -> Self::Output { @@ -424,7 +513,15 @@ mod tests { let sum = element2 + element1; - assert_eq!(BASE64_STANDARD.encode(sum), "OZuIncPAGEp4tYouDownAA=="); + assert_eq!( + sum.to_c_array(), + vec![ + "H1d3GuyA9/0OxeYouUpAAA==", + "OZuIncPAGEp4tYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ] + ); } #[test] @@ -442,9 +539,41 @@ mod tests { let result = element1 * element2; - eprintln!("Result = {:?}", result.to_c_array()); + assert_eq!( + result.to_c_array(), + vec![ + "MoAAAAAAAAAAAAAAAAAAAA==", + "sUgAAAAAAAAAAAAAAAAAAA==", + "MbQAAAAAAAAAAAAAAAAAAA==", + "AAhAAAAAAAAAAAAAAAAAAA==" + ] + ); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } - assert!(false); + #[test] + fn test_field_pow_01() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.pow(3); + + assert_eq!( + result.to_c_array(), + vec![ + "AkkAAAAAAAAAAAAAAAAAAA==", + "DDAAAAAAAAAAAAAAAAAAAA==", + "LQIIAAAAAAAAAAAAAAAAAA==", + "8AAAAAAAAAAAAAAAAAAAAA==", + "ACgCQAAAAAAAAAAAAAAAAA==", + "AAAMAAAAAAAAAAAAAAAAAA==", + "AAAAAgAAAAAAAAAAAAAAAA==" + ] + ); //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } } From a05f2f02b678c21968ecf94675ac5a73dfe27ef6 Mon Sep 17 00:00:00 2001 From: alivecow Date: Wed, 13 Nov 2024 20:27:20 +0100 Subject: [PATCH 07/79] feat/refactor: Change gfmul to take references and add field div --- src/tasks/tasks01/gfmul.rs | 10 +-- src/utils/ciphers.rs | 8 +-- src/utils/field.rs | 138 +++++++++++++++++++++++++++++-------- src/utils/poly.rs | 6 +- 4 files changed, 120 insertions(+), 42 deletions(-) diff --git a/src/tasks/tasks01/gfmul.rs b/src/tasks/tasks01/gfmul.rs index c4acefe..2c1d6b8 100644 --- a/src/tasks/tasks01/gfmul.rs +++ b/src/tasks/tasks01/gfmul.rs @@ -16,7 +16,7 @@ pub fn gfmul_task(args: &Value) -> Result> { let semantic: String = serde_json::from_value(args["semantic"].clone())?; - let result = gfmul(poly_a, poly_b, &semantic)?; + let result = gfmul(&poly_a, &poly_b, &semantic)?; Ok(result) } @@ -39,7 +39,7 @@ mod tests { let poly2_text: String = serde_json::from_value(args["b"].clone())?; let poly_b = BASE64_STANDARD.decode(poly2_text)?; - let result = BASE64_STANDARD.encode(gfmul(poly_a, poly_b, "xex")?); + let result = BASE64_STANDARD.encode(gfmul(&poly_a, &poly_b, "xex")?); assert_eq!( result, "hSQAAAAAAAAAAAAAAAAAAA==", @@ -59,7 +59,7 @@ mod tests { let poly2_text: String = serde_json::from_value(args["b"].clone())?; let poly_b = BASE64_STANDARD.decode(poly2_text)?; - let result = BASE64_STANDARD.encode(gfmul(poly_a, poly_b, "xex")?); + let result = BASE64_STANDARD.encode(gfmul(&poly_a, &poly_b, "xex")?); assert_eq!( result, "QKgUAAAAAAAAAAAAAAAAAA==", @@ -79,7 +79,7 @@ mod tests { let poly2_text: String = serde_json::from_value(args["b"].clone())?; let poly_b = BASE64_STANDARD.decode(poly2_text)?; - let result = BASE64_STANDARD.encode(gfmul(poly_a, poly_b, "xex")?); + let result = BASE64_STANDARD.encode(gfmul(&poly_a, &poly_b, "xex")?); assert_eq!( result, "UIAUAAAAAAAAAAAAAAAAAA==", @@ -99,7 +99,7 @@ mod tests { let poly2_text: String = serde_json::from_value(args["b"].clone())?; let poly_b = BASE64_STANDARD.decode(poly2_text)?; - let result = BASE64_STANDARD.encode(gfmul(poly_a, poly_b, "xex")?); + let result = BASE64_STANDARD.encode(gfmul(&poly_a, &poly_b, "xex")?); assert_eq!( result, "hSQAAAAAAAAAAAAAAAAAAA==", diff --git a/src/utils/ciphers.rs b/src/utils/ciphers.rs index 917a1c7..333ec13 100644 --- a/src/utils/ciphers.rs +++ b/src/utils/ciphers.rs @@ -340,25 +340,25 @@ pub fn ghash( eprintln!("Ad chunks before first next {:001X?}", ad_chunks); let inter1 = xor_bytes(&output, ad_chunks.next().unwrap().to_vec())?; - let mut inter_loop = gfmul(inter1, auth_key_h.clone(), "gcm")?; + let mut inter_loop = gfmul(&inter1, &auth_key_h, "gcm")?; eprintln!("Ad chunks after first next {:001X?}", ad_chunks); for chunk in ad_chunks { eprintln!("Inside ad chunk loop"); eprintln!("Ad chunk in loop {:001X?}", chunk); let inter2 = xor_bytes(&inter_loop, chunk.to_vec())?; - inter_loop = gfmul(inter2, auth_key_h.clone(), "gcm")?; + inter_loop = gfmul(&inter2, &auth_key_h, "gcm")?; } let cipher_chunks = ciphertext.chunks(16); for chunk in cipher_chunks { let inter3 = xor_bytes(&inter_loop, chunk.to_vec())?; - inter_loop = gfmul(inter3, auth_key_h.clone(), "gcm")?; + inter_loop = gfmul(&inter3, &auth_key_h, "gcm")?; } let inter4 = xor_bytes(&inter_loop, l_field)?; - inter_loop = gfmul(inter4, auth_key_h.clone(), "gcm")?; + inter_loop = gfmul(&inter4, &auth_key_h, "gcm")?; eprintln!("GHASH auth tag: {:001X?}", inter_loop); diff --git a/src/utils/field.rs b/src/utils/field.rs index 25088cf..c8de249 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -1,12 +1,15 @@ use std::{ env::args, - ops::{Add, BitXor, Mul}, + ops::{Add, BitXor, Div, Mul, Rem, Sub}, + result, }; use anyhow::{anyhow, Ok, Result}; use base64::prelude::*; use serde_json::Value; +use crate::{tasks::tasks01::poly2block::poly2block, utils::poly::polynomial_2_block}; + use super::{math::xor_bytes, poly::gfmul}; #[derive(Debug)] @@ -142,36 +145,32 @@ impl Add for Polynomial { } } +// Helper implementation for subtraction +impl Sub for &FieldElement { + type Output = FieldElement; + + fn sub(self, rhs: Self) -> FieldElement { + // In a field of characteristic 2, addition and subtraction are the same operation (XOR) + self + rhs + } +} + +// Helper trait for checking emptiness +trait IsEmpty { + fn is_empty(&self) -> bool; +} + +impl IsEmpty for Polynomial { + fn is_empty(&self) -> bool { + self.polynomial.is_empty() + } +} impl AsRef<[FieldElement]> for Polynomial { fn as_ref(&self) -> &[FieldElement] { &self.polynomial } } -/* -impl AsRef<[u8]> for Polynomial { - fn as_ref(&self) -> &[u8] { - &self.polynomial - } -} -*/ -/* -impl Add for Polynomial { - type Output = Self; - fn add(self, rhs: Self) -> Self::Output { - FieldElement::new( - xor_bytes(&self.field_element, rhs.field_element).expect("Error in poly add"), - ) - } -} - -impl AsRef<[u8]> for Polynomial { - fn as_ref(&self) -> &[u8] { - &self.field_element.as_ref() - } -} -*/ - #[derive(Debug)] pub struct FieldElement { field_element: Vec, @@ -187,12 +186,48 @@ impl FieldElement { } pub fn mul(&self, poly_a: Vec, poly_b: Vec) -> Result> { - gfmul(poly_a, poly_b, "gcm") + gfmul(&poly_a, &poly_b, "gcm") } pub fn to_b64(&self) -> String { BASE64_STANDARD.encode(&self.field_element) } + + pub fn pow(&self, mut exponent: u128) -> FieldElement { + if exponent == 0 { + // Return polynomial with coefficient 1 + return FieldElement::new(vec![1]); + } + + let base = self.clone(); + let mut result = base.clone(); + exponent -= 1; // Subtract 1 because we already set result to base + + while exponent > 0 { + result = result * base.clone(); + exponent -= 1; + } + + result + } + + pub fn inv(mut self) -> Self { + let mut inverser: u128 = 0xfffffffffffffffffffffffffffffffe; + let mut inverse: Vec = polynomial_2_block(vec![0], "gcm").unwrap(); + eprintln!("Inverse start {:02X?}", inverse); + + while inverser > 0 { + //eprintln!("{:02X}", inverser); + if inverser & 1 == 1 { + inverse = gfmul(&self.field_element, &inverse, "gcm").unwrap(); + } + inverser >>= 1; + self.field_element = gfmul(&self.field_element, &self.field_element, "gcm") + .expect("Error in sqrmul sqr"); + } + eprintln!("Inverse rhs {:?}", inverse); + FieldElement::new(inverse) + } } impl Mul for FieldElement { @@ -200,7 +235,7 @@ impl Mul for FieldElement { fn mul(self, rhs: Self) -> Self::Output { FieldElement::new( - gfmul(self.field_element, rhs.field_element, "gcm") + gfmul(&self.field_element, &rhs.field_element, "gcm") .expect("Error during multiplication"), ) } @@ -211,7 +246,7 @@ impl Mul for &FieldElement { fn mul(self, rhs: &FieldElement) -> FieldElement { FieldElement::new( - gfmul(self.field_element.clone(), rhs.field_element.clone(), "gcm") + gfmul(&self.field_element, &rhs.field_element, "gcm") .expect("Error during multiplication"), ) } @@ -262,6 +297,36 @@ impl BitXor for FieldElement { } } +impl Div for FieldElement { + type Output = Self; + fn div(self, rhs: Self) -> Self::Output { + eprintln!("RHS in div{:02X?}", &rhs); + + let inverse = rhs.inv(); + eprintln!("Inverse in div{:02X?}", inverse); + self.clone() * inverse + } +} + +impl Div for &FieldElement { + type Output = FieldElement; + + fn div(self, rhs: Self) -> Self::Output { + // First clone and invert the divisor (rhs) + let rhs_inv = rhs.clone().inv(); + // Multiply original number by the inverse + self.clone() * rhs_inv + } +} +/* +//TODO: Not yet ready + impl Rem for FieldElement { + fn rem(self, rhs: Self) -> Self::Output { + + } +} +*/ + /* impl BitXor for FieldElement { fn bitxor(self, rhs: Self) -> Self::Output { @@ -312,13 +377,13 @@ impl ByteArray { let alpha_poly: Vec = base64::prelude::BASE64_STANDARD .decode("AgAAAAAAAAAAAAAAAAAAAA==") .expect("Decode failed"); - self.0 = gfmul(self.0.clone(), alpha_poly, "xex").unwrap(); + self.0 = gfmul(&self.0, &alpha_poly, "xex").unwrap(); } "gcm" => { let alpha_poly: Vec = base64::prelude::BASE64_STANDARD .decode("AgAAAAAAAAAAAAAAAAAAAA==") .expect("Decode failed"); - self.0 = gfmul(self.0.clone(), alpha_poly, "gcm").unwrap(); + self.0 = gfmul(&self.0, &alpha_poly, "gcm").unwrap(); } _ => {} } @@ -576,4 +641,17 @@ mod tests { ); //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } + + #[test] + fn test_poly_div_01() { + let element1 = + FieldElement::new(BASE64_STANDARD.decode("JAAAAAAAAAAAAAAAAAAAAA==").unwrap()); + + let element2 = + FieldElement::new(BASE64_STANDARD.decode("wAAAAAAAAAAAAAAAAAAAAA==").unwrap()); + + let result = element1 / element2; + + assert_eq!(BASE64_STANDARD.encode(result), "OAAAAAAAAAAAAAAAAAAAAA=="); + } } diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 78889c8..6425577 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -7,14 +7,14 @@ use std::{str::FromStr, u128, u8, usize}; use super::{field, math::reverse_bits_in_bytevec}; pub const RED_POLY: u128 = 0x87000000_00000000_00000000_00000000; -pub fn gfmul(poly_a: Vec, poly_b: Vec, semantic: &str) -> Result> { +pub fn gfmul(poly_a: &Vec, poly_b: &Vec, semantic: &str) -> Result> { let mut red_poly_bytes: ByteArray = ByteArray(RED_POLY.to_be_bytes().to_vec()); red_poly_bytes.0.push(0x01); - let mut poly1: ByteArray = ByteArray(poly_a); + let mut poly1: ByteArray = ByteArray(poly_a.to_owned()); poly1.0.push(0x00); - let mut poly2: ByteArray = ByteArray(poly_b); + let mut poly2: ByteArray = ByteArray(poly_b.to_owned()); poly2.0.push(0x00); if semantic == "gcm" { From deb426112106e13bd5f2d3fc1e684d4438d2490c Mon Sep 17 00:00:00 2001 From: alivecow Date: Thu, 14 Nov 2024 22:30:55 +0100 Subject: [PATCH 08/79] feat: add division and powmod (WIP) and start adapting task runner --- src/tasks/mod.rs | 7 ++ src/tasks/tasks01/mod.rs | 1 + src/tasks/tasks01/pfmath.rs | 15 +++ src/utils/field.rs | 176 ++++++++++++++++++++++++++++++++---- 4 files changed, 183 insertions(+), 16 deletions(-) create mode 100644 src/tasks/tasks01/pfmath.rs diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index 0fa72d6..f7475be 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -11,6 +11,7 @@ use tasks01::{ gcm::{gcm_decrypt, gcm_encrypt}, gfmul::gfmul_task, pad_oracle::padding_oracle, + pfmath::gfpoly_add, poly2block::poly2block, sea128::sea128, xex::{self, fde_xex}, @@ -83,6 +84,12 @@ pub fn task_deploy(testcase: &Testcase) -> Result { Ok(json) } + "gfpoly_add" => { + let result = gfpoly_add(args)?; + let json = json!({"plaintext" : result.to_c_array()}); + + Ok(json) + } _ => Err(anyhow!( "Fatal. No compatible action found. Json data was {:?}. Arguments were; {:?}", testcase, diff --git a/src/tasks/tasks01/mod.rs b/src/tasks/tasks01/mod.rs index 479fe47..8200de5 100644 --- a/src/tasks/tasks01/mod.rs +++ b/src/tasks/tasks01/mod.rs @@ -2,6 +2,7 @@ pub mod block2poly; pub mod gcm; pub mod gfmul; pub mod pad_oracle; +pub mod pfmath; pub mod poly2block; pub mod sea128; pub mod xex; diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs new file mode 100644 index 0000000..b0c978e --- /dev/null +++ b/src/tasks/tasks01/pfmath.rs @@ -0,0 +1,15 @@ +use anyhow::Result; +use base64::{prelude::BASE64_STANDARD, Engine}; +use serde_json::Value; + +use crate::utils::field::Polynomial; + +pub fn gfpoly_add(args: &Value) -> Result { + let poly_a = Polynomial::from_c_array(&args["A"].clone()); + + let poly_b = Polynomial::from_c_array(&args["B"].clone()); + + let result = poly_a + poly_b; + + Ok(result) +} diff --git a/src/utils/field.rs b/src/utils/field.rs index c8de249..59ffc18 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -58,14 +58,12 @@ impl Polynomial { pub fn pow(&self, mut exponent: u128) -> Polynomial { if exponent == 0 { - // Return polynomial with coefficient 1 - return Polynomial::new(vec![FieldElement::new(vec![1])]); + return Polynomial::new(vec![FieldElement::new(vec![0])]); } let base = self.clone(); let mut result = base.clone(); - exponent -= 1; // Subtract 1 because we already set result to base - + exponent -= 1; while exponent > 0 { result = result * base.clone(); exponent -= 1; @@ -73,16 +71,90 @@ impl Polynomial { result } - /* - pub fn to_b64(&self) -> String { - let mut output: Vec = vec![]; - for coeff in self.polynomial { - output.push(BASE64_STANDARD.encode(coeff)); + + pub fn pow_mod(mut self, mut exponent: u128, modulus: Polynomial) -> Polynomial { + let mut result: Polynomial = Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![0], "gcm").unwrap(), + )]); + + eprintln!("Initial result: {:?}", result); + while exponent > 0 { + eprintln!("Current exponent: {:02X}", exponent); + if exponent & 1 == 1 { + let temp = &self * &result; + eprintln!("After multiplication: {:?}", temp); + result = temp.div(&modulus).1; + eprintln!("After mod: {:?}", result); + } + let temp_square = &self * &self; + eprintln!("After squaring: {:?}", temp_square); + self = temp_square.div(&modulus).1; + eprintln!("After mod: {:?}", self); + exponent >>= 1; + } + result + } + + // Returns (quotient, remainder) + pub fn div(self, rhs: &Self) -> (Self, Self) { + // Div by zero check ommitted since data is guaranteed to be non 0 + + let mut remainder = self.clone(); + let divisor = rhs; + let dividend_deg = remainder.polynomial.len() - 1; + let divisor_deg = divisor.polynomial.len() - 1; + + if dividend_deg < divisor_deg { + return ( + Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![0; 16], "gcm").unwrap(), + )]), + remainder, + ); } - output + let mut quotient_coeffs = + vec![ + FieldElement::new(polynomial_2_block(vec![0; 16], "gcm").unwrap()); + dividend_deg - divisor_deg + 1 + ]; + + while remainder.polynomial.len() >= divisor.polynomial.len() { + let deg_diff = remainder.polynomial.len() - divisor.polynomial.len(); + + let leading_dividend = remainder.polynomial.last().unwrap(); + let leading_divisor = divisor.polynomial.last().unwrap(); + let quot_coeff = leading_dividend / leading_divisor; + + quotient_coeffs[deg_diff] = quot_coeff.clone(); + + let mut subtrahend = + vec![FieldElement::new(polynomial_2_block(vec![0; 16], "gcm").unwrap()); deg_diff]; + subtrahend.extend( + divisor + .polynomial + .iter() + .map(|x| x.clone() * quot_coeff.clone()), + ); + let subtrahend_poly = Polynomial::new(subtrahend); + + remainder = remainder + subtrahend_poly; + + while !remainder.polynomial.is_empty() + && remainder + .polynomial + .last() + .unwrap() + .as_ref() + .iter() + .all(|&x| x == 0) + { + remainder.polynomial.pop(); + } + } + + (Polynomial::new(quotient_coeffs), remainder) } - */ } impl Clone for Polynomial { @@ -318,15 +390,20 @@ impl Div for &FieldElement { self.clone() * rhs_inv } } -/* -//TODO: Not yet ready - impl Rem for FieldElement { - fn rem(self, rhs: Self) -> Self::Output { +/* +impl Rem for FieldElement { + type Output = Self; + fn rem(self, rhs: Self) -> Self::Output { + let result: FieldElement = self.field_element; + + while self.field_element[15] != 0x00 { + self.field_element + } + todo!(); } } */ - /* impl BitXor for FieldElement { fn bitxor(self, rhs: Self) -> Self::Output { @@ -642,6 +719,32 @@ mod tests { //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } + #[test] + fn test_field_pow_mod_01() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.pow(3); + + assert_eq!( + result.to_c_array(), + vec![ + "AkkAAAAAAAAAAAAAAAAAAA==", + "DDAAAAAAAAAAAAAAAAAAAA==", + "LQIIAAAAAAAAAAAAAAAAAA==", + "8AAAAAAAAAAAAAAAAAAAAA==", + "ACgCQAAAAAAAAAAAAAAAAA==", + "AAAMAAAAAAAAAAAAAAAAAA==", + "AAAAAgAAAAAAAAAAAAAAAA==" + ] + ); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + #[test] fn test_poly_div_01() { let element1 = @@ -654,4 +757,45 @@ mod tests { assert_eq!(BASE64_STANDARD.encode(result), "OAAAAAAAAAAAAAAAAAAAAA=="); } + + #[test] + fn test_field_poly_div_01() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let json2 = json!(["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + //eprintln!("{:?}", element1); + + println!("Beginning the new division"); + let (result, remainder) = element1.div(&element2); + + assert_eq!( + result.to_c_array(), + vec!["nAIAgCAIAgCAIAgCAIAgCg==", "m85znOc5znOc5znOc5znOQ=="] + ); + assert_eq!(remainder.to_c_array(), vec!["lQNA0DQNA0DQNA0DQNA0Dg=="]); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_field_poly_powmod_01() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let modulus: Polynomial = Polynomial::from_c_array(&json2); + + let result = element1.pow_mod(1000, modulus); + + eprintln!("Result is: {:02X?}", result); + assert_eq!(result.to_c_array(), vec!["XrEhmKuat+Glt5zZWtMo6g=="]); + } } From 68d9f13a3dd05dbf96c898a19f4a165ffdae1073 Mon Sep 17 00:00:00 2001 From: alivecow Date: Thu, 14 Nov 2024 23:08:20 +0100 Subject: [PATCH 09/79] feat: finialise test runner and add testing json --- src/tasks/mod.rs | 54 +++++++++++++++++++- src/tasks/tasks01/pfmath.rs | 56 ++++++++++++++++++++- src/utils/field.rs | 16 +++--- test_json/pfmath_tests.json | 98 +++++++++++++++++++++++++++++++++++++ 4 files changed, 213 insertions(+), 11 deletions(-) create mode 100644 test_json/pfmath_tests.json diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index f7475be..b024471 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -11,7 +11,7 @@ use tasks01::{ gcm::{gcm_decrypt, gcm_encrypt}, gfmul::gfmul_task, pad_oracle::padding_oracle, - pfmath::gfpoly_add, + pfmath::{gfdiv, gfpoly_add, gfpoly_divmod, gfpoly_mul, gfpoly_pow, gfpoly_powmod}, poly2block::poly2block, sea128::sea128, xex::{self, fde_xex}, @@ -86,10 +86,42 @@ pub fn task_deploy(testcase: &Testcase) -> Result { } "gfpoly_add" => { let result = gfpoly_add(args)?; - let json = json!({"plaintext" : result.to_c_array()}); + let json = json!({"S" : result.to_c_array()}); Ok(json) } + "gfpoly_mul" => { + let result = gfpoly_mul(args)?; + let json = json!({"P" : result.to_c_array()}); + + Ok(json) + } + "gfpoly_pow" => { + let result = gfpoly_pow(args)?; + let json = json!({"Z" : result.to_c_array()}); + + Ok(json) + } + "gfdiv" => { + let result = gfdiv(args)?; + let out = BASE64_STANDARD.encode(result); + let json = json!({"q" : out}); + + Ok(json) + } + "gfpoly_divmod" => { + let result = gfpoly_divmod(args)?; + let json = json!({"Q" : result.0.to_c_array(), "R" : result.1.to_c_array()}); + + Ok(json) + } + "gfpoly_powmod" => { + let result = gfpoly_powmod(args)?; + let json = json!({"Z" : result.to_c_array()}); + + Ok(json) + } + _ => Err(anyhow!( "Fatal. No compatible action found. Json data was {:?}. Arguments were; {:?}", testcase, @@ -279,4 +311,22 @@ mod tests { Ok(()) } + + #[test] + fn test_task_gcm_gfpoly_add() -> Result<()> { + let json = fs::read_to_string("test_json/gcm_decrypt_sea.json").unwrap(); + let parsed = parse_json(json).unwrap(); + + let expected = json!({ "responses" : { "b856d760-023d-4b00-bad2-15d2b6da22fe" : { + "plaintext": "RGFzIGlzdCBlaW4gVGVzdA==", + "authentic": true, + }}}); + + assert_eq!( + serde_json::to_value(task_distrubute(&parsed)?).unwrap(), + serde_json::to_value(expected).unwrap() + ); + + Ok(()) + } } diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index b0c978e..4ad3ac7 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -2,7 +2,7 @@ use anyhow::Result; use base64::{prelude::BASE64_STANDARD, Engine}; use serde_json::Value; -use crate::utils::field::Polynomial; +use crate::utils::field::{FieldElement, Polynomial}; pub fn gfpoly_add(args: &Value) -> Result { let poly_a = Polynomial::from_c_array(&args["A"].clone()); @@ -13,3 +13,57 @@ pub fn gfpoly_add(args: &Value) -> Result { Ok(result) } + +pub fn gfpoly_mul(args: &Value) -> Result { + let poly_a = Polynomial::from_c_array(&args["A"].clone()); + + let poly_b = Polynomial::from_c_array(&args["B"].clone()); + + let result = poly_a * poly_b; + + Ok(result) +} + +pub fn gfpoly_pow(args: &Value) -> Result { + let poly_a = Polynomial::from_c_array(&args["A"].clone()); + + let k: u128 = serde_json::from_value(args["k"].clone())?; + + let result = poly_a.pow(k); + + Ok(result) +} + +pub fn gfdiv(args: &Value) -> Result { + let f1_text: String = serde_json::from_value(args["a"].clone())?; + let f_a = FieldElement::new(BASE64_STANDARD.decode(f1_text)?); + + let f2_text: String = serde_json::from_value(args["b"].clone())?; + let f_b = FieldElement::new(BASE64_STANDARD.decode(f2_text)?); + + let result = f_a / f_b; + + Ok(result) +} + +pub fn gfpoly_divmod(args: &Value) -> Result<(Polynomial, Polynomial)> { + let poly_a = Polynomial::from_c_array(&args["A"].clone()); + + let poly_b = Polynomial::from_c_array(&args["B"].clone()); + + let result = poly_a.div(&poly_b); + + Ok(result) +} + +pub fn gfpoly_powmod(args: &Value) -> Result { + let poly_a = Polynomial::from_c_array(&args["A"].clone()); + + let poly_m = Polynomial::from_c_array(&args["M"].clone()); + + let k: u128 = serde_json::from_value(args["k"].clone())?; + + let result = poly_a.pow_mod(k, poly_m); + + Ok(result) +} diff --git a/src/utils/field.rs b/src/utils/field.rs index 59ffc18..fac51f2 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -77,19 +77,19 @@ impl Polynomial { polynomial_2_block(vec![0], "gcm").unwrap(), )]); - eprintln!("Initial result: {:?}", result); + //eprintln!("Initial result: {:?}", result); while exponent > 0 { - eprintln!("Current exponent: {:02X}", exponent); + //eprintln!("Current exponent: {:02X}", exponent); if exponent & 1 == 1 { let temp = &self * &result; - eprintln!("After multiplication: {:?}", temp); + //eprintln!("After multiplication: {:?}", temp); result = temp.div(&modulus).1; - eprintln!("After mod: {:?}", result); + //eprintln!("After mod: {:?}", result); } let temp_square = &self * &self; - eprintln!("After squaring: {:?}", temp_square); + //eprintln!("After squaring: {:?}", temp_square); self = temp_square.div(&modulus).1; - eprintln!("After mod: {:?}", self); + //eprintln!("After mod: {:?}", self); exponent >>= 1; } result @@ -286,7 +286,7 @@ impl FieldElement { pub fn inv(mut self) -> Self { let mut inverser: u128 = 0xfffffffffffffffffffffffffffffffe; let mut inverse: Vec = polynomial_2_block(vec![0], "gcm").unwrap(); - eprintln!("Inverse start {:02X?}", inverse); + //eprintln!("Inverse start {:02X?}", inverse); while inverser > 0 { //eprintln!("{:02X}", inverser); @@ -297,7 +297,7 @@ impl FieldElement { self.field_element = gfmul(&self.field_element, &self.field_element, "gcm") .expect("Error in sqrmul sqr"); } - eprintln!("Inverse rhs {:?}", inverse); + //eprintln!("Inverse rhs {:?}", inverse); FieldElement::new(inverse) } } diff --git a/test_json/pfmath_tests.json b/test_json/pfmath_tests.json new file mode 100644 index 0000000..b9cc6e0 --- /dev/null +++ b/test_json/pfmath_tests.json @@ -0,0 +1,98 @@ +{ + "testcases": { + "gfpoly_add": { + "action": "gfpoly_add", + "arguments": { + "A": [ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ], + "B": [ + "KryptoanalyseAAAAAAAAA==", + "DHBWMannheimAAAAAAAAAA==" + ] + } + }, + "gfpoly_mul": { + "action": "gfpoly_mul", + "arguments": { + "A": [ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ], + "B": [ + "0AAAAAAAAAAAAAAAAAAAAA==", + "IQAAAAAAAAAAAAAAAAAAAA==" + ] + } + }, + "gfpoly_mul_10": { + "action": "gfpoly_mul", + "arguments": { + "A": [ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ], + "B": [ + "AAAAAAAAAAAAAAAAAAAAAA==" + ] + } + }, + "gfpoly_mul_01": { + "action": "gfpoly_mul", + "arguments": { + "A": [ + "AAAAAAAAAAAAAAAAAAAAAA==" + ], + "B": [ + "0AAAAAAAAAAAAAAAAAAAAA==", + "IQAAAAAAAAAAAAAAAAAAAA==" + ] + } + }, + "gfpoly_pow": { + "action": "gfpoly_pow", + "arguments": { + "A": [ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ], + "k": 3 + } + }, + "gfpoly_pow_k0": { + "action": "gfpoly_pow", + "arguments": { + "A": [ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ], + "k": 0 + } + }, + "gfpoly_pow_k1": { + "action": "gfpoly_pow", + "arguments": { + "A": [ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ], + "k": 1 + } + }, + "gfdiv": { + "action": "gfdiv", + "arguments": { + "a": "JAAAAAAAAAAAAAAAAAAAAA==", + "b": "wAAAAAAAAAAAAAAAAAAAAA==" + } + } + } +} From 9785b8d8aa5af3f12091eec2a2f54cc750ce23f9 Mon Sep 17 00:00:00 2001 From: alivecow Date: Thu, 14 Nov 2024 23:42:38 +0100 Subject: [PATCH 10/79] refactor: apply rust suggested code cleanups --- src/main.rs | 2 +- src/tasks/mod.rs | 9 +++------ src/tasks/tasks01/block2poly.rs | 2 +- src/tasks/tasks01/gfmul.rs | 5 +---- src/tasks/tasks01/pad_oracle.rs | 10 ++++------ src/tasks/tasks01/poly2block.rs | 3 +-- src/tasks/tasks01/sea128.rs | 2 -- src/utils/ciphers.rs | 5 +---- src/utils/field.rs | 8 ++------ src/utils/math.rs | 4 +--- src/utils/parse.rs | 2 -- src/utils/poly.rs | 4 +--- 12 files changed, 16 insertions(+), 40 deletions(-) diff --git a/src/main.rs b/src/main.rs index 5816ecb..201533c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,5 @@ use std::{ - env::{self, args}, + env::{self}, fs, }; diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index b024471..bdb2fb0 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -1,11 +1,8 @@ use base64::prelude::*; -use std::{collections::HashMap, env::args}; +use std::collections::HashMap; -use crate::utils::{ - ciphers::gcm_encrypt_aes, - parse::{Responses, Testcase, Testcases}, -}; +use crate::utils::parse::{Responses, Testcase, Testcases}; use tasks01::{ block2poly::block2poly, gcm::{gcm_decrypt, gcm_encrypt}, @@ -14,7 +11,7 @@ use tasks01::{ pfmath::{gfdiv, gfpoly_add, gfpoly_divmod, gfpoly_mul, gfpoly_pow, gfpoly_powmod}, poly2block::poly2block, sea128::sea128, - xex::{self, fde_xex}, + xex::{fde_xex}, }; use anyhow::{anyhow, Result}; diff --git a/src/tasks/tasks01/block2poly.rs b/src/tasks/tasks01/block2poly.rs index dbdaf66..3e636eb 100644 --- a/src/tasks/tasks01/block2poly.rs +++ b/src/tasks/tasks01/block2poly.rs @@ -1,4 +1,4 @@ -use crate::utils::poly::{b64_2_num, block_2_polynomial, get_coefficients}; +use crate::utils::poly::block_2_polynomial; use anyhow::Result; use base64::prelude::*; use serde_json::Value; diff --git a/src/tasks/tasks01/gfmul.rs b/src/tasks/tasks01/gfmul.rs index 2c1d6b8..70ab788 100644 --- a/src/tasks/tasks01/gfmul.rs +++ b/src/tasks/tasks01/gfmul.rs @@ -1,7 +1,4 @@ -use crate::utils::{ - field::ByteArray, - poly::{b64_2_num, coefficient_to_binary, gfmul}, -}; +use crate::utils::poly::gfmul; use anyhow::Result; use base64::prelude::*; diff --git a/src/tasks/tasks01/pad_oracle.rs b/src/tasks/tasks01/pad_oracle.rs index 64eb2d1..90e4295 100644 --- a/src/tasks/tasks01/pad_oracle.rs +++ b/src/tasks/tasks01/pad_oracle.rs @@ -3,8 +3,8 @@ use base64::prelude::*; use serde_json::Value; use std::io::prelude::*; use std::net::TcpStream; -use std::time::{Duration, Instant}; -use std::{thread, usize}; +use std::time::Instant; +use std::usize; pub fn padding_oracle(args: &Value) -> Result> { let hostname: String = serde_json::from_value(args["hostname"].clone())?; @@ -29,8 +29,6 @@ pub fn padding_oracle(args: &Value) -> Result> { let mut chunk_counter = 0; for chunk in &cipher_chunks { - let start = Instant::now(); - let mut stream = TcpStream::connect(format!("{}:{}", hostname, port))?; stream.set_nonblocking(false)?; @@ -111,12 +109,12 @@ pub fn padding_oracle(args: &Value) -> Result> { } else { //eprintln!("Invalid padding"); // Search for second hit - let valid_val = (255 + let valid_val = 255 - server_q_resp .iter() .rev() .position(|&r| r == 0x01) - .unwrap_or(0x00) as u8); + .unwrap_or(0x00) as u8; if valid_val == 0x00 { eprintln!("No valid found"); } diff --git a/src/tasks/tasks01/poly2block.rs b/src/tasks/tasks01/poly2block.rs index 293d1c3..6d5ad95 100644 --- a/src/tasks/tasks01/poly2block.rs +++ b/src/tasks/tasks01/poly2block.rs @@ -1,6 +1,5 @@ -use crate::utils::poly::{self, polynomial_2_block}; +use crate::utils::poly::{polynomial_2_block}; use anyhow::{Ok, Result}; -use base64::prelude::*; use serde_json::Value; pub fn poly2block(args: &Value) -> Result> { diff --git a/src/tasks/tasks01/sea128.rs b/src/tasks/tasks01/sea128.rs index 3f5c40d..6d76909 100644 --- a/src/tasks/tasks01/sea128.rs +++ b/src/tasks/tasks01/sea128.rs @@ -12,7 +12,6 @@ pub fn sea128(args: &Value) -> Result { let input_string: String = serde_json::from_value(args["input"].clone())?; //let plaintexts: &[u8] = &b64_2_num(plaintexts_string)?.to_ne_bytes(); let input = BASE64_STANDARD.decode(input_string)?; - let xor_val: u128 = 0xc0ffeec0ffeec0ffeec0ffeec0ffee11; let mode: String = serde_json::from_value(args["mode"].clone())?; match mode.as_str() { @@ -34,7 +33,6 @@ pub fn sea128(args: &Value) -> Result { #[cfg(test)] mod tests { - use std::fs; use anyhow::Result; use serde_json::json; diff --git a/src/utils/ciphers.rs b/src/utils/ciphers.rs index 333ec13..35181a5 100644 --- a/src/utils/ciphers.rs +++ b/src/utils/ciphers.rs @@ -1,6 +1,4 @@ -use std::{io::BufRead, process::Output}; - -use crate::utils::{field::ByteArray, math::reverse_bits_in_bytevec, poly::gfmul}; +use crate::utils::{field::ByteArray, poly::gfmul}; use anyhow::Result; use base64::prelude::*; use openssl::symm::{Cipher, Crypter, Mode}; @@ -40,7 +38,6 @@ pub fn aes_128_decrypt(key: &Vec, input: &Vec) -> Result> { let mut bytes: [u8; 16] = [0u8; 16]; bytes.copy_from_slice(&plaintext); - let number: u128 = ::from_be_bytes(bytes); Ok(plaintext) } diff --git a/src/utils/field.rs b/src/utils/field.rs index fac51f2..14d0c46 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -1,14 +1,10 @@ -use std::{ - env::args, - ops::{Add, BitXor, Div, Mul, Rem, Sub}, - result, -}; +use std::ops::{Add, BitXor, Div, Mul, Sub}; use anyhow::{anyhow, Ok, Result}; use base64::prelude::*; use serde_json::Value; -use crate::{tasks::tasks01::poly2block::poly2block, utils::poly::polynomial_2_block}; +use crate::utils::poly::polynomial_2_block; use super::{math::xor_bytes, poly::gfmul}; diff --git a/src/utils/math.rs b/src/utils/math.rs index cf87e0c..c1809e2 100644 --- a/src/utils/math.rs +++ b/src/utils/math.rs @@ -1,7 +1,5 @@ -use anyhow::{anyhow, Ok, Result}; -use base64::Engine; +use anyhow::{Ok, Result}; -use super::poly::gfmul; pub fn xor_bytes(vec1: &Vec, mut vec2: Vec) -> Result> { for (byte1, byte2) in vec1.iter().zip(vec2.iter_mut()) { diff --git a/src/utils/parse.rs b/src/utils/parse.rs index 5cc1781..6e5d2dd 100644 --- a/src/utils/parse.rs +++ b/src/utils/parse.rs @@ -28,8 +28,6 @@ pub fn parse_json(json: String) -> Result { mod tests { use std::fs; - use serde_json::json; - // Note this useful idiom: importing names from outer (for mod tests) scope. use super::*; diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 6425577..3866e49 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -1,10 +1,8 @@ use crate::utils::field::ByteArray; use anyhow::{anyhow, Result}; use base64::prelude::*; -use serde_json::Value; use std::{str::FromStr, u128, u8, usize}; -use super::{field, math::reverse_bits_in_bytevec}; pub const RED_POLY: u128 = 0x87000000_00000000_00000000_00000000; pub fn gfmul(poly_a: &Vec, poly_b: &Vec, semantic: &str) -> Result> { @@ -172,7 +170,7 @@ pub fn coefficients_to_byte_arr_xex(coeffs: Vec) -> Vec { let mut byte_array: Vec = vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; for coeff in coeffs { let block_num = coeff / 8; - byte_array[usize::from(block_num)] |= (1 << (coeff % 7)); + byte_array[usize::from(block_num)] |= 1 << (coeff % 7); } byte_array From 5dc299372a742b2ba76302574c36ca2f6d5f9ad4 Mon Sep 17 00:00:00 2001 From: alivecow Date: Fri, 15 Nov 2024 10:13:05 +0100 Subject: [PATCH 11/79] fix: Add handling of zero mulitplication for polynomials --- src/utils/field.rs | 105 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 102 insertions(+), 3 deletions(-) diff --git a/src/utils/field.rs b/src/utils/field.rs index 14d0c46..758ea75 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -151,6 +151,15 @@ impl Polynomial { (Polynomial::new(quotient_coeffs), remainder) } + + fn is_zero(&self) -> bool { + for field_element in &self.polynomial { + if !field_element.is_zero() { + return false; + } + } + true + } } impl Clone for Polynomial { @@ -163,8 +172,10 @@ impl Clone for Polynomial { impl Mul for Polynomial { type Output = Self; - fn mul(self, rhs: Self) -> Self::Output { + if self.is_zero() || rhs.is_zero() { + return Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + } let mut polynomial: Vec = vec![FieldElement::new(vec![0; 16]); self.polynomial.len() + rhs.polynomial.len() - 1]; for i in 0..self.polynomial.len() { @@ -180,6 +191,9 @@ impl Mul for Polynomial { impl Mul for &Polynomial { type Output = Polynomial; fn mul(self, rhs: Self) -> Self::Output { + if self.is_zero() || rhs.is_zero() { + return Polynomial::new(vec![FieldElement::new(vec![0])]); + } let mut polynomial: Vec = vec![FieldElement::new(vec![0; 16]); self.polynomial.len() + rhs.polynomial.len() - 1]; for i in 0..self.polynomial.len() { @@ -296,6 +310,10 @@ impl FieldElement { //eprintln!("Inverse rhs {:?}", inverse); FieldElement::new(inverse) } + + fn is_zero(&self) -> bool { + self.field_element.iter().all(|&x| x == 0x00) + } } impl Mul for FieldElement { @@ -662,6 +680,68 @@ mod tests { ); } + #[test] + fn test_field_add_zero() { + let json1 = json!([ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ]); + let json2 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let sum = element2 + element1; + + assert_eq!( + sum.to_c_array(), + vec![ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ] + ); + } + + #[test] + fn test_field_add_zero_to_zero() { + let json1 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let json2 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let sum = element2 + element1; + + assert_eq!(sum.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA=="]); + } + + #[test] + fn test_field_add_short_to_long() { + let json1 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let json2 = json!([ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let sum = element2 + element1; + + assert_eq!( + sum.to_c_array(), + vec![ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ] + ); + } + #[test] fn test_field_mul_01() { let json1 = json!([ @@ -690,7 +770,26 @@ mod tests { } #[test] - fn test_field_pow_01() { + fn test_poly_mul_with_zero() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let json2 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + //eprintln!("{:?}", element1); + + let result = element1 * element2; + + assert_eq!(result.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA=="]); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_poly_pow_01() { let json1 = json!([ "JAAAAAAAAAAAAAAAAAAAAA==", "wAAAAAAAAAAAAAAAAAAAAA==", @@ -792,6 +891,6 @@ mod tests { let result = element1.pow_mod(1000, modulus); eprintln!("Result is: {:02X?}", result); - assert_eq!(result.to_c_array(), vec!["XrEhmKuat+Glt5zZWtMo6g=="]); + assert_eq!(result.to_c_array(), vec!["oNXl5P8xq2WpUTP92u25zg=="]); } } From 2a9db307d9f79c480bef7885bacf38f18659bd54 Mon Sep 17 00:00:00 2001 From: alivecow Date: Fri, 15 Nov 2024 10:26:38 +0100 Subject: [PATCH 12/79] fix: Add handling of pow with 0 --- src/utils/field.rs | 67 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 59 insertions(+), 8 deletions(-) diff --git a/src/utils/field.rs b/src/utils/field.rs index 758ea75..5f47fce 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -54,7 +54,9 @@ impl Polynomial { pub fn pow(&self, mut exponent: u128) -> Polynomial { if exponent == 0 { - return Polynomial::new(vec![FieldElement::new(vec![0])]); + return Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![0], "gcm").unwrap(), + )]); } let base = self.clone(); @@ -69,6 +71,12 @@ impl Polynomial { } pub fn pow_mod(mut self, mut exponent: u128, modulus: Polynomial) -> Polynomial { + if exponent == 0 { + return Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![0], "gcm").unwrap(), + )]); + } + let mut result: Polynomial = Polynomial::new(vec![FieldElement::new( polynomial_2_block(vec![0], "gcm").unwrap(), )]); @@ -536,15 +544,13 @@ impl ByteArray { #[cfg(test)] mod tests { use super::*; - use base64::prelude::*; use serde_json::json; - use std::fs; #[test] fn test_byte_array_shift1() { let mut byte_array: ByteArray = ByteArray(vec![0x00, 0x01]); let shifted_array: ByteArray = ByteArray(vec![0x00, 0x02]); - byte_array.left_shift("xex"); + byte_array.left_shift("xex").unwrap(); assert_eq!(byte_array.0, shifted_array.0); } @@ -553,7 +559,7 @@ mod tests { fn test_byte_array_shift2() { let mut byte_array: ByteArray = ByteArray(vec![0xFF, 0x00]); let shifted_array: ByteArray = ByteArray(vec![0xFE, 0x01]); - byte_array.left_shift("xex"); + byte_array.left_shift("xex").unwrap(); assert_eq!( byte_array.0, shifted_array.0, @@ -566,7 +572,7 @@ mod tests { fn test_byte_array_shift1_gcm() { let mut byte_array: ByteArray = ByteArray(vec![0xFF, 0x00]); let shifted_array: ByteArray = ByteArray(vec![0x7F, 0x80]); - byte_array.left_shift("gcm"); + byte_array.left_shift("gcm").unwrap(); assert_eq!( byte_array.0, shifted_array.0, @@ -579,7 +585,7 @@ mod tests { fn test_byte_array_shift1_right_gcm() { let mut byte_array: ByteArray = ByteArray(vec![0xFF, 0x00]); let shifted_array: ByteArray = ByteArray(vec![0xFE, 0x00]); - byte_array.right_shift("gcm"); + byte_array.right_shift("gcm").unwrap(); assert_eq!( byte_array.0, shifted_array.0, @@ -592,7 +598,7 @@ mod tests { fn test_byte_array_shift_right() { let mut byte_array: ByteArray = ByteArray(vec![0x02]); let shifted_array: ByteArray = ByteArray(vec![0x01]); - byte_array.right_shift("xex"); + byte_array.right_shift("xex").unwrap(); assert_eq!( byte_array.0, shifted_array.0, @@ -814,6 +820,21 @@ mod tests { //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } + #[test] + fn test_poly_pow_with_zero() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.pow(0); + + assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + #[test] fn test_field_pow_mod_01() { let json1 = json!([ @@ -840,6 +861,36 @@ mod tests { //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } + #[test] + fn test_field_pow_mod_with_zero() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.pow(0); + + assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_field_pow_mod_10mill() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.pow(10000000); + + assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + #[test] fn test_poly_div_01() { let element1 = From 0784c264562ec791b2acc8201205695d92303689 Mon Sep 17 00:00:00 2001 From: alivecow Date: Fri, 15 Nov 2024 11:29:25 +0100 Subject: [PATCH 13/79] fix: Add handling for larger divisor --- src/utils/field.rs | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/src/utils/field.rs b/src/utils/field.rs index 5f47fce..3bd1c89 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -103,6 +103,12 @@ impl Polynomial { pub fn div(self, rhs: &Self) -> (Self, Self) { // Div by zero check ommitted since data is guaranteed to be non 0 + eprintln!("{:?}, {:?}", self.polynomial.len(), rhs.polynomial.len()); + + if self.polynomial.len() < rhs.polynomial.len() { + return (Polynomial::new(vec![FieldElement::new(vec![0; 16])]), self); + } + let mut remainder = self.clone(); let divisor = rhs; let dividend_deg = remainder.polynomial.len() - 1; @@ -883,11 +889,13 @@ mod tests { "wAAAAAAAAAAAAAAAAAAAAA==", "ACAAAAAAAAAAAAAAAAAAAA==" ]); + let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); let element1: Polynomial = Polynomial::from_c_array(&json1); + let modulus: Polynomial = Polynomial::from_c_array(&json2); - let result = element1.pow(10000000); + let result = element1.pow_mod(10000000, modulus); - assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); + assert!(!result.is_zero()) //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } @@ -928,6 +936,29 @@ mod tests { //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } + #[test] + fn test_field_poly_div_larger_div() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let json2 = json!(["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + //eprintln!("{:?}", element1); + + println!("Beginning the new division"); + let (result, remainder) = element2.div(&element1); + + assert_eq!(result.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA=="]); + assert_eq!( + remainder.to_c_array(), + vec!["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="] + ); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } #[test] fn test_field_poly_powmod_01() { let json1 = json!([ From 6a04e00fb2fd58a811fd1e3aeaf8a4342681591a Mon Sep 17 00:00:00 2001 From: alivecow Date: Fri, 15 Nov 2024 15:27:13 +0100 Subject: [PATCH 14/79] fix: Fix remainder output of div function --- src/utils/field.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/utils/field.rs b/src/utils/field.rs index 3bd1c89..164a04c 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -71,12 +71,6 @@ impl Polynomial { } pub fn pow_mod(mut self, mut exponent: u128, modulus: Polynomial) -> Polynomial { - if exponent == 0 { - return Polynomial::new(vec![FieldElement::new( - polynomial_2_block(vec![0], "gcm").unwrap(), - )]); - } - let mut result: Polynomial = Polynomial::new(vec![FieldElement::new( polynomial_2_block(vec![0], "gcm").unwrap(), )]); @@ -163,6 +157,9 @@ impl Polynomial { } } + if remainder.is_empty() { + remainder = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + } (Polynomial::new(quotient_coeffs), remainder) } From 67bbf67f18bfbf0d4e777ef9fa39a36dd1c37f9d Mon Sep 17 00:00:00 2001 From: alivecow Date: Fri, 15 Nov 2024 20:02:16 +0100 Subject: [PATCH 15/79] fix: Handle response on adding arbit. len equal polynomials --- src/utils/field.rs | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/utils/field.rs b/src/utils/field.rs index 164a04c..859978b 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -234,6 +234,12 @@ impl Add for Polynomial { } } + for i in (0..polynomial.len() - 1).rev() { + if polynomial[i].is_zero() { + polynomial.pop(); + } + } + Polynomial::new(polynomial) } } @@ -689,6 +695,35 @@ mod tests { ); } + #[test] + fn test_field_add_multiple_zeros() { + let json1 = json!([ + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==" + ]); + let json2 = json!(["AAAAAAAAAAAAAAAAAAAAAA==", "AAAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let sum = element2 + element1; + + assert_eq!(sum.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA==",]); + } + + #[test] + fn test_field_add_same_element() { + let json1 = json!(["NeverGonnaGiveYouUpAAA=="]); + let json2 = json!(["NeverGonnaGiveYouUpAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let sum = element2 + element1; + + assert_eq!(sum.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA==",]); + } + #[test] fn test_field_add_zero() { let json1 = json!([ @@ -956,6 +991,7 @@ mod tests { ); //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } + #[test] fn test_field_poly_powmod_01() { let json1 = json!([ From 7dc6fa1ac982e1b4960c54d012005c7ebcf124a5 Mon Sep 17 00:00:00 2001 From: alivecow Date: Fri, 15 Nov 2024 20:14:54 +0100 Subject: [PATCH 16/79] fix: Fix handling of special cases in powmod --- src/utils/field.rs | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/utils/field.rs b/src/utils/field.rs index 859978b..37502f6 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -75,6 +75,18 @@ impl Polynomial { polynomial_2_block(vec![0], "gcm").unwrap(), )]); + if exponent == 1 { + return self; + } + + if exponent == 0 { + Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![1], "gcm").unwrap(), + )]) + .div(&modulus) + .1; + } + //eprintln!("Initial result: {:?}", result); while exponent > 0 { //eprintln!("Current exponent: {:02X}", exponent); @@ -1008,4 +1020,30 @@ mod tests { eprintln!("Result is: {:02X?}", result); assert_eq!(result.to_c_array(), vec!["oNXl5P8xq2WpUTP92u25zg=="]); } + + #[test] + fn test_field_poly_powmod_k1() { + let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==",]); + let json2 = json!(["KryptoanalyseAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let modulus: Polynomial = Polynomial::from_c_array(&json2); + + let result = element1.pow_mod(1, modulus); + + eprintln!("Result is: {:02X?}", result); + assert_eq!(result.to_c_array(), vec!["JAAAAAAAAAAAAAAAAAAAAA=="]); + } + + #[test] + fn test_field_poly_powmod_k0() { + let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==",]); + let json2 = json!(["KryptoanalyseAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let modulus: Polynomial = Polynomial::from_c_array(&json2); + + let result = element1.pow_mod(0, modulus); + + eprintln!("Result is: {:02X?}", result); + assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); + } } From 295ed98c1e3805756370df8b6bc919b80d82bfd6 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 16 Nov 2024 14:59:31 +0100 Subject: [PATCH 17/79] fix: Add further handling to leading zero blocks in add and powmod --- src/utils/field.rs | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/src/utils/field.rs b/src/utils/field.rs index 37502f6..02eac1e 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -81,7 +81,7 @@ impl Polynomial { if exponent == 0 { Polynomial::new(vec![FieldElement::new( - polynomial_2_block(vec![1], "gcm").unwrap(), + polynomial_2_block(vec![0], "gcm").unwrap(), )]) .div(&modulus) .1; @@ -102,6 +102,23 @@ impl Polynomial { //eprintln!("After mod: {:?}", self); exponent >>= 1; } + + while !result.polynomial.is_empty() + && result + .polynomial + .last() + .unwrap() + .as_ref() + .iter() + .all(|&x| x == 0) + { + result.polynomial.pop(); + } + + if result.is_empty() { + result = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + } + result } @@ -246,10 +263,13 @@ impl Add for Polynomial { } } - for i in (0..polynomial.len() - 1).rev() { - if polynomial[i].is_zero() { - polynomial.pop(); - } + while !polynomial.is_empty() && polynomial.last().unwrap().as_ref().iter().all(|&x| x == 0) + { + polynomial.pop(); + } + + if polynomial.is_empty() { + return Polynomial::new(vec![FieldElement::new(vec![0; 16])]); } Polynomial::new(polynomial) From ca2067c04e7ea8a04c6bd77975ff0c79e89db8bc Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 16 Nov 2024 20:31:16 +0100 Subject: [PATCH 18/79] fix: Add better handling of special cases to powmod --- src/utils/field.rs | 132 +++++++++++++++++++++++++++++++++++++-------- 1 file changed, 110 insertions(+), 22 deletions(-) diff --git a/src/utils/field.rs b/src/utils/field.rs index 02eac1e..e4fff9c 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -76,15 +76,19 @@ impl Polynomial { )]); if exponent == 1 { - return self; + eprintln!("special case 1: {:02X?}", self.clone().div(&modulus).1); + + return self.div(&modulus).1; } if exponent == 0 { - Polynomial::new(vec![FieldElement::new( + let inter = Polynomial::new(vec![FieldElement::new( polynomial_2_block(vec![0], "gcm").unwrap(), - )]) - .div(&modulus) - .1; + )]); + let result = inter.div(&modulus); + + eprintln!("Returned value is: {:02X?}", result); + return result.1; } //eprintln!("Initial result: {:?}", result); @@ -103,6 +107,8 @@ impl Polynomial { exponent >>= 1; } + eprintln!("result in powmod before reduction: {:02X?}", result); + while !result.polynomial.is_empty() && result .polynomial @@ -115,6 +121,8 @@ impl Polynomial { result.polynomial.pop(); } + eprintln!("result in powmod after reduction: {:02X?}", result); + if result.is_empty() { result = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); } @@ -946,23 +954,6 @@ mod tests { //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } - #[test] - fn test_field_pow_mod_10mill() { - let json1 = json!([ - "JAAAAAAAAAAAAAAAAAAAAA==", - "wAAAAAAAAAAAAAAAAAAAAA==", - "ACAAAAAAAAAAAAAAAAAAAA==" - ]); - let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let modulus: Polynomial = Polynomial::from_c_array(&json2); - - let result = element1.pow_mod(10000000, modulus); - - assert!(!result.is_zero()) - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); - } - #[test] fn test_poly_div_01() { let element1 = @@ -1024,6 +1015,38 @@ mod tests { //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } + #[test] + fn test_field_poly_div_eqdeg() { + let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==", "wAAAAAAAAAAAAAAAAAAAAA==",]); + let json2 = json!(["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let (result, remainder) = element2.div(&element1); + + eprintln!("{:02X?}", (&result, &remainder)); + + assert!(!result.is_zero()); + assert!(!remainder.is_zero()); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_field_poly_div_eqdeg_02() { + let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==", "wAAAAAAAAAAAAAAAAAAAAA==",]); + let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let (result, remainder) = element2.div(&element1); + + eprintln!("{:02X?}", (&result, &remainder)); + + assert!(!result.is_zero()); + assert!(!remainder.is_zero()); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + #[test] fn test_field_poly_powmod_01() { let json1 = json!([ @@ -1043,6 +1066,19 @@ mod tests { #[test] fn test_field_poly_powmod_k1() { + let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==",]); + let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let modulus: Polynomial = Polynomial::from_c_array(&json2); + + let result = element1.pow_mod(1, modulus); + + eprintln!("Result is: {:02X?}", result); + assert_eq!(result.to_c_array(), vec!["JAAAAAAAAAAAAAAAAAAAAA=="]); + } + + #[test] + fn test_field_poly_powmod_k1_modulus_is_deg0() { let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==",]); let json2 = json!(["KryptoanalyseAAAAAAAAA=="]); let element1: Polynomial = Polynomial::from_c_array(&json1); @@ -1054,6 +1090,41 @@ mod tests { assert_eq!(result.to_c_array(), vec!["JAAAAAAAAAAAAAAAAAAAAA=="]); } + #[test] + fn test_field_poly_powmod_k1_eqdeg() { + let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==", "JAAAAAAAAAAAAAAAAAAAAA=="]); + let json2 = json!(["KryptoanalyseAAAAAAAAA==", "KryptoanalyseAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let modulus: Polynomial = Polynomial::from_c_array(&json2); + + let result = element1.pow_mod(1, modulus); + + eprintln!("Result is: {:02X?}", result); + + assert!(!(0 < 0)); + assert_eq!( + result.to_c_array(), + vec!["JAAAAAAAAAAAAAAAAAAAAA==", "JAAAAAAAAAAAAAAAAAAAAA=="] + ); + } + + #[test] + fn test_field_poly_powmod_kn_eqdeg() { + let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==", "JAAAAAAAAAAAAAAAAAAAAA=="]); + let json2 = json!(["KryptoanalyseAAAAAAAAA==", "KryptoanalyseAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let modulus: Polynomial = Polynomial::from_c_array(&json2); + + let result = element1.pow_mod(100000, modulus); + + eprintln!("Result is: {:02X?}", result); + + assert!(!(0 < 0)); + assert_eq!( + result.to_c_array(), + vec!["JAAAAAAAAAAAAAAAAAAAAA==", "JAAAAAAAAAAAAAAAAAAAAA=="] + ); + } #[test] fn test_field_poly_powmod_k0() { let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==",]); @@ -1066,4 +1137,21 @@ mod tests { eprintln!("Result is: {:02X?}", result); assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); } + + #[test] + fn test_field_pow_mod_10mill() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let modulus: Polynomial = Polynomial::from_c_array(&json2); + + let result = element1.pow_mod(10000000, modulus); + + assert!(!result.is_zero()) + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } } From bb5e762a1df258465ff6592d69625a0a4a17caae Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 16 Nov 2024 23:21:10 +0100 Subject: [PATCH 19/79] chore: Try pushing again because no response was received from pipeline --- src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index f546561..fd69ac4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,7 +3,7 @@ use std::{ fs, }; -// TESTING +// TESTING 2 use anyhow::Result; From c3ea652c87bc271a373d10ec7ff30459368b0cce Mon Sep 17 00:00:00 2001 From: Alivecow Date: Wed, 20 Nov 2024 19:37:46 +0100 Subject: [PATCH 20/79] feat: Sorting of polynomial array with rust standard sort implemented --- src/tasks/mod.rs | 12 +++- src/tasks/tasks01/pfmath.rs | 74 +++++++++++++++++++- src/utils/field.rs | 132 ++++++++++++++++++++++++++++-------- 3 files changed, 185 insertions(+), 33 deletions(-) diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index bdb2fb0..a4751e4 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -8,10 +8,12 @@ use tasks01::{ gcm::{gcm_decrypt, gcm_encrypt}, gfmul::gfmul_task, pad_oracle::padding_oracle, - pfmath::{gfdiv, gfpoly_add, gfpoly_divmod, gfpoly_mul, gfpoly_pow, gfpoly_powmod}, + pfmath::{ + gfdiv, gfpoly_add, gfpoly_divmod, gfpoly_mul, gfpoly_pow, gfpoly_powmod, gfpoly_sort, + }, poly2block::poly2block, sea128::sea128, - xex::{fde_xex}, + xex::fde_xex, }; use anyhow::{anyhow, Result}; @@ -118,6 +120,12 @@ pub fn task_deploy(testcase: &Testcase) -> Result { Ok(json) } + "gfpoly_sort" => { + let result = gfpoly_sort(args)?; + let json = json!({"sorted_polys" : json!(result)}); + + Ok(json) + } _ => Err(anyhow!( "Fatal. No compatible action found. Json data was {:?}. Arguments were; {:?}", diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index 4ad3ac7..9742be8 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -2,7 +2,7 @@ use anyhow::Result; use base64::{prelude::BASE64_STANDARD, Engine}; use serde_json::Value; -use crate::utils::field::{FieldElement, Polynomial}; +use crate::utils::field::{sort_polynomial_array, FieldElement, Polynomial}; pub fn gfpoly_add(args: &Value) -> Result { let poly_a = Polynomial::from_c_array(&args["A"].clone()); @@ -67,3 +67,75 @@ pub fn gfpoly_powmod(args: &Value) -> Result { Ok(result) } + +pub fn gfpoly_sort(args: &Value) -> Result> { + let poly_arrays: Vec = serde_json::from_value(args["polys"].clone())?; + let mut polys: Vec = vec![]; + + for array in poly_arrays { + polys.push(Polynomial::from_c_array(&array)); + } + + polys.sort(); + //polys.sort(); + Ok(polys) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn test_poly_sorting() { + let json1 = json!( + {"polys": [ + [ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ], + [ + "WereNoStrangersToLoveA==", + "YouKnowTheRulesAAAAAAA==", + "AndSoDoIAAAAAAAAAAAAAA==" + ], + [ + "NeverGonnaMakeYouCryAA==", + "NeverGonnaSayGoodbyeAA==", + "NeverGonnaTellALieAAAA==", + "AndHurtYouAAAAAAAAAAAA==" + ] + ]}); + + let expected = json!([ + [ + "WereNoStrangersToLoveA==", + "YouKnowTheRulesAAAAAAA==", + "AndSoDoIAAAAAAAAAAAAAA==" + ], + [ + "NeverGonnaMakeYouCryAA==", + "NeverGonnaSayGoodbyeAA==", + "NeverGonnaTellALieAAAA==", + "AndHurtYouAAAAAAAAAAAA==" + ], + [ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ] + ]); + + let sorted_array = gfpoly_sort(&json1).unwrap(); + let mut result: Vec> = vec![]; + for poly in sorted_array { + result.push(poly.to_c_array()); + } + + assert_eq!(json!(result), expected); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } +} diff --git a/src/utils/field.rs b/src/utils/field.rs index e4fff9c..a682eff 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -1,4 +1,7 @@ -use std::ops::{Add, BitXor, Div, Mul, Sub}; +use std::{ + cmp::Ordering, + ops::{Add, BitXor, Div, Mul, Sub}, +}; use anyhow::{anyhow, Ok, Result}; use base64::prelude::*; @@ -8,7 +11,7 @@ use crate::utils::poly::polynomial_2_block; use super::{math::xor_bytes, poly::gfmul}; -#[derive(Debug)] +#[derive(Debug, serde::Serialize)] pub struct Polynomial { polynomial: Vec, } @@ -284,17 +287,14 @@ impl Add for Polynomial { } } -// Helper implementation for subtraction impl Sub for &FieldElement { type Output = FieldElement; fn sub(self, rhs: Self) -> FieldElement { - // In a field of characteristic 2, addition and subtraction are the same operation (XOR) self + rhs } } -// Helper trait for checking emptiness trait IsEmpty { fn is_empty(&self) -> bool; } @@ -310,7 +310,66 @@ impl AsRef<[FieldElement]> for Polynomial { } } -#[derive(Debug)] +impl PartialEq for Polynomial { + fn eq(&self, other: &Self) -> bool { + if self.polynomial.len() != other.polynomial.len() { + return false; + } + // Compare each coefficient + self.polynomial + .iter() + .zip(other.polynomial.iter()) + .all(|(a, b)| a == b) + } +} + +impl PartialOrd for Polynomial { + fn partial_cmp(&self, other: &Self) -> Option { + if self.polynomial.len() != other.polynomial.len() { + return Some(self.polynomial.len().cmp(&other.polynomial.len())); + } else { + for (field_a, field_b) in self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) { + match field_a.cmp(field_b) { + std::cmp::Ordering::Equal => continue, + other => return Some(other.reverse()), + } + } + Some(Ordering::Equal) + } + } +} + +impl Eq for Polynomial {} + +impl Ord for Polynomial { + fn cmp(&self, other: &Self) -> Ordering { + match self.polynomial.len().cmp(&other.polynomial.len()) { + Ordering::Equal => { + for (field_a, field_b) in + self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) + { + match field_a.cmp(field_b) { + std::cmp::Ordering::Equal => continue, + other => return other.reverse(), + } + } + Ordering::Equal + } + other => other, + } + } +} + +pub fn sort_polynomial_array(mut polys: Vec) -> Result> { + // Algorithm to sort polynomials + // First sorting round + // Sorting by degree of polynomial + polys.sort(); + + Ok(polys) +} + +#[derive(Debug, serde::Serialize)] pub struct FieldElement { field_element: Vec, } @@ -462,34 +521,39 @@ impl Div for &FieldElement { } } -/* -impl Rem for FieldElement { - type Output = Self; - fn rem(self, rhs: Self) -> Self::Output { - let result: FieldElement = self.field_element; - - while self.field_element[15] != 0x00 { - self.field_element +impl PartialOrd for FieldElement { + fn partial_cmp(&self, other: &Self) -> Option { + for (byte_a, byte_b) in self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) { + match byte_a.reverse_bits().cmp(&byte_b.reverse_bits()) { + std::cmp::Ordering::Equal => continue, + other => return Some(other), + } } - todo!(); + Some(Ordering::Equal) } } -*/ -/* -impl BitXor for FieldElement { - fn bitxor(self, rhs: Self) -> Self::Output { - FieldElement - } -} -*/ -/* -impl From> for FieldElement { - fn from(item: Vec) -> Self { - FieldElement { bytes: item } +impl PartialEq for FieldElement { + fn eq(&self, other: &Self) -> bool { + self.field_element == other.field_element + } +} + +impl Eq for FieldElement { + // add code here +} + +impl Ord for FieldElement { + fn cmp(&self, other: &Self) -> Ordering { + for (byte_a, byte_b) in self.as_ref().iter().zip(other.as_ref().iter()) { + match byte_a.reverse_bits().cmp(&byte_b.reverse_bits()) { + std::cmp::Ordering::Equal => continue, + other => return other, + } + } + Ordering::Equal } } -*/ #[derive(Debug)] pub struct ByteArray(pub Vec); @@ -1110,8 +1174,16 @@ mod tests { #[test] fn test_field_poly_powmod_kn_eqdeg() { - let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==", "JAAAAAAAAAAAAAAAAAAAAA=="]); - let json2 = json!(["KryptoanalyseAAAAAAAAA==", "KryptoanalyseAAAAAAAAA=="]); + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "JAAAAAAAAAAAAAAAAAAAAA==", + "KryptoanalyseAAAAAAAAA==" + ]); + let json2 = json!([ + "KryptoanalyseAAAAAAAAA==", + "KryptoanalyseAAAAAAAAA==", + "JAAAAAAAAABBAAAAAAAAAA==" + ]); let element1: Polynomial = Polynomial::from_c_array(&json1); let modulus: Polynomial = Polynomial::from_c_array(&json2); From bad946e9acbd312b8b2a9fa075e8c778d98ef9d6 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Wed, 20 Nov 2024 19:50:26 +0100 Subject: [PATCH 21/79] feat: Add proper handling in testcase runner and add testing json file --- src/tasks/mod.rs | 8 +++++++- test_json/poly_algs.json | 29 +++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 test_json/poly_algs.json diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index a4751e4..9d24f8b 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -121,7 +121,13 @@ pub fn task_deploy(testcase: &Testcase) -> Result { Ok(json) } "gfpoly_sort" => { - let result = gfpoly_sort(args)?; + let sorted_array = gfpoly_sort(args)?; + let mut result: Vec> = vec![]; + + for poly in sorted_array { + result.push(poly.to_c_array()); + } + let json = json!({"sorted_polys" : json!(result)}); Ok(json) diff --git a/test_json/poly_algs.json b/test_json/poly_algs.json new file mode 100644 index 0000000..b4a687e --- /dev/null +++ b/test_json/poly_algs.json @@ -0,0 +1,29 @@ +{ + "testcases": { + "b856d760-023d-4b00-bad2-15d2b6da22fe": { + +"action": "gfpoly_sort", +"arguments": { +"polys": [ +[ +"NeverGonnaGiveYouUpAAA==", +"NeverGonnaLetYouDownAA==", +"NeverGonnaRunAroundAAA==", +"AndDesertYouAAAAAAAAAA==" +], +[ +"WereNoStrangersToLoveA==", +"YouKnowTheRulesAAAAAAA==", +"AndSoDoIAAAAAAAAAAAAAA==" +], +[ +"NeverGonnaMakeYouCryAA==", +"NeverGonnaSayGoodbyeAA==", +"NeverGonnaTellALieAAAA==", +"AndHurtYouAAAAAAAAAAAA==" +] +] +} +} + } +} From b63dc86c7eb4b4888759da475fc899e869ddb277 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Thu, 21 Nov 2024 16:56:28 +0100 Subject: [PATCH 22/79] WIP: feat: Change soring behaviour and add new testcase --- src/tasks/tasks01/pfmath.rs | 54 +++++++++++++++++++++++++++++++++++++ src/utils/field.rs | 21 ++++++++------- 2 files changed, 66 insertions(+), 9 deletions(-) diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index 9742be8..71d6991 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -138,4 +138,58 @@ mod tests { assert_eq!(json!(result), expected); //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } + + #[test] + fn test_poly_sorting_02() { + let json1 = json!( + {"polys": [ + [ + "AQAAAAAAAAAAAAAAAAAAAA==", // 0x01 + "AgAAAAAAAAAAAAAAAAAAAA==", // 0x02 + "AwAAAAAAAAAAAAAAAAAAAA==" // 0x03 + ], + [ + "AQAAAAAAAAAAAAAAAAAAAA==", // 0x01 + "AgAAAAAAAAAAAAAAAAAAAA==", // 0x02 + "BAAAAAAAAAAAAAAAAAAAAA==" // 0x04 + ], + [ + "AQAAAAAAAAAAAAAAAAAAAA==", // 0x01 + "AgAAAAAAAAAAAAAAAAAAAA==" // 0x02 + ], + [ + "AQAAAAAAAAAAAAAAAAAAAA==", // 0x01 + "AwAAAAAAAAAAAAAAAAAAAA==" // 0x03 + ] + ],}); + + let expected = json!([ + [ + "WereNoStrangersToLoveA==", + "YouKnowTheRulesAAAAAAA==", + "AndSoDoIAAAAAAAAAAAAAA==" + ], + [ + "NeverGonnaMakeYouCryAA==", + "NeverGonnaSayGoodbyeAA==", + "NeverGonnaTellALieAAAA==", + "AndHurtYouAAAAAAAAAAAA==" + ], + [ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ] + ]); + + let sorted_array = gfpoly_sort(&json1).unwrap(); + let mut result: Vec> = vec![]; + for poly in sorted_array { + result.push(poly.to_c_array()); + } + + assert_eq!(json!(result), expected); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } } diff --git a/src/utils/field.rs b/src/utils/field.rs index a682eff..2c80b51 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -324,17 +324,20 @@ impl PartialEq for Polynomial { } impl PartialOrd for Polynomial { - fn partial_cmp(&self, other: &Self) -> Option { - if self.polynomial.len() != other.polynomial.len() { - return Some(self.polynomial.len().cmp(&other.polynomial.len())); - } else { - for (field_a, field_b) in self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) { - match field_a.cmp(field_b) { - std::cmp::Ordering::Equal => continue, - other => return Some(other.reverse()), + fn partial_cmp(&self, other: &Self) -> Option { + match self.polynomial.len().cmp(&other.polynomial.len()) { + Ordering::Equal => { + for (field_a, field_b) in + self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) + { + match field_a.cmp(field_b) { + std::cmp::Ordering::Equal => continue, + other => return Some(other.reverse()), + } } + Some(Ordering::Equal) } - Some(Ordering::Equal) + other => Some(other), } } } From 81fe06941dbf7d43d05ab12c6f9375c327dded67 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Thu, 21 Nov 2024 17:20:29 +0100 Subject: [PATCH 23/79] fix: add fix for powmod spcial case k=0 --- src/utils/field.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/utils/field.rs b/src/utils/field.rs index 2c80b51..3c7c683 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -85,13 +85,12 @@ impl Polynomial { } if exponent == 0 { - let inter = Polynomial::new(vec![FieldElement::new( + let result = Polynomial::new(vec![FieldElement::new( polynomial_2_block(vec![0], "gcm").unwrap(), )]); - let result = inter.div(&modulus); eprintln!("Returned value is: {:02X?}", result); - return result.1; + return result; } //eprintln!("Initial result: {:?}", result); @@ -1175,6 +1174,20 @@ mod tests { ); } + #[test] + fn test_field_poly_powmod_k0_special() { + let json1 = json!(["NeverGonnaGiveYouUpAAA=="]); + let json2 = json!(["NeverGonnaGiveYouUpAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let modulus: Polynomial = Polynomial::from_c_array(&json2); + + let result = element1.pow_mod(0, modulus); + + eprintln!("Result is: {:02X?}", result); + + assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); + } + #[test] fn test_field_poly_powmod_kn_eqdeg() { let json1 = json!([ From a520a811b41fa35ef269a341a66447ac804043b0 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 22 Nov 2024 11:37:35 +0100 Subject: [PATCH 24/79] fix/feat: Attempt more fixes for the sorting function and add initial monic function --- src/tasks/tasks01/pfmath.rs | 59 ++++++++++++++++------------------- src/utils/field.rs | 62 ++++++++++++++++++++++++------------- 2 files changed, 67 insertions(+), 54 deletions(-) diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index 71d6991..1df7e96 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -143,43 +143,38 @@ mod tests { fn test_poly_sorting_02() { let json1 = json!( {"polys": [ - [ - "AQAAAAAAAAAAAAAAAAAAAA==", // 0x01 - "AgAAAAAAAAAAAAAAAAAAAA==", // 0x02 - "AwAAAAAAAAAAAAAAAAAAAA==" // 0x03 - ], - [ - "AQAAAAAAAAAAAAAAAAAAAA==", // 0x01 - "AgAAAAAAAAAAAAAAAAAAAA==", // 0x02 - "BAAAAAAAAAAAAAAAAAAAAA==" // 0x04 - ], - [ - "AQAAAAAAAAAAAAAAAAAAAA==", // 0x01 - "AgAAAAAAAAAAAAAAAAAAAA==" // 0x02 - ], - [ - "AQAAAAAAAAAAAAAAAAAAAA==", // 0x01 - "AwAAAAAAAAAAAAAAAAAAAA==" // 0x03 - ] - ],}); + [ + "AQAAAAAAAAAAAAAAAAAAAA==", // 0x01 + "AgAAAAAAAAAAAAAAAAAAAA==", // 0x02 + "AwAAAAAAAAAAAAAAAAAAAA==" // 0x03 + ], + [ + "AQAAAAAAAAAAAAAAAAAAAA==", // 0x01 + "AgAAAAAAAAAAAAAAAAAAAA==", // 0x02 + "BAAAAAAAAAAAAAAAAAAAAA==" // 0x04 + ], + [ + "AQAAAAAAAAAAAAAAAAAAAA==", // 0x01 + "AgAAAAAAAAAAAAAAAAAAAA==" // 0x02 + ], + [ + "AQAAAAAAAAAAAAAAAAAAAA==", // 0x01 + "AwAAAAAAAAAAAAAAAAAAAA==" // 0x03 + ] + ],}); let expected = json!([ + ["AQAAAAAAAAAAAAAAAAAAAA==", "AgAAAAAAAAAAAAAAAAAAAA=="], + ["AQAAAAAAAAAAAAAAAAAAAA==", "AwAAAAAAAAAAAAAAAAAAAA=="], [ - "WereNoStrangersToLoveA==", - "YouKnowTheRulesAAAAAAA==", - "AndSoDoIAAAAAAAAAAAAAA==" + "AQAAAAAAAAAAAAAAAAAAAA==", + "AgAAAAAAAAAAAAAAAAAAAA==", + "BAAAAAAAAAAAAAAAAAAAAA==" ], [ - "NeverGonnaMakeYouCryAA==", - "NeverGonnaSayGoodbyeAA==", - "NeverGonnaTellALieAAAA==", - "AndHurtYouAAAAAAAAAAAA==" - ], - [ - "NeverGonnaGiveYouUpAAA==", - "NeverGonnaLetYouDownAA==", - "NeverGonnaRunAroundAAA==", - "AndDesertYouAAAAAAAAAA==" + "AQAAAAAAAAAAAAAAAAAAAA==", + "AgAAAAAAAAAAAAAAAAAAAA==", + "AwAAAAAAAAAAAAAAAAAAAA==" ] ]); diff --git a/src/utils/field.rs b/src/utils/field.rs index 2c80b51..4f1e211 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -1,5 +1,6 @@ use std::{ cmp::Ordering, + mem::discriminant, ops::{Add, BitXor, Div, Mul, Sub}, }; @@ -9,7 +10,10 @@ use serde_json::Value; use crate::utils::poly::polynomial_2_block; -use super::{math::xor_bytes, poly::gfmul}; +use super::{ + math::{reverse_bits_in_bytevec, xor_bytes}, + poly::gfmul, +}; #[derive(Debug, serde::Serialize)] pub struct Polynomial { @@ -211,6 +215,16 @@ impl Polynomial { } true } + + fn monic(mut self) -> Self { + let divident = self.polynomial.last().unwrap().clone(); + + for fieldelement in &mut self.polynomial.iter_mut() { + *fieldelement = fieldelement.clone() / divident.clone(); + } + + todo!(); + } } impl Clone for Polynomial { @@ -325,19 +339,21 @@ impl PartialEq for Polynomial { impl PartialOrd for Polynomial { fn partial_cmp(&self, other: &Self) -> Option { - match self.polynomial.len().cmp(&other.polynomial.len()) { + match other.polynomial.len().cmp(&self.polynomial.len()) { Ordering::Equal => { - for (field_a, field_b) in - self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) - { - match field_a.cmp(field_b) { - std::cmp::Ordering::Equal => continue, - other => return Some(other.reverse()), + for (field_a, field_b) in self.as_ref().iter().zip(other.as_ref().iter()) { + match field_a + .reverse_bits() + .partial_cmp(&field_b.reverse_bits()) + .unwrap() + { + Ordering::Equal => continue, + other => return Some(other), } } Some(Ordering::Equal) } - other => Some(other), + other => Some(other.reverse()), } } } @@ -346,19 +362,17 @@ impl Eq for Polynomial {} impl Ord for Polynomial { fn cmp(&self, other: &Self) -> Ordering { - match self.polynomial.len().cmp(&other.polynomial.len()) { + match other.polynomial.len().cmp(&self.polynomial.len()) { Ordering::Equal => { - for (field_a, field_b) in - self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) - { - match field_a.cmp(field_b) { - std::cmp::Ordering::Equal => continue, - other => return other.reverse(), + for (field_a, field_b) in self.as_ref().iter().zip(other.as_ref().iter()) { + match field_a.reverse_bits().cmp(&field_b.reverse_bits()) { + Ordering::Equal => continue, + other => return other, } } Ordering::Equal } - other => other, + other => other.reverse(), } } } @@ -433,6 +447,10 @@ impl FieldElement { fn is_zero(&self) -> bool { self.field_element.iter().all(|&x| x == 0x00) } + + fn reverse_bits(&self) -> Self { + FieldElement::new(reverse_bits_in_bytevec(self.field_element.clone())) + } } impl Mul for FieldElement { @@ -526,10 +544,10 @@ impl Div for &FieldElement { impl PartialOrd for FieldElement { fn partial_cmp(&self, other: &Self) -> Option { - for (byte_a, byte_b) in self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) { - match byte_a.reverse_bits().cmp(&byte_b.reverse_bits()) { + for (byte_a, byte_b) in self.as_ref().iter().zip(other.as_ref().iter()) { + match byte_a.partial_cmp(&byte_b).unwrap() { std::cmp::Ordering::Equal => continue, - other => return Some(other), + other => return Some(other.reverse()), } } Some(Ordering::Equal) @@ -549,9 +567,9 @@ impl Eq for FieldElement { impl Ord for FieldElement { fn cmp(&self, other: &Self) -> Ordering { for (byte_a, byte_b) in self.as_ref().iter().zip(other.as_ref().iter()) { - match byte_a.reverse_bits().cmp(&byte_b.reverse_bits()) { + match byte_a.cmp(&byte_b) { std::cmp::Ordering::Equal => continue, - other => return other, + other => return other.reverse(), } } Ordering::Equal From ad8326b51e4bdb26b4e23aba420c3152d649d9a1 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 22 Nov 2024 14:36:20 +0100 Subject: [PATCH 25/79] fix: Modifiy the sorting behavior and remove unneded testcases --- src/utils/field.rs | 100 +++++++++++++++------------------------------ 1 file changed, 34 insertions(+), 66 deletions(-) diff --git a/src/utils/field.rs b/src/utils/field.rs index 86f545d..2864a5e 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -340,7 +340,15 @@ impl PartialOrd for Polynomial { fn partial_cmp(&self, other: &Self) -> Option { match other.polynomial.len().cmp(&self.polynomial.len()) { Ordering::Equal => { - for (field_a, field_b) in self.as_ref().iter().zip(other.as_ref().iter()) { + for (field_a, field_b) in + self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) + { + eprintln!( + "Poly partord: {:02X?} {:02X?} ", + self.clone().to_c_array(), + other.clone().to_c_array() + ); + match field_a .reverse_bits() .partial_cmp(&field_b.reverse_bits()) @@ -363,7 +371,9 @@ impl Ord for Polynomial { fn cmp(&self, other: &Self) -> Ordering { match other.polynomial.len().cmp(&self.polynomial.len()) { Ordering::Equal => { - for (field_a, field_b) in self.as_ref().iter().zip(other.as_ref().iter()) { + for (field_a, field_b) in + self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) + { match field_a.reverse_bits().cmp(&field_b.reverse_bits()) { Ordering::Equal => continue, other => return other, @@ -543,10 +553,17 @@ impl Div for &FieldElement { impl PartialOrd for FieldElement { fn partial_cmp(&self, other: &Self) -> Option { - for (byte_a, byte_b) in self.as_ref().iter().zip(other.as_ref().iter()) { - match byte_a.partial_cmp(&byte_b).unwrap() { - std::cmp::Ordering::Equal => continue, - other => return Some(other.reverse()), + for (byte_a, byte_b) in self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) { + eprintln!("Field Partial Ord Bytes: {:02X} {:02X}", byte_a, byte_b); + if byte_a > byte_b { + eprintln!("Bytes were greater"); + return Some(Ordering::Greater); + } else if byte_a < byte_b { + eprintln!("Bytes were less"); + return Some(Ordering::Less); + } else { + eprintln!("Bytes were equal"); + continue; } } Some(Ordering::Equal) @@ -565,10 +582,17 @@ impl Eq for FieldElement { impl Ord for FieldElement { fn cmp(&self, other: &Self) -> Ordering { - for (byte_a, byte_b) in self.as_ref().iter().zip(other.as_ref().iter()) { - match byte_a.cmp(&byte_b) { - std::cmp::Ordering::Equal => continue, - other => return other.reverse(), + for (byte_a, byte_b) in self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) { + eprintln!("Field Ord Bytes: {:02X} {:02X}", byte_a, byte_b); + if byte_a > byte_b { + eprintln!("Bytes were greater"); + return Ordering::Greater; + } else if byte_a < byte_b { + eprintln!("Bytes were less"); + return Ordering::Less; + } else { + eprintln!("Bytes were equal"); + continue; } } Ordering::Equal @@ -1161,37 +1185,6 @@ mod tests { assert_eq!(result.to_c_array(), vec!["JAAAAAAAAAAAAAAAAAAAAA=="]); } - #[test] - fn test_field_poly_powmod_k1_modulus_is_deg0() { - let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==",]); - let json2 = json!(["KryptoanalyseAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let modulus: Polynomial = Polynomial::from_c_array(&json2); - - let result = element1.pow_mod(1, modulus); - - eprintln!("Result is: {:02X?}", result); - assert_eq!(result.to_c_array(), vec!["JAAAAAAAAAAAAAAAAAAAAA=="]); - } - - #[test] - fn test_field_poly_powmod_k1_eqdeg() { - let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==", "JAAAAAAAAAAAAAAAAAAAAA=="]); - let json2 = json!(["KryptoanalyseAAAAAAAAA==", "KryptoanalyseAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let modulus: Polynomial = Polynomial::from_c_array(&json2); - - let result = element1.pow_mod(1, modulus); - - eprintln!("Result is: {:02X?}", result); - - assert!(!(0 < 0)); - assert_eq!( - result.to_c_array(), - vec!["JAAAAAAAAAAAAAAAAAAAAA==", "JAAAAAAAAAAAAAAAAAAAAA=="] - ); - } - #[test] fn test_field_poly_powmod_k0_special() { let json1 = json!(["NeverGonnaGiveYouUpAAA=="]); @@ -1206,31 +1199,6 @@ mod tests { assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); } - #[test] - fn test_field_poly_powmod_kn_eqdeg() { - let json1 = json!([ - "JAAAAAAAAAAAAAAAAAAAAA==", - "JAAAAAAAAAAAAAAAAAAAAA==", - "KryptoanalyseAAAAAAAAA==" - ]); - let json2 = json!([ - "KryptoanalyseAAAAAAAAA==", - "KryptoanalyseAAAAAAAAA==", - "JAAAAAAAAABBAAAAAAAAAA==" - ]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let modulus: Polynomial = Polynomial::from_c_array(&json2); - - let result = element1.pow_mod(100000, modulus); - - eprintln!("Result is: {:02X?}", result); - - assert!(!(0 < 0)); - assert_eq!( - result.to_c_array(), - vec!["JAAAAAAAAAAAAAAAAAAAAA==", "JAAAAAAAAAAAAAAAAAAAAA=="] - ); - } #[test] fn test_field_poly_powmod_k0() { let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==",]); From a5a3ea61faa236cbbebb507e331bc21a05ade249 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 22 Nov 2024 15:28:00 +0100 Subject: [PATCH 26/79] refactor: Split Polynomial class into poly.rs file --- src/tasks/tasks01/pfmath.rs | 2 +- src/utils/field.rs | 802 +---------------------------------- src/utils/poly.rs | 819 +++++++++++++++++++++++++++++++++++- 3 files changed, 825 insertions(+), 798 deletions(-) diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index 1df7e96..9fb7014 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -2,7 +2,7 @@ use anyhow::Result; use base64::{prelude::BASE64_STANDARD, Engine}; use serde_json::Value; -use crate::utils::field::{sort_polynomial_array, FieldElement, Polynomial}; +use crate::utils::{field::FieldElement, poly::Polynomial}; pub fn gfpoly_add(args: &Value) -> Result { let poly_a = Polynomial::from_c_array(&args["A"].clone()); diff --git a/src/utils/field.rs b/src/utils/field.rs index 2864a5e..6894023 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -1,3 +1,6 @@ +use base64::prelude::*; +use std::{str::FromStr, u128, u8, usize}; + use std::{ cmp::Ordering, mem::discriminant, @@ -5,396 +8,14 @@ use std::{ }; use anyhow::{anyhow, Ok, Result}; -use base64::prelude::*; use serde_json::Value; -use crate::utils::poly::polynomial_2_block; - +use super::poly::polynomial_2_block; use super::{ math::{reverse_bits_in_bytevec, xor_bytes}, poly::gfmul, }; -#[derive(Debug, serde::Serialize)] -pub struct Polynomial { - polynomial: Vec, -} - -impl Polynomial { - pub const fn new(polynomial: Vec) -> Self { - Self { polynomial } - } - - pub fn from_c_array(array: &Value) -> Self { - let mut polynomial: Vec = vec![]; - let c_array: Vec = array - .as_array() - .expect("Input is not an array") - .iter() - .map(|x| { - x.as_str() - .expect("Array element is not a string") - .to_string() - }) - .collect(); - - eprintln!("{:?}", c_array); - - for coefficient in c_array { - polynomial.push(FieldElement::new( - BASE64_STANDARD - .decode(coefficient) - .expect("Error on poly decode:"), - )); - } - Self { polynomial } - } - - pub fn to_c_array(self) -> Vec { - let mut output: Vec = vec![]; - for coeff in self.polynomial { - output.push(BASE64_STANDARD.encode(coeff)); - } - - output - } - - pub fn pow(&self, mut exponent: u128) -> Polynomial { - if exponent == 0 { - return Polynomial::new(vec![FieldElement::new( - polynomial_2_block(vec![0], "gcm").unwrap(), - )]); - } - - let base = self.clone(); - let mut result = base.clone(); - exponent -= 1; - while exponent > 0 { - result = result * base.clone(); - exponent -= 1; - } - - result - } - - pub fn pow_mod(mut self, mut exponent: u128, modulus: Polynomial) -> Polynomial { - let mut result: Polynomial = Polynomial::new(vec![FieldElement::new( - polynomial_2_block(vec![0], "gcm").unwrap(), - )]); - - if exponent == 1 { - eprintln!("special case 1: {:02X?}", self.clone().div(&modulus).1); - - return self.div(&modulus).1; - } - - if exponent == 0 { - let result = Polynomial::new(vec![FieldElement::new( - polynomial_2_block(vec![0], "gcm").unwrap(), - )]); - - eprintln!("Returned value is: {:02X?}", result); - return result; - } - - //eprintln!("Initial result: {:?}", result); - while exponent > 0 { - //eprintln!("Current exponent: {:02X}", exponent); - if exponent & 1 == 1 { - let temp = &self * &result; - //eprintln!("After multiplication: {:?}", temp); - result = temp.div(&modulus).1; - //eprintln!("After mod: {:?}", result); - } - let temp_square = &self * &self; - //eprintln!("After squaring: {:?}", temp_square); - self = temp_square.div(&modulus).1; - //eprintln!("After mod: {:?}", self); - exponent >>= 1; - } - - eprintln!("result in powmod before reduction: {:02X?}", result); - - while !result.polynomial.is_empty() - && result - .polynomial - .last() - .unwrap() - .as_ref() - .iter() - .all(|&x| x == 0) - { - result.polynomial.pop(); - } - - eprintln!("result in powmod after reduction: {:02X?}", result); - - if result.is_empty() { - result = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); - } - - result - } - - // Returns (quotient, remainder) - pub fn div(self, rhs: &Self) -> (Self, Self) { - // Div by zero check ommitted since data is guaranteed to be non 0 - - eprintln!("{:?}, {:?}", self.polynomial.len(), rhs.polynomial.len()); - - if self.polynomial.len() < rhs.polynomial.len() { - return (Polynomial::new(vec![FieldElement::new(vec![0; 16])]), self); - } - - let mut remainder = self.clone(); - let divisor = rhs; - let dividend_deg = remainder.polynomial.len() - 1; - let divisor_deg = divisor.polynomial.len() - 1; - - if dividend_deg < divisor_deg { - return ( - Polynomial::new(vec![FieldElement::new( - polynomial_2_block(vec![0; 16], "gcm").unwrap(), - )]), - remainder, - ); - } - - let mut quotient_coeffs = - vec![ - FieldElement::new(polynomial_2_block(vec![0; 16], "gcm").unwrap()); - dividend_deg - divisor_deg + 1 - ]; - - while remainder.polynomial.len() >= divisor.polynomial.len() { - let deg_diff = remainder.polynomial.len() - divisor.polynomial.len(); - - let leading_dividend = remainder.polynomial.last().unwrap(); - let leading_divisor = divisor.polynomial.last().unwrap(); - let quot_coeff = leading_dividend / leading_divisor; - - quotient_coeffs[deg_diff] = quot_coeff.clone(); - - let mut subtrahend = - vec![FieldElement::new(polynomial_2_block(vec![0; 16], "gcm").unwrap()); deg_diff]; - subtrahend.extend( - divisor - .polynomial - .iter() - .map(|x| x.clone() * quot_coeff.clone()), - ); - let subtrahend_poly = Polynomial::new(subtrahend); - - remainder = remainder + subtrahend_poly; - - while !remainder.polynomial.is_empty() - && remainder - .polynomial - .last() - .unwrap() - .as_ref() - .iter() - .all(|&x| x == 0) - { - remainder.polynomial.pop(); - } - } - - if remainder.is_empty() { - remainder = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); - } - (Polynomial::new(quotient_coeffs), remainder) - } - - fn is_zero(&self) -> bool { - for field_element in &self.polynomial { - if !field_element.is_zero() { - return false; - } - } - true - } - - fn monic(mut self) -> Self { - let divident = self.polynomial.last().unwrap().clone(); - - for fieldelement in &mut self.polynomial.iter_mut() { - *fieldelement = fieldelement.clone() / divident.clone(); - } - - todo!(); - } -} - -impl Clone for Polynomial { - fn clone(&self) -> Self { - Polynomial { - polynomial: self.polynomial.clone(), - } - } -} - -impl Mul for Polynomial { - type Output = Self; - fn mul(self, rhs: Self) -> Self::Output { - if self.is_zero() || rhs.is_zero() { - return Polynomial::new(vec![FieldElement::new(vec![0; 16])]); - } - let mut polynomial: Vec = - vec![FieldElement::new(vec![0; 16]); self.polynomial.len() + rhs.polynomial.len() - 1]; - for i in 0..self.polynomial.len() { - for j in 0..rhs.polynomial.len() { - polynomial[i + j] = &polynomial[i + j] - + &(self.polynomial.get(i).unwrap() * rhs.polynomial.get(j).unwrap()); - } - } - Polynomial::new(polynomial) - } -} - -impl Mul for &Polynomial { - type Output = Polynomial; - fn mul(self, rhs: Self) -> Self::Output { - if self.is_zero() || rhs.is_zero() { - return Polynomial::new(vec![FieldElement::new(vec![0])]); - } - let mut polynomial: Vec = - vec![FieldElement::new(vec![0; 16]); self.polynomial.len() + rhs.polynomial.len() - 1]; - for i in 0..self.polynomial.len() { - for j in 0..rhs.polynomial.len() { - polynomial[i + j] = &polynomial[i + j] - + &(self.polynomial.get(i).unwrap() * rhs.polynomial.get(j).unwrap()); - } - } - Polynomial::new(polynomial) - } -} - -impl Add for Polynomial { - type Output = Self; - fn add(self, rhs: Self) -> Self::Output { - let mut polynomial: Vec; - - if self.polynomial.len() > rhs.polynomial.len() { - polynomial = self.polynomial.clone(); - for i in 0..rhs.polynomial.len() { - polynomial[i] = polynomial[i].clone() + rhs.polynomial[i].clone(); - } - } else { - polynomial = rhs.polynomial.clone(); - for i in 0..self.polynomial.len() { - polynomial[i] = polynomial[i].clone() + self.polynomial[i].clone(); - } - } - - while !polynomial.is_empty() && polynomial.last().unwrap().as_ref().iter().all(|&x| x == 0) - { - polynomial.pop(); - } - - if polynomial.is_empty() { - return Polynomial::new(vec![FieldElement::new(vec![0; 16])]); - } - - Polynomial::new(polynomial) - } -} - -impl Sub for &FieldElement { - type Output = FieldElement; - - fn sub(self, rhs: Self) -> FieldElement { - self + rhs - } -} - -trait IsEmpty { - fn is_empty(&self) -> bool; -} - -impl IsEmpty for Polynomial { - fn is_empty(&self) -> bool { - self.polynomial.is_empty() - } -} -impl AsRef<[FieldElement]> for Polynomial { - fn as_ref(&self) -> &[FieldElement] { - &self.polynomial - } -} - -impl PartialEq for Polynomial { - fn eq(&self, other: &Self) -> bool { - if self.polynomial.len() != other.polynomial.len() { - return false; - } - // Compare each coefficient - self.polynomial - .iter() - .zip(other.polynomial.iter()) - .all(|(a, b)| a == b) - } -} - -impl PartialOrd for Polynomial { - fn partial_cmp(&self, other: &Self) -> Option { - match other.polynomial.len().cmp(&self.polynomial.len()) { - Ordering::Equal => { - for (field_a, field_b) in - self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) - { - eprintln!( - "Poly partord: {:02X?} {:02X?} ", - self.clone().to_c_array(), - other.clone().to_c_array() - ); - - match field_a - .reverse_bits() - .partial_cmp(&field_b.reverse_bits()) - .unwrap() - { - Ordering::Equal => continue, - other => return Some(other), - } - } - Some(Ordering::Equal) - } - other => Some(other.reverse()), - } - } -} - -impl Eq for Polynomial {} - -impl Ord for Polynomial { - fn cmp(&self, other: &Self) -> Ordering { - match other.polynomial.len().cmp(&self.polynomial.len()) { - Ordering::Equal => { - for (field_a, field_b) in - self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) - { - match field_a.reverse_bits().cmp(&field_b.reverse_bits()) { - Ordering::Equal => continue, - other => return other, - } - } - Ordering::Equal - } - other => other.reverse(), - } - } -} - -pub fn sort_polynomial_array(mut polys: Vec) -> Result> { - // Algorithm to sort polynomials - // First sorting round - // Sorting by degree of polynomial - polys.sort(); - - Ok(polys) -} - #[derive(Debug, serde::Serialize)] pub struct FieldElement { field_element: Vec, @@ -453,11 +74,11 @@ impl FieldElement { FieldElement::new(inverse) } - fn is_zero(&self) -> bool { + pub fn is_zero(&self) -> bool { self.field_element.iter().all(|&x| x == 0x00) } - fn reverse_bits(&self) -> Self { + pub fn reverse_bits(&self) -> Self { FieldElement::new(reverse_bits_in_bytevec(self.field_element.clone())) } } @@ -817,415 +438,4 @@ mod tests { assert_eq!(BASE64_STANDARD.encode(sum), "OZuIncPAGEp4tYouDownAA=="); } - - #[test] - fn test_field_add_03() { - let json1 = json!([ - "NeverGonnaGiveYouUpAAA==", - "NeverGonnaLetYouDownAA==", - "NeverGonnaRunAroundAAA==", - "AndDesertYouAAAAAAAAAA==" - ]); - let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let element2: Polynomial = Polynomial::from_c_array(&json2); - - let sum = element2 + element1; - - assert_eq!( - sum.to_c_array(), - vec![ - "H1d3GuyA9/0OxeYouUpAAA==", - "OZuIncPAGEp4tYouDownAA==", - "NeverGonnaRunAroundAAA==", - "AndDesertYouAAAAAAAAAA==" - ] - ); - } - - #[test] - fn test_field_add_multiple_zeros() { - let json1 = json!([ - "AAAAAAAAAAAAAAAAAAAAAA==", - "AAAAAAAAAAAAAAAAAAAAAA==", - "AAAAAAAAAAAAAAAAAAAAAA==", - "AAAAAAAAAAAAAAAAAAAAAA==" - ]); - let json2 = json!(["AAAAAAAAAAAAAAAAAAAAAA==", "AAAAAAAAAAAAAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let element2: Polynomial = Polynomial::from_c_array(&json2); - - let sum = element2 + element1; - - assert_eq!(sum.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA==",]); - } - - #[test] - fn test_field_add_same_element() { - let json1 = json!(["NeverGonnaGiveYouUpAAA=="]); - let json2 = json!(["NeverGonnaGiveYouUpAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let element2: Polynomial = Polynomial::from_c_array(&json2); - - let sum = element2 + element1; - - assert_eq!(sum.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA==",]); - } - - #[test] - fn test_field_add_zero() { - let json1 = json!([ - "NeverGonnaGiveYouUpAAA==", - "NeverGonnaLetYouDownAA==", - "NeverGonnaRunAroundAAA==", - "AndDesertYouAAAAAAAAAA==" - ]); - let json2 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let element2: Polynomial = Polynomial::from_c_array(&json2); - - let sum = element2 + element1; - - assert_eq!( - sum.to_c_array(), - vec![ - "NeverGonnaGiveYouUpAAA==", - "NeverGonnaLetYouDownAA==", - "NeverGonnaRunAroundAAA==", - "AndDesertYouAAAAAAAAAA==" - ] - ); - } - - #[test] - fn test_field_add_zero_to_zero() { - let json1 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); - let json2 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let element2: Polynomial = Polynomial::from_c_array(&json2); - - let sum = element2 + element1; - - assert_eq!(sum.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA=="]); - } - - #[test] - fn test_field_add_short_to_long() { - let json1 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); - let json2 = json!([ - "NeverGonnaGiveYouUpAAA==", - "NeverGonnaLetYouDownAA==", - "NeverGonnaRunAroundAAA==", - "AndDesertYouAAAAAAAAAA==" - ]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let element2: Polynomial = Polynomial::from_c_array(&json2); - - let sum = element2 + element1; - - assert_eq!( - sum.to_c_array(), - vec![ - "NeverGonnaGiveYouUpAAA==", - "NeverGonnaLetYouDownAA==", - "NeverGonnaRunAroundAAA==", - "AndDesertYouAAAAAAAAAA==" - ] - ); - } - - #[test] - fn test_field_mul_01() { - let json1 = json!([ - "JAAAAAAAAAAAAAAAAAAAAA==", - "wAAAAAAAAAAAAAAAAAAAAA==", - "ACAAAAAAAAAAAAAAAAAAAA==" - ]); - let json2 = json!(["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let element2: Polynomial = Polynomial::from_c_array(&json2); - - //eprintln!("{:?}", element1); - - let result = element1 * element2; - - assert_eq!( - result.to_c_array(), - vec![ - "MoAAAAAAAAAAAAAAAAAAAA==", - "sUgAAAAAAAAAAAAAAAAAAA==", - "MbQAAAAAAAAAAAAAAAAAAA==", - "AAhAAAAAAAAAAAAAAAAAAA==" - ] - ); - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); - } - - #[test] - fn test_poly_mul_with_zero() { - let json1 = json!([ - "JAAAAAAAAAAAAAAAAAAAAA==", - "wAAAAAAAAAAAAAAAAAAAAA==", - "ACAAAAAAAAAAAAAAAAAAAA==" - ]); - let json2 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let element2: Polynomial = Polynomial::from_c_array(&json2); - - //eprintln!("{:?}", element1); - - let result = element1 * element2; - - assert_eq!(result.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA=="]); - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); - } - - #[test] - fn test_poly_pow_01() { - let json1 = json!([ - "JAAAAAAAAAAAAAAAAAAAAA==", - "wAAAAAAAAAAAAAAAAAAAAA==", - "ACAAAAAAAAAAAAAAAAAAAA==" - ]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - - let result = element1.pow(3); - - assert_eq!( - result.to_c_array(), - vec![ - "AkkAAAAAAAAAAAAAAAAAAA==", - "DDAAAAAAAAAAAAAAAAAAAA==", - "LQIIAAAAAAAAAAAAAAAAAA==", - "8AAAAAAAAAAAAAAAAAAAAA==", - "ACgCQAAAAAAAAAAAAAAAAA==", - "AAAMAAAAAAAAAAAAAAAAAA==", - "AAAAAgAAAAAAAAAAAAAAAA==" - ] - ); - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); - } - - #[test] - fn test_poly_pow_with_zero() { - let json1 = json!([ - "JAAAAAAAAAAAAAAAAAAAAA==", - "wAAAAAAAAAAAAAAAAAAAAA==", - "ACAAAAAAAAAAAAAAAAAAAA==" - ]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - - let result = element1.pow(0); - - assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); - } - - #[test] - fn test_field_pow_mod_01() { - let json1 = json!([ - "JAAAAAAAAAAAAAAAAAAAAA==", - "wAAAAAAAAAAAAAAAAAAAAA==", - "ACAAAAAAAAAAAAAAAAAAAA==" - ]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - - let result = element1.pow(3); - - assert_eq!( - result.to_c_array(), - vec![ - "AkkAAAAAAAAAAAAAAAAAAA==", - "DDAAAAAAAAAAAAAAAAAAAA==", - "LQIIAAAAAAAAAAAAAAAAAA==", - "8AAAAAAAAAAAAAAAAAAAAA==", - "ACgCQAAAAAAAAAAAAAAAAA==", - "AAAMAAAAAAAAAAAAAAAAAA==", - "AAAAAgAAAAAAAAAAAAAAAA==" - ] - ); - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); - } - - #[test] - fn test_field_pow_mod_with_zero() { - let json1 = json!([ - "JAAAAAAAAAAAAAAAAAAAAA==", - "wAAAAAAAAAAAAAAAAAAAAA==", - "ACAAAAAAAAAAAAAAAAAAAA==" - ]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - - let result = element1.pow(0); - - assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); - } - - #[test] - fn test_poly_div_01() { - let element1 = - FieldElement::new(BASE64_STANDARD.decode("JAAAAAAAAAAAAAAAAAAAAA==").unwrap()); - - let element2 = - FieldElement::new(BASE64_STANDARD.decode("wAAAAAAAAAAAAAAAAAAAAA==").unwrap()); - - let result = element1 / element2; - - assert_eq!(BASE64_STANDARD.encode(result), "OAAAAAAAAAAAAAAAAAAAAA=="); - } - - #[test] - fn test_field_poly_div_01() { - let json1 = json!([ - "JAAAAAAAAAAAAAAAAAAAAA==", - "wAAAAAAAAAAAAAAAAAAAAA==", - "ACAAAAAAAAAAAAAAAAAAAA==" - ]); - let json2 = json!(["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let element2: Polynomial = Polynomial::from_c_array(&json2); - - //eprintln!("{:?}", element1); - - println!("Beginning the new division"); - let (result, remainder) = element1.div(&element2); - - assert_eq!( - result.to_c_array(), - vec!["nAIAgCAIAgCAIAgCAIAgCg==", "m85znOc5znOc5znOc5znOQ=="] - ); - assert_eq!(remainder.to_c_array(), vec!["lQNA0DQNA0DQNA0DQNA0Dg=="]); - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); - } - - #[test] - fn test_field_poly_div_larger_div() { - let json1 = json!([ - "JAAAAAAAAAAAAAAAAAAAAA==", - "wAAAAAAAAAAAAAAAAAAAAA==", - "ACAAAAAAAAAAAAAAAAAAAA==" - ]); - let json2 = json!(["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let element2: Polynomial = Polynomial::from_c_array(&json2); - - //eprintln!("{:?}", element1); - - println!("Beginning the new division"); - let (result, remainder) = element2.div(&element1); - - assert_eq!(result.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA=="]); - assert_eq!( - remainder.to_c_array(), - vec!["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="] - ); - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); - } - - #[test] - fn test_field_poly_div_eqdeg() { - let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==", "wAAAAAAAAAAAAAAAAAAAAA==",]); - let json2 = json!(["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let element2: Polynomial = Polynomial::from_c_array(&json2); - - let (result, remainder) = element2.div(&element1); - - eprintln!("{:02X?}", (&result, &remainder)); - - assert!(!result.is_zero()); - assert!(!remainder.is_zero()); - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); - } - - #[test] - fn test_field_poly_div_eqdeg_02() { - let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==", "wAAAAAAAAAAAAAAAAAAAAA==",]); - let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let element2: Polynomial = Polynomial::from_c_array(&json2); - - let (result, remainder) = element2.div(&element1); - - eprintln!("{:02X?}", (&result, &remainder)); - - assert!(!result.is_zero()); - assert!(!remainder.is_zero()); - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); - } - - #[test] - fn test_field_poly_powmod_01() { - let json1 = json!([ - "JAAAAAAAAAAAAAAAAAAAAA==", - "wAAAAAAAAAAAAAAAAAAAAA==", - "ACAAAAAAAAAAAAAAAAAAAA==" - ]); - let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let modulus: Polynomial = Polynomial::from_c_array(&json2); - - let result = element1.pow_mod(1000, modulus); - - eprintln!("Result is: {:02X?}", result); - assert_eq!(result.to_c_array(), vec!["oNXl5P8xq2WpUTP92u25zg=="]); - } - - #[test] - fn test_field_poly_powmod_k1() { - let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==",]); - let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let modulus: Polynomial = Polynomial::from_c_array(&json2); - - let result = element1.pow_mod(1, modulus); - - eprintln!("Result is: {:02X?}", result); - assert_eq!(result.to_c_array(), vec!["JAAAAAAAAAAAAAAAAAAAAA=="]); - } - - #[test] - fn test_field_poly_powmod_k0_special() { - let json1 = json!(["NeverGonnaGiveYouUpAAA=="]); - let json2 = json!(["NeverGonnaGiveYouUpAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let modulus: Polynomial = Polynomial::from_c_array(&json2); - - let result = element1.pow_mod(0, modulus); - - eprintln!("Result is: {:02X?}", result); - - assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); - } - - #[test] - fn test_field_poly_powmod_k0() { - let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==",]); - let json2 = json!(["KryptoanalyseAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let modulus: Polynomial = Polynomial::from_c_array(&json2); - - let result = element1.pow_mod(0, modulus); - - eprintln!("Result is: {:02X?}", result); - assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); - } - - #[test] - fn test_field_pow_mod_10mill() { - let json1 = json!([ - "JAAAAAAAAAAAAAAAAAAAAA==", - "wAAAAAAAAAAAAAAAAAAAAA==", - "ACAAAAAAAAAAAAAAAAAAAA==" - ]); - let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); - let modulus: Polynomial = Polynomial::from_c_array(&json2); - - let result = element1.pow_mod(10000000, modulus); - - assert!(!result.is_zero()) - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); - } } diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 3866e49..99def36 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -1,8 +1,391 @@ use crate::utils::field::ByteArray; -use anyhow::{anyhow, Result}; use base64::prelude::*; use std::{str::FromStr, u128, u8, usize}; +use std::{ + cmp::Ordering, + mem::discriminant, + ops::{Add, BitXor, Div, Mul, Sub}, +}; + +use anyhow::{anyhow, Ok, Result}; +use serde_json::Value; + +use super::field::FieldElement; +use super::math::{reverse_bits_in_bytevec, xor_bytes}; + +#[derive(Debug, serde::Serialize)] +pub struct Polynomial { + polynomial: Vec, +} + +impl Polynomial { + pub const fn new(polynomial: Vec) -> Self { + Self { polynomial } + } + + pub fn from_c_array(array: &Value) -> Self { + let mut polynomial: Vec = vec![]; + let c_array: Vec = array + .as_array() + .expect("Input is not an array") + .iter() + .map(|x| { + x.as_str() + .expect("Array element is not a string") + .to_string() + }) + .collect(); + + eprintln!("{:?}", c_array); + + for coefficient in c_array { + polynomial.push(FieldElement::new( + BASE64_STANDARD + .decode(coefficient) + .expect("Error on poly decode:"), + )); + } + Self { polynomial } + } + + pub fn to_c_array(self) -> Vec { + let mut output: Vec = vec![]; + for coeff in self.polynomial { + output.push(BASE64_STANDARD.encode(coeff)); + } + + output + } + + pub fn pow(&self, mut exponent: u128) -> Polynomial { + if exponent == 0 { + return Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![0], "gcm").unwrap(), + )]); + } + + let base = self.clone(); + let mut result = base.clone(); + exponent -= 1; + while exponent > 0 { + result = result * base.clone(); + exponent -= 1; + } + + result + } + + pub fn pow_mod(mut self, mut exponent: u128, modulus: Polynomial) -> Polynomial { + let mut result: Polynomial = Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![0], "gcm").unwrap(), + )]); + + if exponent == 1 { + eprintln!("special case 1: {:02X?}", self.clone().div(&modulus).1); + + return self.div(&modulus).1; + } + + if exponent == 0 { + let result = Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![0], "gcm").unwrap(), + )]); + + eprintln!("Returned value is: {:02X?}", result); + return result; + } + + //eprintln!("Initial result: {:?}", result); + while exponent > 0 { + //eprintln!("Current exponent: {:02X}", exponent); + if exponent & 1 == 1 { + let temp = &self * &result; + //eprintln!("After multiplication: {:?}", temp); + result = temp.div(&modulus).1; + //eprintln!("After mod: {:?}", result); + } + let temp_square = &self * &self; + //eprintln!("After squaring: {:?}", temp_square); + self = temp_square.div(&modulus).1; + //eprintln!("After mod: {:?}", self); + exponent >>= 1; + } + + eprintln!("result in powmod before reduction: {:02X?}", result); + + while !result.polynomial.is_empty() + && result + .polynomial + .last() + .unwrap() + .as_ref() + .iter() + .all(|&x| x == 0) + { + result.polynomial.pop(); + } + + eprintln!("result in powmod after reduction: {:02X?}", result); + + if result.is_empty() { + result = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + } + + result + } + + // Returns (quotient, remainder) + pub fn div(self, rhs: &Self) -> (Self, Self) { + // Div by zero check ommitted since data is guaranteed to be non 0 + + eprintln!("{:?}, {:?}", self.polynomial.len(), rhs.polynomial.len()); + + if self.polynomial.len() < rhs.polynomial.len() { + return (Polynomial::new(vec![FieldElement::new(vec![0; 16])]), self); + } + + let mut remainder = self.clone(); + let divisor = rhs; + let dividend_deg = remainder.polynomial.len() - 1; + let divisor_deg = divisor.polynomial.len() - 1; + + if dividend_deg < divisor_deg { + return ( + Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![0; 16], "gcm").unwrap(), + )]), + remainder, + ); + } + + let mut quotient_coeffs = + vec![ + FieldElement::new(polynomial_2_block(vec![0; 16], "gcm").unwrap()); + dividend_deg - divisor_deg + 1 + ]; + + while remainder.polynomial.len() >= divisor.polynomial.len() { + let deg_diff = remainder.polynomial.len() - divisor.polynomial.len(); + + let leading_dividend = remainder.polynomial.last().unwrap(); + let leading_divisor = divisor.polynomial.last().unwrap(); + let quot_coeff = leading_dividend / leading_divisor; + + quotient_coeffs[deg_diff] = quot_coeff.clone(); + + let mut subtrahend = + vec![FieldElement::new(polynomial_2_block(vec![0; 16], "gcm").unwrap()); deg_diff]; + subtrahend.extend( + divisor + .polynomial + .iter() + .map(|x| x.clone() * quot_coeff.clone()), + ); + let subtrahend_poly = Polynomial::new(subtrahend); + + remainder = remainder + subtrahend_poly; + + while !remainder.polynomial.is_empty() + && remainder + .polynomial + .last() + .unwrap() + .as_ref() + .iter() + .all(|&x| x == 0) + { + remainder.polynomial.pop(); + } + } + + if remainder.is_empty() { + remainder = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + } + (Polynomial::new(quotient_coeffs), remainder) + } + + fn is_zero(&self) -> bool { + for field_element in &self.polynomial { + if !field_element.is_zero() { + return false; + } + } + true + } + + fn monic(mut self) -> Self { + let divident = self.polynomial.last().unwrap().clone(); + + for fieldelement in &mut self.polynomial.iter_mut() { + *fieldelement = fieldelement.clone() / divident.clone(); + } + + self + } +} + +impl Clone for Polynomial { + fn clone(&self) -> Self { + Polynomial { + polynomial: self.polynomial.clone(), + } + } +} + +impl Mul for Polynomial { + type Output = Self; + fn mul(self, rhs: Self) -> Self::Output { + if self.is_zero() || rhs.is_zero() { + return Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + } + let mut polynomial: Vec = + vec![FieldElement::new(vec![0; 16]); self.polynomial.len() + rhs.polynomial.len() - 1]; + for i in 0..self.polynomial.len() { + for j in 0..rhs.polynomial.len() { + polynomial[i + j] = &polynomial[i + j] + + &(self.polynomial.get(i).unwrap() * rhs.polynomial.get(j).unwrap()); + } + } + Polynomial::new(polynomial) + } +} + +impl Mul for &Polynomial { + type Output = Polynomial; + fn mul(self, rhs: Self) -> Self::Output { + if self.is_zero() || rhs.is_zero() { + return Polynomial::new(vec![FieldElement::new(vec![0])]); + } + let mut polynomial: Vec = + vec![FieldElement::new(vec![0; 16]); self.polynomial.len() + rhs.polynomial.len() - 1]; + for i in 0..self.polynomial.len() { + for j in 0..rhs.polynomial.len() { + polynomial[i + j] = &polynomial[i + j] + + &(self.polynomial.get(i).unwrap() * rhs.polynomial.get(j).unwrap()); + } + } + Polynomial::new(polynomial) + } +} + +impl Add for Polynomial { + type Output = Self; + fn add(self, rhs: Self) -> Self::Output { + let mut polynomial: Vec; + + if self.polynomial.len() > rhs.polynomial.len() { + polynomial = self.polynomial.clone(); + for i in 0..rhs.polynomial.len() { + polynomial[i] = polynomial[i].clone() + rhs.polynomial[i].clone(); + } + } else { + polynomial = rhs.polynomial.clone(); + for i in 0..self.polynomial.len() { + polynomial[i] = polynomial[i].clone() + self.polynomial[i].clone(); + } + } + + while !polynomial.is_empty() && polynomial.last().unwrap().as_ref().iter().all(|&x| x == 0) + { + polynomial.pop(); + } + + if polynomial.is_empty() { + return Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + } + + Polynomial::new(polynomial) + } +} + +trait IsEmpty { + fn is_empty(&self) -> bool; +} + +impl IsEmpty for Polynomial { + fn is_empty(&self) -> bool { + self.polynomial.is_empty() + } +} +impl AsRef<[FieldElement]> for Polynomial { + fn as_ref(&self) -> &[FieldElement] { + &self.polynomial + } +} + +impl PartialEq for Polynomial { + fn eq(&self, other: &Self) -> bool { + if self.polynomial.len() != other.polynomial.len() { + return false; + } + // Compare each coefficient + self.polynomial + .iter() + .zip(other.polynomial.iter()) + .all(|(a, b)| a == b) + } +} + +impl PartialOrd for Polynomial { + fn partial_cmp(&self, other: &Self) -> Option { + match other.polynomial.len().cmp(&self.polynomial.len()) { + Ordering::Equal => { + for (field_a, field_b) in + self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) + { + eprintln!( + "Poly partord: {:02X?} {:02X?} ", + self.clone().to_c_array(), + other.clone().to_c_array() + ); + + match field_a + .reverse_bits() + .partial_cmp(&field_b.reverse_bits()) + .unwrap() + { + Ordering::Equal => continue, + other => return Some(other), + } + } + Some(Ordering::Equal) + } + other => Some(other.reverse()), + } + } +} + +impl Eq for Polynomial {} + +impl Ord for Polynomial { + fn cmp(&self, other: &Self) -> Ordering { + match other.polynomial.len().cmp(&self.polynomial.len()) { + Ordering::Equal => { + for (field_a, field_b) in + self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) + { + match field_a.reverse_bits().cmp(&field_b.reverse_bits()) { + Ordering::Equal => continue, + other => return other, + } + } + Ordering::Equal + } + other => other.reverse(), + } + } +} + +pub fn sort_polynomial_array(mut polys: Vec) -> Result> { + // Algorithm to sort polynomials + // First sorting round + // Sorting by degree of polynomial + polys.sort(); + + Ok(polys) +} + pub const RED_POLY: u128 = 0x87000000_00000000_00000000_00000000; pub fn gfmul(poly_a: &Vec, poly_b: &Vec, semantic: &str) -> Result> { @@ -189,6 +572,7 @@ pub fn coefficient_to_binary(coefficients: Vec) -> u128 { mod tests { use crate::utils::poly::b64_2_num; use anyhow::Result; + use serde_json::json; // Note this useful idiom: importing names from outer (for mod tests) scope. use super::*; @@ -256,4 +640,437 @@ mod tests { Ok(()) } + + #[test] + fn test_field_add_03() { + let json1 = json!([ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ]); + let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let sum = element2 + element1; + + assert_eq!( + sum.to_c_array(), + vec![ + "H1d3GuyA9/0OxeYouUpAAA==", + "OZuIncPAGEp4tYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ] + ); + } + + #[test] + fn test_field_add_multiple_zeros() { + let json1 = json!([ + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==" + ]); + let json2 = json!(["AAAAAAAAAAAAAAAAAAAAAA==", "AAAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let sum = element2 + element1; + + assert_eq!(sum.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA==",]); + } + + #[test] + fn test_field_add_same_element() { + let json1 = json!(["NeverGonnaGiveYouUpAAA=="]); + let json2 = json!(["NeverGonnaGiveYouUpAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let sum = element2 + element1; + + assert_eq!(sum.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA==",]); + } + + #[test] + fn test_field_add_zero() { + let json1 = json!([ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ]); + let json2 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let sum = element2 + element1; + + assert_eq!( + sum.to_c_array(), + vec![ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ] + ); + } + + #[test] + fn test_field_add_zero_to_zero() { + let json1 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let json2 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let sum = element2 + element1; + + assert_eq!(sum.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA=="]); + } + + #[test] + fn test_field_add_short_to_long() { + let json1 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let json2 = json!([ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let sum = element2 + element1; + + assert_eq!( + sum.to_c_array(), + vec![ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ] + ); + } + + #[test] + fn test_field_mul_01() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let json2 = json!(["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + //eprintln!("{:?}", element1); + + let result = element1 * element2; + + assert_eq!( + result.to_c_array(), + vec![ + "MoAAAAAAAAAAAAAAAAAAAA==", + "sUgAAAAAAAAAAAAAAAAAAA==", + "MbQAAAAAAAAAAAAAAAAAAA==", + "AAhAAAAAAAAAAAAAAAAAAA==" + ] + ); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_poly_mul_with_zero() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let json2 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + //eprintln!("{:?}", element1); + + let result = element1 * element2; + + assert_eq!(result.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA=="]); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_poly_pow_01() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.pow(3); + + assert_eq!( + result.to_c_array(), + vec![ + "AkkAAAAAAAAAAAAAAAAAAA==", + "DDAAAAAAAAAAAAAAAAAAAA==", + "LQIIAAAAAAAAAAAAAAAAAA==", + "8AAAAAAAAAAAAAAAAAAAAA==", + "ACgCQAAAAAAAAAAAAAAAAA==", + "AAAMAAAAAAAAAAAAAAAAAA==", + "AAAAAgAAAAAAAAAAAAAAAA==" + ] + ); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_poly_pow_with_zero() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.pow(0); + + assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_field_pow_mod_01() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.pow(3); + + assert_eq!( + result.to_c_array(), + vec![ + "AkkAAAAAAAAAAAAAAAAAAA==", + "DDAAAAAAAAAAAAAAAAAAAA==", + "LQIIAAAAAAAAAAAAAAAAAA==", + "8AAAAAAAAAAAAAAAAAAAAA==", + "ACgCQAAAAAAAAAAAAAAAAA==", + "AAAMAAAAAAAAAAAAAAAAAA==", + "AAAAAgAAAAAAAAAAAAAAAA==" + ] + ); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_field_pow_mod_with_zero() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.pow(0); + + assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_poly_div_01() { + let element1 = + FieldElement::new(BASE64_STANDARD.decode("JAAAAAAAAAAAAAAAAAAAAA==").unwrap()); + + let element2 = + FieldElement::new(BASE64_STANDARD.decode("wAAAAAAAAAAAAAAAAAAAAA==").unwrap()); + + let result = element1 / element2; + + assert_eq!(BASE64_STANDARD.encode(result), "OAAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_field_poly_div_01() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let json2 = json!(["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + //eprintln!("{:?}", element1); + + println!("Beginning the new division"); + let (result, remainder) = element1.div(&element2); + + assert_eq!( + result.to_c_array(), + vec!["nAIAgCAIAgCAIAgCAIAgCg==", "m85znOc5znOc5znOc5znOQ=="] + ); + assert_eq!(remainder.to_c_array(), vec!["lQNA0DQNA0DQNA0DQNA0Dg=="]); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_field_poly_div_larger_div() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let json2 = json!(["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + //eprintln!("{:?}", element1); + + println!("Beginning the new division"); + let (result, remainder) = element2.div(&element1); + + assert_eq!(result.to_c_array(), vec!["AAAAAAAAAAAAAAAAAAAAAA=="]); + assert_eq!( + remainder.to_c_array(), + vec!["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="] + ); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_field_poly_div_eqdeg() { + let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==", "wAAAAAAAAAAAAAAAAAAAAA==",]); + let json2 = json!(["0AAAAAAAAAAAAAAAAAAAAA==", "IQAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let (result, remainder) = element2.div(&element1); + + eprintln!("{:02X?}", (&result, &remainder)); + + assert!(!result.is_zero()); + assert!(!remainder.is_zero()); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_field_poly_div_eqdeg_02() { + let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==", "wAAAAAAAAAAAAAAAAAAAAA==",]); + let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let element2: Polynomial = Polynomial::from_c_array(&json2); + + let (result, remainder) = element2.div(&element1); + + eprintln!("{:02X?}", (&result, &remainder)); + + assert!(!result.is_zero()); + assert!(!remainder.is_zero()); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_field_poly_powmod_01() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let modulus: Polynomial = Polynomial::from_c_array(&json2); + + let result = element1.pow_mod(1000, modulus); + + eprintln!("Result is: {:02X?}", result); + assert_eq!(result.to_c_array(), vec!["oNXl5P8xq2WpUTP92u25zg=="]); + } + + #[test] + fn test_field_poly_powmod_k1() { + let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==",]); + let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let modulus: Polynomial = Polynomial::from_c_array(&json2); + + let result = element1.pow_mod(1, modulus); + + eprintln!("Result is: {:02X?}", result); + assert_eq!(result.to_c_array(), vec!["JAAAAAAAAAAAAAAAAAAAAA=="]); + } + + #[test] + fn test_field_poly_powmod_k0_special() { + let json1 = json!(["NeverGonnaGiveYouUpAAA=="]); + let json2 = json!(["NeverGonnaGiveYouUpAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let modulus: Polynomial = Polynomial::from_c_array(&json2); + + let result = element1.pow_mod(0, modulus); + + eprintln!("Result is: {:02X?}", result); + + assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); + } + + #[test] + fn test_field_poly_powmod_k0() { + let json1 = json!(["JAAAAAAAAAAAAAAAAAAAAA==",]); + let json2 = json!(["KryptoanalyseAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let modulus: Polynomial = Polynomial::from_c_array(&json2); + + let result = element1.pow_mod(0, modulus); + + eprintln!("Result is: {:02X?}", result); + assert_eq!(result.to_c_array(), vec!["gAAAAAAAAAAAAAAAAAAAAA=="]); + } + + #[test] + fn test_field_pow_mod_10mill() { + let json1 = json!([ + "JAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let json2 = json!(["KryptoanalyseAAAAAAAAA==", "DHBWMannheimAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + let modulus: Polynomial = Polynomial::from_c_array(&json2); + + let result = element1.pow_mod(10000000, modulus); + + assert!(!result.is_zero()) + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_poly_monic() { + let json1 = json!([ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ]); + let expected = json!([ + "edY47onJ4MtCENDTHG/sZw==", + "oaXjCKnceBIxSavZ9eFT8w==", + "1Ial5rAJGOucIdUe3zh5bw==", + "gAAAAAAAAAAAAAAAAAAAAA==" + ]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.monic(); + + assert_eq!(json!(result.to_c_array()), expected); + //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } } From 5e50ef6091f4c3a72586432757dfc063f701201e Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 22 Nov 2024 15:28:36 +0100 Subject: [PATCH 27/79] refactor: apply cargo recommended cleanups --- src/tasks/tasks01/pad_oracle.rs | 1 - src/utils/field.rs | 6 ++---- src/utils/poly.rs | 4 +--- 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/src/tasks/tasks01/pad_oracle.rs b/src/tasks/tasks01/pad_oracle.rs index 90e4295..4286e37 100644 --- a/src/tasks/tasks01/pad_oracle.rs +++ b/src/tasks/tasks01/pad_oracle.rs @@ -3,7 +3,6 @@ use base64::prelude::*; use serde_json::Value; use std::io::prelude::*; use std::net::TcpStream; -use std::time::Instant; use std::usize; pub fn padding_oracle(args: &Value) -> Result> { diff --git a/src/utils/field.rs b/src/utils/field.rs index 6894023..82234da 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -1,14 +1,12 @@ use base64::prelude::*; -use std::{str::FromStr, u128, u8, usize}; +use std::{u128, u8, usize}; use std::{ cmp::Ordering, - mem::discriminant, - ops::{Add, BitXor, Div, Mul, Sub}, + ops::{Add, BitXor, Div, Mul}, }; use anyhow::{anyhow, Ok, Result}; -use serde_json::Value; use super::poly::polynomial_2_block; use super::{ diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 99def36..bb05366 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -4,15 +4,13 @@ use std::{str::FromStr, u128, u8, usize}; use std::{ cmp::Ordering, - mem::discriminant, - ops::{Add, BitXor, Div, Mul, Sub}, + ops::{Add, Div, Mul}, }; use anyhow::{anyhow, Ok, Result}; use serde_json::Value; use super::field::FieldElement; -use super::math::{reverse_bits_in_bytevec, xor_bytes}; #[derive(Debug, serde::Serialize)] pub struct Polynomial { From 6391912bc4fdb9bb67c829c588249ecc8405f595 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 22 Nov 2024 15:47:59 +0100 Subject: [PATCH 28/79] feat: Add and improve poly monic function with testcases Make a polynomial monic by dividing all field elements with the leading element --- src/utils/poly.rs | 45 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/src/utils/poly.rs b/src/utils/poly.rs index bb05366..e624361 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -219,6 +219,22 @@ impl Polynomial { *fieldelement = fieldelement.clone() / divident.clone(); } + while !self.polynomial.is_empty() + && self + .polynomial + .last() + .unwrap() + .as_ref() + .iter() + .all(|&x| x == 0) + { + self.polynomial.pop(); + } + + if self.is_empty() { + self = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + } + self } } @@ -1047,7 +1063,6 @@ mod tests { let result = element1.pow_mod(10000000, modulus); assert!(!result.is_zero()) - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } #[test] @@ -1069,6 +1084,32 @@ mod tests { let result = element1.monic(); assert_eq!(json!(result.to_c_array()), expected); - //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); + } + + #[test] + fn test_poly_monic_poly_zero() { + let json1 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let expected = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.monic(); + + assert_eq!(json!(result.to_c_array()), expected); + } + + #[test] + fn test_poly_monic_poly_multiple_zero() { + let json1 = json!([ + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==" + ]); + let expected = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.monic(); + + assert_eq!(json!(result.to_c_array()), expected); } } From f75e7de73385f802267763cd50c032a83babaf08 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 22 Nov 2024 20:48:06 +0100 Subject: [PATCH 29/79] feat: Add polynomial square root algo --- src/utils/field.rs | 43 +++++++++++++++---- src/utils/poly.rs | 101 ++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 125 insertions(+), 19 deletions(-) diff --git a/src/utils/field.rs b/src/utils/field.rs index 82234da..184b2c6 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -36,21 +36,46 @@ impl FieldElement { BASE64_STANDARD.encode(&self.field_element) } - pub fn pow(&self, mut exponent: u128) -> FieldElement { + pub fn pow(mut self, mut exponent: u128) -> FieldElement { + let mut result: FieldElement = + FieldElement::new(polynomial_2_block(vec![0], "gcm").unwrap()); + + if exponent == 1 { + eprintln!("special case 1: {:02X?}", self.clone()); + + return self; + } + if exponent == 0 { - // Return polynomial with coefficient 1 - return FieldElement::new(vec![1]); + let result = FieldElement::new(polynomial_2_block(vec![0], "gcm").unwrap()); + + eprintln!("Returned value is: {:02X?}", result); + return result; } - let base = self.clone(); - let mut result = base.clone(); - exponent -= 1; // Subtract 1 because we already set result to base - + //eprintln!("Initial result: {:?}", result); while exponent > 0 { - result = result * base.clone(); - exponent -= 1; + //eprintln!("Current exponent: {:02X}", exponent); + if exponent & 1 == 1 { + let temp = &self * &result; + eprintln!("Mult"); + eprintln!("After mod: {:?}", temp); + + result = temp + } + let temp_square = &self * &self; + eprintln!("Square"); + + eprintln!("After squaring: {:?}", temp_square); + self = temp_square; + //eprintln!("After mod: {:?}", self); + exponent >>= 1; } + eprintln!("result in powmod before reduction: {:02X?}", result); + + eprintln!("result in powmod after reduction: {:02X?}", result); + result } diff --git a/src/utils/poly.rs b/src/utils/poly.rs index e624361..642be5c 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -56,19 +56,63 @@ impl Polynomial { output } - pub fn pow(&self, mut exponent: u128) -> Polynomial { - if exponent == 0 { - return Polynomial::new(vec![FieldElement::new( - polynomial_2_block(vec![0], "gcm").unwrap(), - )]); + pub fn pow(mut self, mut exponent: u128) -> Polynomial { + let mut result: Polynomial = Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![0], "gcm").unwrap(), + )]); + + if exponent == 1 { + eprintln!("special case 1: {:02X?}", self.clone()); + + return self; } - let base = self.clone(); - let mut result = base.clone(); - exponent -= 1; + if exponent == 0 { + let result = Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![0], "gcm").unwrap(), + )]); + + eprintln!("Returned value is: {:02X?}", result); + return result; + } + + //eprintln!("Initial result: {:?}", result); while exponent > 0 { - result = result * base.clone(); - exponent -= 1; + //eprintln!("Current exponent: {:02X}", exponent); + if exponent & 1 == 1 { + let temp = &self * &result; + eprintln!("Mult"); + eprintln!("After mod: {:?}", temp); + + result = temp + } + let temp_square = &self * &self; + eprintln!("Square"); + + eprintln!("After squaring: {:?}", temp_square); + self = temp_square; + //eprintln!("After mod: {:?}", self); + exponent >>= 1; + } + + eprintln!("result in powmod before reduction: {:02X?}", result); + + while !result.polynomial.is_empty() + && result + .polynomial + .last() + .unwrap() + .as_ref() + .iter() + .all(|&x| x == 0) + { + result.polynomial.pop(); + } + + eprintln!("result in powmod after reduction: {:02X?}", result); + + if result.is_empty() { + result = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); } result @@ -237,6 +281,18 @@ impl Polynomial { self } + + fn sqrt(self) -> Self { + let mut result = vec![]; + + for (position, element) in self.polynomial.iter().enumerate() { + if position % 2 == 0 { + result.push(element.clone().pow(2u128.pow(127))); + } + } + + Polynomial::new(result) + } } impl Clone for Polynomial { @@ -1112,4 +1168,29 @@ mod tests { assert_eq!(json!(result.to_c_array()), expected); } + + #[test] + fn test_poly_poly_sqrt() { + let json1 = json!([ + "5TxUxLHO1lHE/rSFquKIAg==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "0DEUJYdHlmd4X7nzzIdcCA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "PKUa1+JHTxHE8y3LbuKIIA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "Ds96KiAKKoigKoiKiiKAiA==" + ]); + let expected = json!([ + "NeverGonnaGiveYouUpAAA==", + "NeverGonnaLetYouDownAA==", + "NeverGonnaRunAroundAAA==", + "AndDesertYouAAAAAAAAAA==" + ]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + eprintln!("Starting poly sqrt"); + + let result = element1.sqrt(); + + assert_eq!(json!(result.to_c_array()), expected); + } } From 5bb9bcebff5f649818da9ef1ad514c411d16351d Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 22 Nov 2024 21:16:53 +0100 Subject: [PATCH 30/79] feat: ready test runner for monic and sqrt tasks --- src/tasks/mod.rs | 15 +++++++++++++- src/tasks/tasks01/pfmath.rs | 16 +++++++++++++++ src/utils/field.rs | 12 +++++------ src/utils/poly.rs | 40 ++++++++++++++++--------------------- 4 files changed, 53 insertions(+), 30 deletions(-) diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index 9d24f8b..87ca189 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -9,7 +9,8 @@ use tasks01::{ gfmul::gfmul_task, pad_oracle::padding_oracle, pfmath::{ - gfdiv, gfpoly_add, gfpoly_divmod, gfpoly_mul, gfpoly_pow, gfpoly_powmod, gfpoly_sort, + gfdiv, gfpoly_add, gfpoly_divmod, gfpoly_make_monic, gfpoly_mul, gfpoly_pow, gfpoly_powmod, + gfpoly_sort, gfpoly_sqrt, }, poly2block::poly2block, sea128::sea128, @@ -132,6 +133,18 @@ pub fn task_deploy(testcase: &Testcase) -> Result { Ok(json) } + "gfpoly_make_monic" => { + let result = gfpoly_make_monic(args)?; + let json = json!({"S" : result.to_c_array()}); + + Ok(json) + } + "gfpoly_sqrt" => { + let result = gfpoly_sqrt(args)?; + let json = json!({"S" : result.to_c_array()}); + + Ok(json) + } _ => Err(anyhow!( "Fatal. No compatible action found. Json data was {:?}. Arguments were; {:?}", diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index 9fb7014..9a9859c 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -81,6 +81,22 @@ pub fn gfpoly_sort(args: &Value) -> Result> { Ok(polys) } +pub fn gfpoly_make_monic(args: &Value) -> Result { + let mut poly_a = Polynomial::from_c_array(&args["A"].clone()); + + poly_a.monic(); + + Ok(poly_a) +} + +pub fn gfpoly_sqrt(args: &Value) -> Result { + let poly_a = Polynomial::from_c_array(&args["Q"].clone()); + + let result = poly_a.sqrt(); + + Ok(result) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/utils/field.rs b/src/utils/field.rs index 184b2c6..28f7bb5 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -58,23 +58,23 @@ impl FieldElement { //eprintln!("Current exponent: {:02X}", exponent); if exponent & 1 == 1 { let temp = &self * &result; - eprintln!("Mult"); - eprintln!("After mod: {:?}", temp); + //eprintln!("Mult"); + //eprintln!("After mod: {:?}", temp); result = temp } let temp_square = &self * &self; - eprintln!("Square"); + // eprintln!("Square"); - eprintln!("After squaring: {:?}", temp_square); + // eprintln!("After squaring: {:?}", temp_square); self = temp_square; //eprintln!("After mod: {:?}", self); exponent >>= 1; } - eprintln!("result in powmod before reduction: {:02X?}", result); + // eprintln!("result in powmod before reduction: {:02X?}", result); - eprintln!("result in powmod after reduction: {:02X?}", result); + // eprintln!("result in powmod after reduction: {:02X?}", result); result } diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 642be5c..fa4b343 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -81,21 +81,21 @@ impl Polynomial { //eprintln!("Current exponent: {:02X}", exponent); if exponent & 1 == 1 { let temp = &self * &result; - eprintln!("Mult"); - eprintln!("After mod: {:?}", temp); + //eprintln!("Mult"); + //eprintln!("After mod: {:?}", temp); result = temp } let temp_square = &self * &self; - eprintln!("Square"); + //eprintln!("Square"); - eprintln!("After squaring: {:?}", temp_square); + //eprintln!("After squaring: {:?}", temp_square); self = temp_square; //eprintln!("After mod: {:?}", self); exponent >>= 1; } - eprintln!("result in powmod before reduction: {:02X?}", result); + //eprintln!("result in powmod before reduction: {:02X?}", result); while !result.polynomial.is_empty() && result @@ -109,7 +109,7 @@ impl Polynomial { result.polynomial.pop(); } - eprintln!("result in powmod after reduction: {:02X?}", result); + //eprintln!("result in powmod after reduction: {:02X?}", result); if result.is_empty() { result = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); @@ -256,7 +256,7 @@ impl Polynomial { true } - fn monic(mut self) -> Self { + pub fn monic(&mut self) { let divident = self.polynomial.last().unwrap().clone(); for fieldelement in &mut self.polynomial.iter_mut() { @@ -274,15 +274,9 @@ impl Polynomial { { self.polynomial.pop(); } - - if self.is_empty() { - self = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); - } - - self } - fn sqrt(self) -> Self { + pub fn sqrt(self) -> Self { let mut result = vec![]; for (position, element) in self.polynomial.iter().enumerate() { @@ -1135,22 +1129,22 @@ mod tests { "1Ial5rAJGOucIdUe3zh5bw==", "gAAAAAAAAAAAAAAAAAAAAA==" ]); - let element1: Polynomial = Polynomial::from_c_array(&json1); + let mut element1: Polynomial = Polynomial::from_c_array(&json1); - let result = element1.monic(); + element1.monic(); - assert_eq!(json!(result.to_c_array()), expected); + assert_eq!(json!(element1.to_c_array()), expected); } #[test] fn test_poly_monic_poly_zero() { let json1 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); let expected = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); + let mut element1: Polynomial = Polynomial::from_c_array(&json1); - let result = element1.monic(); + element1.monic(); - assert_eq!(json!(result.to_c_array()), expected); + assert_eq!(json!(element1.to_c_array()), expected); } #[test] @@ -1162,11 +1156,11 @@ mod tests { "AAAAAAAAAAAAAAAAAAAAAA==" ]); let expected = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); - let element1: Polynomial = Polynomial::from_c_array(&json1); + let mut element1: Polynomial = Polynomial::from_c_array(&json1); - let result = element1.monic(); + element1.monic(); - assert_eq!(json!(result.to_c_array()), expected); + assert_eq!(json!(element1.to_c_array()), expected); } #[test] From 1290adcd9b7b699a0d2b06dece06e8dcc285024d Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 22 Nov 2024 21:34:01 +0100 Subject: [PATCH 31/79] fix: Fix error in calling of monic function --- src/tasks/tasks01/pfmath.rs | 6 +++--- src/utils/poly.rs | 25 +++++++++++++++---------- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index 9a9859c..b1e7516 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -82,11 +82,11 @@ pub fn gfpoly_sort(args: &Value) -> Result> { } pub fn gfpoly_make_monic(args: &Value) -> Result { - let mut poly_a = Polynomial::from_c_array(&args["A"].clone()); + let poly_a = Polynomial::from_c_array(&args["A"].clone()); - poly_a.monic(); + let result = poly_a.monic(); - Ok(poly_a) + Ok(result) } pub fn gfpoly_sqrt(args: &Value) -> Result { diff --git a/src/utils/poly.rs b/src/utils/poly.rs index fa4b343..f56abf4 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -256,7 +256,7 @@ impl Polynomial { true } - pub fn monic(&mut self) { + pub fn monic(mut self) -> Self { let divident = self.polynomial.last().unwrap().clone(); for fieldelement in &mut self.polynomial.iter_mut() { @@ -274,6 +274,11 @@ impl Polynomial { { self.polynomial.pop(); } + + if self.is_empty() { + self = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + } + self } pub fn sqrt(self) -> Self { @@ -1129,22 +1134,22 @@ mod tests { "1Ial5rAJGOucIdUe3zh5bw==", "gAAAAAAAAAAAAAAAAAAAAA==" ]); - let mut element1: Polynomial = Polynomial::from_c_array(&json1); + let element1: Polynomial = Polynomial::from_c_array(&json1); - element1.monic(); + let result = element1.monic(); - assert_eq!(json!(element1.to_c_array()), expected); + assert_eq!(json!(result.to_c_array()), expected); } #[test] fn test_poly_monic_poly_zero() { let json1 = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); let expected = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); - let mut element1: Polynomial = Polynomial::from_c_array(&json1); + let element1: Polynomial = Polynomial::from_c_array(&json1); - element1.monic(); + let result = element1.monic(); - assert_eq!(json!(element1.to_c_array()), expected); + assert_eq!(json!(result.to_c_array()), expected); } #[test] @@ -1156,11 +1161,11 @@ mod tests { "AAAAAAAAAAAAAAAAAAAAAA==" ]); let expected = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); - let mut element1: Polynomial = Polynomial::from_c_array(&json1); + let element1: Polynomial = Polynomial::from_c_array(&json1); - element1.monic(); + let result = element1.monic(); - assert_eq!(json!(element1.to_c_array()), expected); + assert_eq!(json!(result.to_c_array()), expected); } #[test] From b595276143b311e1b7afb90a9ab500dde3bc202b Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 23 Nov 2024 09:44:47 +0100 Subject: [PATCH 32/79] fix: Fix incorrect naming of response json object for monic --- src/tasks/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index 87ca189..2cc97b7 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -135,7 +135,7 @@ pub fn task_deploy(testcase: &Testcase) -> Result { } "gfpoly_make_monic" => { let result = gfpoly_make_monic(args)?; - let json = json!({"S" : result.to_c_array()}); + let json = json!({"A*" : result.to_c_array()}); Ok(json) } From 4b1bca8ee023824e45ea17c1bf5f279d110c0551 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 23 Nov 2024 10:17:08 +0100 Subject: [PATCH 33/79] feat: add function for polynomial differentiation --- src/tasks/mod.rs | 10 +++++-- src/tasks/tasks01/pfmath.rs | 8 ++++++ src/utils/field.rs | 4 +++ src/utils/poly.rs | 54 +++++++++++++++++++++++-------------- test_json/sandbox.json | 15 +++++++++++ 5 files changed, 69 insertions(+), 22 deletions(-) create mode 100644 test_json/sandbox.json diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index 2cc97b7..e72b502 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -9,8 +9,8 @@ use tasks01::{ gfmul::gfmul_task, pad_oracle::padding_oracle, pfmath::{ - gfdiv, gfpoly_add, gfpoly_divmod, gfpoly_make_monic, gfpoly_mul, gfpoly_pow, gfpoly_powmod, - gfpoly_sort, gfpoly_sqrt, + gfdiv, gfpoly_add, gfpoly_diff, gfpoly_divmod, gfpoly_make_monic, gfpoly_mul, gfpoly_pow, + gfpoly_powmod, gfpoly_sort, gfpoly_sqrt, }, poly2block::poly2block, sea128::sea128, @@ -145,6 +145,12 @@ pub fn task_deploy(testcase: &Testcase) -> Result { Ok(json) } + "gfpoly_diff" => { + let result = gfpoly_diff(args)?; + let json = json!({"F'" : result.to_c_array()}); + + Ok(json) + } _ => Err(anyhow!( "Fatal. No compatible action found. Json data was {:?}. Arguments were; {:?}", diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index b1e7516..3da23fc 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -97,6 +97,14 @@ pub fn gfpoly_sqrt(args: &Value) -> Result { Ok(result) } +pub fn gfpoly_diff(args: &Value) -> Result { + let poly_f = Polynomial::from_c_array(&args["F"].clone()); + + let result = poly_f.diff(); + + Ok(result) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/utils/field.rs b/src/utils/field.rs index 28f7bb5..ce0b8a4 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -24,6 +24,10 @@ impl FieldElement { 87, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 01, ]; + pub fn zero(self) -> Self { + FieldElement::new(vec![0]) + } + pub const fn new(field_element: Vec) -> Self { Self { field_element } } diff --git a/src/utils/poly.rs b/src/utils/poly.rs index f56abf4..8dc0105 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -292,6 +292,19 @@ impl Polynomial { Polynomial::new(result) } + + pub fn diff(mut self) -> Self { + // Pop first element + self.polynomial.remove(0); + + for (position, element) in self.polynomial.iter_mut().enumerate() { + if position % 2 == 1 { + *element = FieldElement::new(vec![0; 16]); + } + } + + self + } } impl Clone for Polynomial { @@ -645,26 +658,6 @@ mod tests { // Note this useful idiom: importing names from outer (for mod tests) scope. use super::*; - /* - * TODO: Consider removing - #[test] - fn coefficients_to_byte_arr_xex_test1() { - let coefficients: Vec = vec![0]; - let byte_array = vec![ - 01, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, - ]; - assert_eq!(coefficients_to_byte_arr_xex(coefficients), byte_array) - } - - #[test] - fn coefficients_to_byte_arr_xex_test2() { - let coefficients: Vec = vec![127, 12, 9, 0]; - let byte_array = vec![ - 01, 12, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 80, - ]; - assert_eq!(coefficients_to_byte_arr_xex(coefficients), byte_array) - } - */ #[test] fn byte_indices_0x01() { let byte: u8 = 0x01; @@ -1192,4 +1185,25 @@ mod tests { assert_eq!(json!(result.to_c_array()), expected); } + + #[test] + fn test_poly_diff() { + let json1 = json!([ + "IJustWannaTellYouAAAAA==", + "HowImFeelingAAAAAAAAAA==", + "GottaMakeYouAAAAAAAAAA==", + "UnderstaaaaaaaaaaaaanQ==" + ]); + let expected = json!([ + "HowImFeelingAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "UnderstaaaaaaaaaaaaanQ==" + ]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + eprintln!("Starting poly sqrt"); + + let result = element1.diff(); + + assert_eq!(json!(result.to_c_array()), expected); + } } diff --git a/test_json/sandbox.json b/test_json/sandbox.json new file mode 100644 index 0000000..8a670d3 --- /dev/null +++ b/test_json/sandbox.json @@ -0,0 +1,15 @@ +{ + "testcases": { + "sandbox": { + "action": "gfpoly_diff", + "arguments": { + "F": [ + "IJustWannaTellYouAAAAA==", + "HowImFeelingAAAAAAAAAA==", + "GottaMakeYouAAAAAAAAAA==", + "UnderstaaaaaaaaaaaaanQ==" + ] + } + } + } +} From 8be8dc7a5464842dae3cbb90cbb295a0f3f40d66 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 23 Nov 2024 10:26:32 +0100 Subject: [PATCH 34/79] feat: Add edge case handling for poly diff Add handling for cases in which poly is of degree 0 or 1 --- src/utils/poly.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 8dc0105..8c5c51a 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -295,9 +295,17 @@ impl Polynomial { pub fn diff(mut self) -> Self { // Pop first element - self.polynomial.remove(0); + // Check if the polynomial is 1 or less. In this case, output would be [] without check + // Output should be [0; 16] however + if self.polynomial.len() > 1 { + self.polynomial.remove(0); + } else { + return Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + } for (position, element) in self.polynomial.iter_mut().enumerate() { + // Set all uneven degrees to 0, as they were the even degrees before + // As we are in GF128, this means they become 0 after mul with even number if position % 2 == 1 { *element = FieldElement::new(vec![0; 16]); } @@ -1206,4 +1214,16 @@ mod tests { assert_eq!(json!(result.to_c_array()), expected); } + + #[test] + fn test_poly_diff_len1() { + let json1 = json!(["IJustWannaTellYouAAAAA==",]); + let expected = json!(["AAAAAAAAAAAAAAAAAAAAAA==",]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + eprintln!("Starting poly sqrt"); + + let result = element1.diff(); + + assert_eq!(json!(result.to_c_array()), expected); + } } From 1a2910b28fcd8ff92d9d685ba085baa40c311add Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 23 Nov 2024 11:42:05 +0100 Subject: [PATCH 35/79] fix: Add removal of leading zeros in poly diff --- src/utils/poly.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 8c5c51a..f999351 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -311,6 +311,22 @@ impl Polynomial { } } + while !self.polynomial.is_empty() + && self + .polynomial + .last() + .unwrap() + .as_ref() + .iter() + .all(|&x| x == 0) + { + self.polynomial.pop(); + } + + if self.is_empty() { + self = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + } + self } } @@ -1226,4 +1242,22 @@ mod tests { assert_eq!(json!(result.to_c_array()), expected); } + + #[test] + fn test_poly_diff_multi_zero() { + let json1 = json!([ + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + ]); + let expected = json!(["AAAAAAAAAAAAAAAAAAAAAA==",]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + eprintln!("Starting poly sqrt"); + + let result = element1.diff(); + + assert_eq!(json!(result.to_c_array()), expected); + } } From 0b18ba1bffa822349678c77801d0bb21175aeea1 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 23 Nov 2024 12:31:27 +0100 Subject: [PATCH 36/79] feat: Adding gcd implementation --- src/tasks/mod.rs | 10 ++++-- src/tasks/tasks01/pfmath.rs | 14 ++++++++- src/utils/poly.rs | 62 +++++++++++++++++++++++++++++++++++++ test_json/sandbox.json | 25 +++++++++++---- 4 files changed, 102 insertions(+), 9 deletions(-) diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index e72b502..0613d93 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -9,8 +9,8 @@ use tasks01::{ gfmul::gfmul_task, pad_oracle::padding_oracle, pfmath::{ - gfdiv, gfpoly_add, gfpoly_diff, gfpoly_divmod, gfpoly_make_monic, gfpoly_mul, gfpoly_pow, - gfpoly_powmod, gfpoly_sort, gfpoly_sqrt, + gfdiv, gfpoly_add, gfpoly_diff, gfpoly_divmod, gfpoly_gcd, gfpoly_make_monic, gfpoly_mul, + gfpoly_pow, gfpoly_powmod, gfpoly_sort, gfpoly_sqrt, }, poly2block::poly2block, sea128::sea128, @@ -151,6 +151,12 @@ pub fn task_deploy(testcase: &Testcase) -> Result { Ok(json) } + "gfpoly_gcd" => { + let result = gfpoly_gcd(args)?; + let json = json!({"G" : result.to_c_array()}); + + Ok(json) + } _ => Err(anyhow!( "Fatal. No compatible action found. Json data was {:?}. Arguments were; {:?}", diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index 3da23fc..ea60e78 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -2,7 +2,10 @@ use anyhow::Result; use base64::{prelude::BASE64_STANDARD, Engine}; use serde_json::Value; -use crate::utils::{field::FieldElement, poly::Polynomial}; +use crate::utils::{ + field::FieldElement, + poly::{gcd, Polynomial}, +}; pub fn gfpoly_add(args: &Value) -> Result { let poly_a = Polynomial::from_c_array(&args["A"].clone()); @@ -105,6 +108,15 @@ pub fn gfpoly_diff(args: &Value) -> Result { Ok(result) } +pub fn gfpoly_gcd(args: &Value) -> Result { + let poly_a = Polynomial::from_c_array(&args["A"].clone()); + let poly_b = Polynomial::from_c_array(&args["B"].clone()); + + let result = gcd(poly_a, poly_b); + + Ok(result) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 8c5c51a..5b5f737 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -467,6 +467,14 @@ impl Ord for Polynomial { } } +pub fn gcd(a: Polynomial, b: Polynomial) -> Polynomial { + if a.is_zero() { + return b; + } + + return gcd(b.div(&a).1.monic(), a); +} + pub fn sort_polynomial_array(mut polys: Vec) -> Result> { // Algorithm to sort polynomials // First sorting round @@ -1226,4 +1234,58 @@ mod tests { assert_eq!(json!(result.to_c_array()), expected); } + + #[test] + fn test_poly_diff_multi_zero() { + let json1 = json!([ + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + ]); + let expected = json!(["AAAAAAAAAAAAAAAAAAAAAA==",]); + let element1: Polynomial = Polynomial::from_c_array(&json1); + + let result = element1.diff(); + + assert_eq!(json!(result.to_c_array()), expected); + } + + #[test] + fn test_poly_gcd() { + let a = json!([ + "DNWpXnnY24XecPa7a8vrEA==", + "I8uYpCbsiPaVvUznuv1IcA==", + "wsbiU432ARWuO93He3vbvA==", + "zp0g3o8iNz7Y+8oUxw1vJw==", + "J0GekE3uendpN6WUAuJ4AA==", + "wACd0e6u1ii4AAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ]); + let b = json!([ + "I20VjJmlSnRSe88gaDiLRQ==", + "0Cw5HxJm/pfybJoQDf7/4w==", + "8ByrMMf+vVj5r3YXUNCJ1g==", + "rEU/f2UZRXqmZ6V7EPKfBA==", + "LfdALhvCrdhhGZWl9l9DSg==", + "KSUKhN0n6/DZmHPozd1prw==", + "DQrRkuA9Zx279wAAAAAAAA==", + "AhCEAAAAAAAAAAAAAAAAAA==" + ]); + let expected = json!([ + "NeverGonnaMakeYouCryAA==", + "NeverGonnaSayGoodbyeAA==", + "NeverGonnaTellALieAAAA==", + "AndHurtYouAAAAAAAAAAAA==", + "gAAAAAAAAAAAAAAAAAAAAA==" + ]); + + let a: Polynomial = Polynomial::from_c_array(&a); + let b: Polynomial = Polynomial::from_c_array(&b); + + let result = gcd(a.monic(), b.monic()); + + assert_eq!(json!(result.to_c_array()), expected); + } } diff --git a/test_json/sandbox.json b/test_json/sandbox.json index 8a670d3..48d59ed 100644 --- a/test_json/sandbox.json +++ b/test_json/sandbox.json @@ -1,13 +1,26 @@ { "testcases": { "sandbox": { - "action": "gfpoly_diff", + "action": "gfpoly_gcd", "arguments": { - "F": [ - "IJustWannaTellYouAAAAA==", - "HowImFeelingAAAAAAAAAA==", - "GottaMakeYouAAAAAAAAAA==", - "UnderstaaaaaaaaaaaaanQ==" + "A": [ + "DNWpXnnY24XecPa7a8vrEA==", + "I8uYpCbsiPaVvUznuv1IcA==", + "wsbiU432ARWuO93He3vbvA==", + "zp0g3o8iNz7Y+8oUxw1vJw==", + "J0GekE3uendpN6WUAuJ4AA==", + "wACd0e6u1ii4AAAAAAAAAA==", + "ACAAAAAAAAAAAAAAAAAAAA==" + ], + "B": [ + "I20VjJmlSnRSe88gaDiLRQ==", + "0Cw5HxJm/pfybJoQDf7/4w==", + "8ByrMMf+vVj5r3YXUNCJ1g==", + "rEU/f2UZRXqmZ6V7EPKfBA==", + "LfdALhvCrdhhGZWl9l9DSg==", + "KSUKhN0n6/DZmHPozd1prw==", + "DQrRkuA9Zx279wAAAAAAAA==", + "AhCEAAAAAAAAAAAAAAAAAA==" ] } } From 69a2026c843a278c2a1b2f48e0aced63ba0f89de Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 23 Nov 2024 13:33:51 +0100 Subject: [PATCH 37/79] fix: Make all polynomials monic in task fn --- src/tasks/tasks01/pfmath.rs | 2 +- src/utils/poly.rs | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index ea60e78..4fc686e 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -112,7 +112,7 @@ pub fn gfpoly_gcd(args: &Value) -> Result { let poly_a = Polynomial::from_c_array(&args["A"].clone()); let poly_b = Polynomial::from_c_array(&args["B"].clone()); - let result = gcd(poly_a, poly_b); + let result = gcd(poly_a.monic(), poly_b.monic()); Ok(result) } diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 0be3b89..b820e01 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -1267,7 +1267,7 @@ mod tests { assert_eq!(json!(result.to_c_array()), expected); } - + #[test] fn test_poly_gcd() { let a = json!([ @@ -1304,4 +1304,18 @@ mod tests { assert_eq!(json!(result.to_c_array()), expected); } + + #[test] + fn test_poly_gcd_zero() { + let a = json!(["AAAAAAAAAAAAAAAAAAAAAA==",]); + let b = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + let expected = json!(["AAAAAAAAAAAAAAAAAAAAAA=="]); + + let a: Polynomial = Polynomial::from_c_array(&a); + let b: Polynomial = Polynomial::from_c_array(&b); + + let result = gcd(a.monic(), b.monic()); + + assert_eq!(json!(result.to_c_array()), expected); + } } From 17bade8a6241163798bbd138e857f03c51197183 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 23 Nov 2024 19:07:30 +0100 Subject: [PATCH 38/79] WIP: feat: Initial implementation of ssf. Sort missinf --- src/tasks/tasks01/pfmath.rs | 2 +- src/utils/dff.rs | 0 src/utils/edf.rs | 0 src/utils/field.rs | 2 +- src/utils/mod.rs | 3 ++ src/utils/poly.rs | 20 ++++---- src/utils/sff.rs | 91 +++++++++++++++++++++++++++++++++++++ 7 files changed, 108 insertions(+), 10 deletions(-) create mode 100644 src/utils/dff.rs create mode 100644 src/utils/edf.rs create mode 100644 src/utils/sff.rs diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index 4fc686e..182e17d 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -112,7 +112,7 @@ pub fn gfpoly_gcd(args: &Value) -> Result { let poly_a = Polynomial::from_c_array(&args["A"].clone()); let poly_b = Polynomial::from_c_array(&args["B"].clone()); - let result = gcd(poly_a.monic(), poly_b.monic()); + let result = gcd(&poly_a.monic(), &poly_b.monic()); Ok(result) } diff --git a/src/utils/dff.rs b/src/utils/dff.rs new file mode 100644 index 0000000..e69de29 diff --git a/src/utils/edf.rs b/src/utils/edf.rs new file mode 100644 index 0000000..e69de29 diff --git a/src/utils/field.rs b/src/utils/field.rs index ce0b8a4..626d40d 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -14,7 +14,7 @@ use super::{ poly::gfmul, }; -#[derive(Debug, serde::Serialize)] +#[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct FieldElement { field_element: Vec, } diff --git a/src/utils/mod.rs b/src/utils/mod.rs index 298415b..35fb781 100644 --- a/src/utils/mod.rs +++ b/src/utils/mod.rs @@ -1,6 +1,9 @@ pub mod ciphers; +pub mod dff; +pub mod edf; pub mod field; pub mod math; pub mod net; pub mod parse; pub mod poly; +pub mod sff; diff --git a/src/utils/poly.rs b/src/utils/poly.rs index b820e01..b4a1060 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -12,7 +12,7 @@ use serde_json::Value; use super::field::FieldElement; -#[derive(Debug, serde::Serialize)] +#[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct Polynomial { polynomial: Vec, } @@ -178,13 +178,16 @@ impl Polynomial { } // Returns (quotient, remainder) - pub fn div(self, rhs: &Self) -> (Self, Self) { + pub fn div(&self, rhs: &Self) -> (Self, Self) { // Div by zero check ommitted since data is guaranteed to be non 0 eprintln!("{:?}, {:?}", self.polynomial.len(), rhs.polynomial.len()); if self.polynomial.len() < rhs.polynomial.len() { - return (Polynomial::new(vec![FieldElement::new(vec![0; 16])]), self); + return ( + Polynomial::new(vec![FieldElement::new(vec![0; 16])]), + self.clone(), + ); } let mut remainder = self.clone(); @@ -483,12 +486,13 @@ impl Ord for Polynomial { } } -pub fn gcd(a: Polynomial, b: Polynomial) -> Polynomial { +pub fn gcd(a: &Polynomial, b: &Polynomial) -> Polynomial { if a.is_zero() { - return b; + return b.clone(); } - return gcd(b.div(&a).1.monic(), a); + let monic_b = b.div(&a).1.monic(); + return gcd(&monic_b, a); } pub fn sort_polynomial_array(mut polys: Vec) -> Result> { @@ -1300,7 +1304,7 @@ mod tests { let a: Polynomial = Polynomial::from_c_array(&a); let b: Polynomial = Polynomial::from_c_array(&b); - let result = gcd(a.monic(), b.monic()); + let result = gcd(&a.monic(), &b.monic()); assert_eq!(json!(result.to_c_array()), expected); } @@ -1314,7 +1318,7 @@ mod tests { let a: Polynomial = Polynomial::from_c_array(&a); let b: Polynomial = Polynomial::from_c_array(&b); - let result = gcd(a.monic(), b.monic()); + let result = gcd(&a.monic(), &b.monic()); assert_eq!(json!(result.to_c_array()), expected); } diff --git a/src/utils/sff.rs b/src/utils/sff.rs new file mode 100644 index 0000000..fc0705a --- /dev/null +++ b/src/utils/sff.rs @@ -0,0 +1,91 @@ +use serde::{Deserialize, Serialize}; + +use crate::utils::{ + field::FieldElement, + poly::{gcd, polynomial_2_block}, +}; + +use super::poly::Polynomial; + +#[derive(Debug, Serialize, Deserialize)] +struct Factors { + factor: Vec, + exponent: u32, +} + +pub fn sff(mut f: Polynomial) -> Vec<(Polynomial, u32)> { + let mut c = gcd(&f, &f.clone().diff()); + f = f.div(&c).0; + let mut z: Vec<(Polynomial, u32)> = vec![]; + let mut e: u32 = 1; + + let one_element = Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![0], "gcm").unwrap(), + )]); + + while f != one_element { + let y = gcd(&f, &c); + if f != y { + z.push(((f.div(&y).0), e)); + } + + f = y.clone(); + c = c.div(&y).0; + e += 1; + } + + if c != one_element { + let r = sff(c.sqrt()); + for (f_star, e_star) in r { + z.push((f_star, 2 * e_star)); + } + } + + z +} + +#[cfg(test)] +mod tests { + + use serde_json::json; + // Note this useful idiom: importing names from outer (for mod tests) scope. + use super::*; + + #[test] + fn byte_indices_0x01() { + let json_f = json!([ + "vL77UwAAAAAAAAAAAAAAAA==", + "mEHchYAAAAAAAAAAAAAAAA==", + "9WJa0MAAAAAAAAAAAAAAAA==", + "akHfwWAAAAAAAAAAAAAAAA==", + "E12o/QAAAAAAAAAAAAAAAA==", + "vKJ/FgAAAAAAAAAAAAAAAA==", + "yctWwAAAAAAAAAAAAAAAAA==", + "c1BXYAAAAAAAAAAAAAAAAA==", + "o0AtAAAAAAAAAAAAAAAAAA==", + "AbP2AAAAAAAAAAAAAAAAAA==", + "k2YAAAAAAAAAAAAAAAAAAA==", + "vBYAAAAAAAAAAAAAAAAAAA==", + "dSAAAAAAAAAAAAAAAAAAAA==", + "69gAAAAAAAAAAAAAAAAAAA==", + "VkAAAAAAAAAAAAAAAAAAAA==", + "a4AAAAAAAAAAAAAAAAAAAA==", + "gAAAAAAAAAAAAAAAAAAAAA==" + ]); + let poly_f = Polynomial::from_c_array(&json_f); + + let factors = sff(poly_f); + let mut result: Vec = vec![]; + + for (factor, exponent) in factors { + result.push(Factors { + factor: factor.to_c_array(), + exponent, + }); + } + + println!("{:?}", result.sort()); + let bit_indices: Vec = vec![0]; + assert!(false) + } +} From 2d4f7a111033c23d6007144f928422d9db186256 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 23 Nov 2024 19:20:25 +0100 Subject: [PATCH 39/79] feat: sff working in testcase --- src/utils/sff.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/utils/sff.rs b/src/utils/sff.rs index fc0705a..04eb439 100644 --- a/src/utils/sff.rs +++ b/src/utils/sff.rs @@ -1,3 +1,5 @@ +use std::usize; + use serde::{Deserialize, Serialize}; use crate::utils::{ @@ -10,13 +12,13 @@ use super::poly::Polynomial; #[derive(Debug, Serialize, Deserialize)] struct Factors { factor: Vec, - exponent: u32, + exponent: usize, } -pub fn sff(mut f: Polynomial) -> Vec<(Polynomial, u32)> { +pub fn sff(mut f: Polynomial) -> Vec { let mut c = gcd(&f, &f.clone().diff()); f = f.div(&c).0; - let mut z: Vec<(Polynomial, u32)> = vec![]; + let mut z: Vec = vec![]; let mut e: u32 = 1; let one_element = Polynomial::new(vec![FieldElement::new( @@ -26,7 +28,7 @@ pub fn sff(mut f: Polynomial) -> Vec<(Polynomial, u32)> { while f != one_element { let y = gcd(&f, &c); if f != y { - z.push(((f.div(&y).0), e)); + z.push(f.div(&y).0); } f = y.clone(); @@ -36,8 +38,8 @@ pub fn sff(mut f: Polynomial) -> Vec<(Polynomial, u32)> { if c != one_element { let r = sff(c.sqrt()); - for (f_star, e_star) in r { - z.push((f_star, 2 * e_star)); + for f_star in r { + z.push(f_star); } } @@ -74,17 +76,19 @@ mod tests { ]); let poly_f = Polynomial::from_c_array(&json_f); - let factors = sff(poly_f); + let mut factors = sff(poly_f); + factors.sort(); + let mut result: Vec = vec![]; - for (factor, exponent) in factors { + for (exponent, factor) in factors.iter().enumerate() { result.push(Factors { - factor: factor.to_c_array(), - exponent, + factor: factor.clone().to_c_array(), + exponent: exponent + 1, }); } - println!("{:?}", result.sort()); + println!("{:?}", result); let bit_indices: Vec = vec![0]; assert!(false) } From 1c9948ac6210142416ef22800cbe43642efbcc46 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sun, 24 Nov 2024 14:07:37 +0100 Subject: [PATCH 40/79] fix: Change sff to use the exponent as a tuple again --- src/utils/sff.rs | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/src/utils/sff.rs b/src/utils/sff.rs index 04eb439..f2478b5 100644 --- a/src/utils/sff.rs +++ b/src/utils/sff.rs @@ -1,5 +1,3 @@ -use std::usize; - use serde::{Deserialize, Serialize}; use crate::utils::{ @@ -12,13 +10,13 @@ use super::poly::Polynomial; #[derive(Debug, Serialize, Deserialize)] struct Factors { factor: Vec, - exponent: usize, + exponent: u32, } -pub fn sff(mut f: Polynomial) -> Vec { +pub fn sff(mut f: Polynomial) -> Vec<(Polynomial, u32)> { let mut c = gcd(&f, &f.clone().diff()); f = f.div(&c).0; - let mut z: Vec = vec![]; + let mut z: Vec<(Polynomial, u32)> = vec![]; let mut e: u32 = 1; let one_element = Polynomial::new(vec![FieldElement::new( @@ -28,7 +26,7 @@ pub fn sff(mut f: Polynomial) -> Vec { while f != one_element { let y = gcd(&f, &c); if f != y { - z.push(f.div(&y).0); + z.push(((f.div(&y).0), e)); } f = y.clone(); @@ -38,8 +36,8 @@ pub fn sff(mut f: Polynomial) -> Vec { if c != one_element { let r = sff(c.sqrt()); - for f_star in r { - z.push(f_star); + for (f_star, e_star) in r { + z.push((f_star, 2 * e_star)); } } @@ -78,13 +76,12 @@ mod tests { let mut factors = sff(poly_f); factors.sort(); - let mut result: Vec = vec![]; - for (exponent, factor) in factors.iter().enumerate() { + for (factor, exponent) in factors { result.push(Factors { - factor: factor.clone().to_c_array(), - exponent: exponent + 1, + factor: factor.to_c_array(), + exponent, }); } From 6856420ff90e66a866d29e5019906f22bf335582 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Mon, 25 Nov 2024 14:19:41 +0100 Subject: [PATCH 41/79] feat: Add task runner for the sff task --- src/tasks/mod.rs | 10 ++++++++-- src/tasks/tasks01/pfmath.rs | 18 ++++++++++++++++++ src/utils/dff.rs | 10 ++++++++++ src/utils/poly.rs | 4 ++++ src/utils/sff.rs | 6 +++--- test_json/sandbox.json | 38 ++++++++++++++++++------------------- 6 files changed, 62 insertions(+), 24 deletions(-) diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index 0613d93..2c3a428 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -9,8 +9,8 @@ use tasks01::{ gfmul::gfmul_task, pad_oracle::padding_oracle, pfmath::{ - gfdiv, gfpoly_add, gfpoly_diff, gfpoly_divmod, gfpoly_gcd, gfpoly_make_monic, gfpoly_mul, - gfpoly_pow, gfpoly_powmod, gfpoly_sort, gfpoly_sqrt, + gfdiv, gfpoly_add, gfpoly_diff, gfpoly_divmod, gfpoly_factor_sff, gfpoly_gcd, + gfpoly_make_monic, gfpoly_mul, gfpoly_pow, gfpoly_powmod, gfpoly_sort, gfpoly_sqrt, }, poly2block::poly2block, sea128::sea128, @@ -157,6 +157,12 @@ pub fn task_deploy(testcase: &Testcase) -> Result { Ok(json) } + "gfpoly_factor_sff" => { + let result = gfpoly_factor_sff(args)?; + let json = json!({"factors" : result}); + + Ok(json) + } _ => Err(anyhow!( "Fatal. No compatible action found. Json data was {:?}. Arguments were; {:?}", diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index 182e17d..b9067cc 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -5,6 +5,7 @@ use serde_json::Value; use crate::utils::{ field::FieldElement, poly::{gcd, Polynomial}, + sff::{sff, Factors}, }; pub fn gfpoly_add(args: &Value) -> Result { @@ -117,6 +118,23 @@ pub fn gfpoly_gcd(args: &Value) -> Result { Ok(result) } +pub fn gfpoly_factor_sff(arsg: &Value) -> Result> { + let poly_f = Polynomial::from_c_array(&arsg["F"].clone()); + + let mut factors = sff(poly_f); + factors.sort(); + let mut result: Vec = vec![]; + + for (factor, exponent) in factors { + result.push(Factors { + factor: factor.to_c_array(), + exponent, + }); + } + + Ok(result) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/utils/dff.rs b/src/utils/dff.rs index e69de29..575d9de 100644 --- a/src/utils/dff.rs +++ b/src/utils/dff.rs @@ -0,0 +1,10 @@ +use super::poly::Polynomial; + +pub fn dff(f: Polynomial) { + let q = 2u128.pow(128); + let z: Vec<(Polynomial, u32)> = vec![]; + let d = 1; + let f_start = f.clone(); + + while f_start.degree() >= 2 * d {} +} diff --git a/src/utils/poly.rs b/src/utils/poly.rs index b4a1060..786c67a 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -22,6 +22,10 @@ impl Polynomial { Self { polynomial } } + pub fn degree(&self) -> usize { + self.polynomial.len() + } + pub fn from_c_array(array: &Value) -> Self { let mut polynomial: Vec = vec![]; let c_array: Vec = array diff --git a/src/utils/sff.rs b/src/utils/sff.rs index f2478b5..f8f1358 100644 --- a/src/utils/sff.rs +++ b/src/utils/sff.rs @@ -8,9 +8,9 @@ use crate::utils::{ use super::poly::Polynomial; #[derive(Debug, Serialize, Deserialize)] -struct Factors { - factor: Vec, - exponent: u32, +pub struct Factors { + pub factor: Vec, + pub exponent: u32, } pub fn sff(mut f: Polynomial) -> Vec<(Polynomial, u32)> { diff --git a/test_json/sandbox.json b/test_json/sandbox.json index 48d59ed..007d487 100644 --- a/test_json/sandbox.json +++ b/test_json/sandbox.json @@ -1,26 +1,26 @@ { "testcases": { "sandbox": { - "action": "gfpoly_gcd", + "action": "gfpoly_factor_sff", "arguments": { - "A": [ - "DNWpXnnY24XecPa7a8vrEA==", - "I8uYpCbsiPaVvUznuv1IcA==", - "wsbiU432ARWuO93He3vbvA==", - "zp0g3o8iNz7Y+8oUxw1vJw==", - "J0GekE3uendpN6WUAuJ4AA==", - "wACd0e6u1ii4AAAAAAAAAA==", - "ACAAAAAAAAAAAAAAAAAAAA==" - ], - "B": [ - "I20VjJmlSnRSe88gaDiLRQ==", - "0Cw5HxJm/pfybJoQDf7/4w==", - "8ByrMMf+vVj5r3YXUNCJ1g==", - "rEU/f2UZRXqmZ6V7EPKfBA==", - "LfdALhvCrdhhGZWl9l9DSg==", - "KSUKhN0n6/DZmHPozd1prw==", - "DQrRkuA9Zx279wAAAAAAAA==", - "AhCEAAAAAAAAAAAAAAAAAA==" + "F": [ + "vL77UwAAAAAAAAAAAAAAAA==", + "mEHchYAAAAAAAAAAAAAAAA==", + "9WJa0MAAAAAAAAAAAAAAAA==", + "akHfwWAAAAAAAAAAAAAAAA==", + "E12o/QAAAAAAAAAAAAAAAA==", + "vKJ/FgAAAAAAAAAAAAAAAA==", + "yctWwAAAAAAAAAAAAAAAAA==", + "c1BXYAAAAAAAAAAAAAAAAA==", + "o0AtAAAAAAAAAAAAAAAAAA==", + "AbP2AAAAAAAAAAAAAAAAAA==", + "k2YAAAAAAAAAAAAAAAAAAA==", + "vBYAAAAAAAAAAAAAAAAAAA==", + "dSAAAAAAAAAAAAAAAAAAAA==", + "69gAAAAAAAAAAAAAAAAAAA==", + "VkAAAAAAAAAAAAAAAAAAAA==", + "a4AAAAAAAAAAAAAAAAAAAA==", + "gAAAAAAAAAAAAAAAAAAAAA==" ] } } From 341b22e18422c847affd2bf9f8063cadd6a55480 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Tue, 26 Nov 2024 13:19:07 +0100 Subject: [PATCH 42/79] feat: Add ddf algorithm --- Cargo.toml | 1 + src/tasks/mod.rs | 11 ++++- src/tasks/tasks01/pfmath.rs | 32 ++++++++++++-- src/utils/dff.rs | 85 ++++++++++++++++++++++++++++++++++--- src/utils/poly.rs | 77 +++++++++++++++++++++++++++++++++ 5 files changed, 193 insertions(+), 13 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e127c7e..8582eed 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ base64 = "0.22" openssl = "0.10" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" +num = "0.4" [source.crates-io] replace-with = "vendored-sources" diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index 2c3a428..a129f04 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -9,8 +9,9 @@ use tasks01::{ gfmul::gfmul_task, pad_oracle::padding_oracle, pfmath::{ - gfdiv, gfpoly_add, gfpoly_diff, gfpoly_divmod, gfpoly_factor_sff, gfpoly_gcd, - gfpoly_make_monic, gfpoly_mul, gfpoly_pow, gfpoly_powmod, gfpoly_sort, gfpoly_sqrt, + gfdiv, gfpoly_add, gfpoly_diff, gfpoly_divmod, gfpoly_factor_ddf, gfpoly_factor_sff, + gfpoly_gcd, gfpoly_make_monic, gfpoly_mul, gfpoly_pow, gfpoly_powmod, gfpoly_sort, + gfpoly_sqrt, }, poly2block::poly2block, sea128::sea128, @@ -163,6 +164,12 @@ pub fn task_deploy(testcase: &Testcase) -> Result { Ok(json) } + "gfpoly_factor_ddf" => { + let result = gfpoly_factor_ddf(args)?; + let json = json!({"factors" : result}); + + Ok(json) + } _ => Err(anyhow!( "Fatal. No compatible action found. Json data was {:?}. Arguments were; {:?}", diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index b9067cc..dec3b6e 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -1,11 +1,18 @@ +use std::usize; + use anyhow::Result; use base64::{prelude::BASE64_STANDARD, Engine}; use serde_json::Value; -use crate::utils::{ - field::FieldElement, - poly::{gcd, Polynomial}, - sff::{sff, Factors}, +use crate::{ + tasks, + utils::{ + self, + dff::ddf, + field::FieldElement, + poly::{gcd, Polynomial}, + sff::{sff, Factors}, + }, }; pub fn gfpoly_add(args: &Value) -> Result { @@ -135,6 +142,23 @@ pub fn gfpoly_factor_sff(arsg: &Value) -> Result> { Ok(result) } +pub fn gfpoly_factor_ddf(arsg: &Value) -> Result> { + let poly_f = Polynomial::from_c_array(&arsg["F"].clone()); + + let mut factors = ddf(poly_f); + factors.sort(); + let mut result: Vec = vec![]; + + for (factor, degree) in factors { + result.push(utils::dff::Factors { + factor: factor.to_c_array(), + degree: degree as u32, + }); + } + + Ok(result) +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/utils/dff.rs b/src/utils/dff.rs index 575d9de..6335d27 100644 --- a/src/utils/dff.rs +++ b/src/utils/dff.rs @@ -1,10 +1,81 @@ -use super::poly::Polynomial; +use std::usize; -pub fn dff(f: Polynomial) { - let q = 2u128.pow(128); - let z: Vec<(Polynomial, u32)> = vec![]; - let d = 1; - let f_start = f.clone(); +use num::{pow::Pow, traits::ToBytes, BigUint, FromPrimitive}; +use serde::{Deserialize, Serialize}; - while f_start.degree() >= 2 * d {} +use super::poly::{gcd, Polynomial}; + +#[derive(Debug, Serialize, Deserialize)] +pub struct Factors { + pub factor: Vec, + pub degree: u32, +} + +pub fn ddf(f: Polynomial) -> Vec<(Polynomial, usize)> { + let q = BigUint::pow(&BigUint::from_u8(2).unwrap(), 128); + eprintln!("q: {:?}", q); + + let mut z: Vec<(Polynomial, usize)> = vec![]; + let mut d: u32 = 1; + let mut f_star = f.clone(); + + let one_cmp = Polynomial::one(); + while f_star.degree() >= (2 * d) as usize { + let h = Polynomial::x().bpow_mod(q.clone().pow(d), f_star.clone()) + + Polynomial::x().div(&f_star).1; + + let g = gcd(&h, &f_star); + if g != one_cmp { + z.push((g.clone(), d as usize)); + f_star = f_star.div(&g).0; + } + + d += 1; + } + if f_star != one_cmp { + z.push((f_star.clone(), f_star.degree())); + } else if z.len() == 0 { + z.push((f.clone(), 1)); + } + + z +} + +#[cfg(test)] +mod tests { + + use serde_json::json; + + // Note this useful idiom: importing names from outer (for mod tests) scope. + use super::*; + + #[test] + fn test_dff_sheet() { + let json_f = json!([ + "tpkgAAAAAAAAAAAAAAAAAA==", + "m6MQAAAAAAAAAAAAAAAAAA==", + "8roAAAAAAAAAAAAAAAAAAA==", + "3dUAAAAAAAAAAAAAAAAAAA==", + "FwAAAAAAAAAAAAAAAAAAAA==", + "/kAAAAAAAAAAAAAAAAAAAA==", + "a4AAAAAAAAAAAAAAAAAAAA==", + "gAAAAAAAAAAAAAAAAAAAAA==" + ]); + let poly_f = Polynomial::from_c_array(&json_f); + + let mut factors = ddf(poly_f); + factors.sort(); + let mut result: Vec = vec![]; + + for (factor, degree) in factors { + result.push(Factors { + factor: factor.to_c_array(), + degree: degree as u32, + }); + } + + println!("Result: {:?}", result); + let bit_indices: Vec = vec![0]; + assert!(false) + } } diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 786c67a..42e6916 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -1,5 +1,7 @@ use crate::utils::field::ByteArray; +use base64::alphabet::BIN_HEX; use base64::prelude::*; +use num::{BigInt, BigUint, One, Zero}; use std::{str::FromStr, u128, u8, usize}; use std::{ @@ -26,6 +28,23 @@ impl Polynomial { self.polynomial.len() } + pub fn one() -> Self { + Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![0], "gcm").unwrap(), + )]) + } + + pub fn x() -> Self { + Polynomial::new(vec![ + FieldElement::new(vec![0; 16]), + FieldElement::new(polynomial_2_block(vec![0], "gcm").unwrap()), + ]) + } + + pub fn zero() -> Self { + Polynomial::new(vec![FieldElement::new(vec![0; 16])]) + } + pub fn from_c_array(array: &Value) -> Self { let mut polynomial: Vec = vec![]; let c_array: Vec = array @@ -122,6 +141,64 @@ impl Polynomial { result } + pub fn bpow_mod(mut self, mut exponent: BigUint, modulus: Polynomial) -> Polynomial { + let mut result: Polynomial = Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![0], "gcm").unwrap(), + )]); + + if exponent == BigUint::one() { + eprintln!("special case 1: {:02X?}", self.clone().div(&modulus).1); + + return self.div(&modulus).1; + } + + if exponent == BigUint::zero() { + let result = Polynomial::new(vec![FieldElement::new( + polynomial_2_block(vec![0], "gcm").unwrap(), + )]); + + eprintln!("Returned value is: {:02X?}", result); + return result; + } + + //eprintln!("Initial result: {:?}", result); + while &exponent > &BigUint::zero() { + //eprintln!("Current exponent: {:02X}", exponent); + if &exponent & BigUint::one() == BigUint::one() { + let temp = &self * &result; + //eprintln!("After multiplication: {:?}", temp); + result = temp.div(&modulus).1; + //eprintln!("After mod: {:?}", result); + } + let temp_square = &self * &self; + //eprintln!("After squaring: {:?}", temp_square); + self = temp_square.div(&modulus).1; + //eprintln!("After mod: {:?}", self); + exponent >>= 1; + } + + eprintln!("result in powmod before reduction: {:02X?}", result); + + while !result.polynomial.is_empty() + && result + .polynomial + .last() + .unwrap() + .as_ref() + .iter() + .all(|&x| x == 0) + { + result.polynomial.pop(); + } + + eprintln!("result in powmod after reduction: {:02X?}", result); + + if result.is_empty() { + result = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + } + + result + } pub fn pow_mod(mut self, mut exponent: u128, modulus: Polynomial) -> Polynomial { let mut result: Polynomial = Polynomial::new(vec![FieldElement::new( polynomial_2_block(vec![0], "gcm").unwrap(), From b54753fe7e2bd80494d15bc5c0cc2a4c2ada1571 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Tue, 26 Nov 2024 14:55:40 +0100 Subject: [PATCH 43/79] fix: Remove mod from X subtrahend in dff The modular operation is likely incorrect in this case. Removig it. --- src/utils/dff.rs | 13 ++++++------- src/utils/sff.rs | 8 ++++---- test_json/sandbox.json | 23 +++++++---------------- 3 files changed, 17 insertions(+), 27 deletions(-) diff --git a/src/utils/dff.rs b/src/utils/dff.rs index 6335d27..2cd754e 100644 --- a/src/utils/dff.rs +++ b/src/utils/dff.rs @@ -11,29 +11,28 @@ pub struct Factors { pub degree: u32, } -pub fn ddf(f: Polynomial) -> Vec<(Polynomial, usize)> { +pub fn ddf(f: Polynomial) -> Vec<(Polynomial, u128)> { let q = BigUint::pow(&BigUint::from_u8(2).unwrap(), 128); eprintln!("q: {:?}", q); - let mut z: Vec<(Polynomial, usize)> = vec![]; - let mut d: u32 = 1; + let mut z: Vec<(Polynomial, u128)> = vec![]; + let mut d: u128 = 1; let mut f_star = f.clone(); let one_cmp = Polynomial::one(); while f_star.degree() >= (2 * d) as usize { - let h = Polynomial::x().bpow_mod(q.clone().pow(d), f_star.clone()) - + Polynomial::x().div(&f_star).1; + let h = Polynomial::x().bpow_mod(q.clone().pow(d), f_star.clone()) + Polynomial::x(); let g = gcd(&h, &f_star); if g != one_cmp { - z.push((g.clone(), d as usize)); + z.push((g.clone(), d)); f_star = f_star.div(&g).0; } d += 1; } if f_star != one_cmp { - z.push((f_star.clone(), f_star.degree())); + z.push((f_star.clone(), f_star.degree() as u128)); } else if z.len() == 0 { z.push((f.clone(), 1)); } diff --git a/src/utils/sff.rs b/src/utils/sff.rs index f8f1358..e7a154a 100644 --- a/src/utils/sff.rs +++ b/src/utils/sff.rs @@ -10,14 +10,14 @@ use super::poly::Polynomial; #[derive(Debug, Serialize, Deserialize)] pub struct Factors { pub factor: Vec, - pub exponent: u32, + pub exponent: u128, } -pub fn sff(mut f: Polynomial) -> Vec<(Polynomial, u32)> { +pub fn sff(mut f: Polynomial) -> Vec<(Polynomial, u128)> { let mut c = gcd(&f, &f.clone().diff()); f = f.div(&c).0; - let mut z: Vec<(Polynomial, u32)> = vec![]; - let mut e: u32 = 1; + let mut z: Vec<(Polynomial, u128)> = vec![]; + let mut e: u128 = 1; let one_element = Polynomial::new(vec![FieldElement::new( polynomial_2_block(vec![0], "gcm").unwrap(), diff --git a/test_json/sandbox.json b/test_json/sandbox.json index 007d487..d0a0f3c 100644 --- a/test_json/sandbox.json +++ b/test_json/sandbox.json @@ -1,24 +1,15 @@ { "testcases": { "sandbox": { - "action": "gfpoly_factor_sff", + "action": "gfpoly_factor_ddf", "arguments": { "F": [ - "vL77UwAAAAAAAAAAAAAAAA==", - "mEHchYAAAAAAAAAAAAAAAA==", - "9WJa0MAAAAAAAAAAAAAAAA==", - "akHfwWAAAAAAAAAAAAAAAA==", - "E12o/QAAAAAAAAAAAAAAAA==", - "vKJ/FgAAAAAAAAAAAAAAAA==", - "yctWwAAAAAAAAAAAAAAAAA==", - "c1BXYAAAAAAAAAAAAAAAAA==", - "o0AtAAAAAAAAAAAAAAAAAA==", - "AbP2AAAAAAAAAAAAAAAAAA==", - "k2YAAAAAAAAAAAAAAAAAAA==", - "vBYAAAAAAAAAAAAAAAAAAA==", - "dSAAAAAAAAAAAAAAAAAAAA==", - "69gAAAAAAAAAAAAAAAAAAA==", - "VkAAAAAAAAAAAAAAAAAAAA==", + "tpkgAAAAAAAAAAAAAAAAAA==", + "m6MQAAAAAAAAAAAAAAAAAA==", + "8roAAAAAAAAAAAAAAAAAAA==", + "3dUAAAAAAAAAAAAAAAAAAA==", + "FwAAAAAAAAAAAAAAAAAAAA==", + "/kAAAAAAAAAAAAAAAAAAAA==", "a4AAAAAAAAAAAAAAAAAAAA==", "gAAAAAAAAAAAAAAAAAAAAA==" ] From d599292d3a758805634ac88756d4890160787528 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Wed, 27 Nov 2024 10:17:29 +0100 Subject: [PATCH 44/79] fix: Fix dff algorithm attempt --- src/utils/dff.rs | 11 ++++++++--- src/utils/field.rs | 11 ----------- src/utils/poly.rs | 6 +----- 3 files changed, 9 insertions(+), 19 deletions(-) diff --git a/src/utils/dff.rs b/src/utils/dff.rs index 2cd754e..19a6b63 100644 --- a/src/utils/dff.rs +++ b/src/utils/dff.rs @@ -1,6 +1,6 @@ use std::usize; -use num::{pow::Pow, traits::ToBytes, BigUint, FromPrimitive}; +use num::{cast::AsPrimitive, pow::Pow, traits::ToBytes, BigUint, FromPrimitive}; use serde::{Deserialize, Serialize}; use super::poly::{gcd, Polynomial}; @@ -13,25 +13,30 @@ pub struct Factors { pub fn ddf(f: Polynomial) -> Vec<(Polynomial, u128)> { let q = BigUint::pow(&BigUint::from_u8(2).unwrap(), 128); - eprintln!("q: {:?}", q); let mut z: Vec<(Polynomial, u128)> = vec![]; let mut d: u128 = 1; let mut f_star = f.clone(); let one_cmp = Polynomial::one(); - while f_star.degree() >= (2 * d) as usize { + while f_star.degree() as u128 >= (d) { let h = Polynomial::x().bpow_mod(q.clone().pow(d), f_star.clone()) + Polynomial::x(); let g = gcd(&h, &f_star); if g != one_cmp { + eprintln!("d is: {}", d); + eprintln!("g is: {:?}", &g.clone().to_c_array()); + z.push((g.clone(), d)); f_star = f_star.div(&g).0; } + eprintln!("d outer is: {}", d); + eprintln!("F star degree is {:?}", &f_star.degree()); d += 1; } if f_star != one_cmp { + eprintln!("fstar not one"); z.push((f_star.clone(), f_star.degree() as u128)); } else if z.len() == 0 { z.push((f.clone(), 1)); diff --git a/src/utils/field.rs b/src/utils/field.rs index 626d40d..bbdfa91 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -180,10 +180,7 @@ impl BitXor for FieldElement { impl Div for FieldElement { type Output = Self; fn div(self, rhs: Self) -> Self::Output { - eprintln!("RHS in div{:02X?}", &rhs); - let inverse = rhs.inv(); - eprintln!("Inverse in div{:02X?}", inverse); self.clone() * inverse } } @@ -202,15 +199,11 @@ impl Div for &FieldElement { impl PartialOrd for FieldElement { fn partial_cmp(&self, other: &Self) -> Option { for (byte_a, byte_b) in self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) { - eprintln!("Field Partial Ord Bytes: {:02X} {:02X}", byte_a, byte_b); if byte_a > byte_b { - eprintln!("Bytes were greater"); return Some(Ordering::Greater); } else if byte_a < byte_b { - eprintln!("Bytes were less"); return Some(Ordering::Less); } else { - eprintln!("Bytes were equal"); continue; } } @@ -231,15 +224,11 @@ impl Eq for FieldElement { impl Ord for FieldElement { fn cmp(&self, other: &Self) -> Ordering { for (byte_a, byte_b) in self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) { - eprintln!("Field Ord Bytes: {:02X} {:02X}", byte_a, byte_b); if byte_a > byte_b { - eprintln!("Bytes were greater"); return Ordering::Greater; } else if byte_a < byte_b { - eprintln!("Bytes were less"); return Ordering::Less; } else { - eprintln!("Bytes were equal"); continue; } } diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 42e6916..ef625ce 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -177,8 +177,6 @@ impl Polynomial { exponent >>= 1; } - eprintln!("result in powmod before reduction: {:02X?}", result); - while !result.polynomial.is_empty() && result .polynomial @@ -191,8 +189,6 @@ impl Polynomial { result.polynomial.pop(); } - eprintln!("result in powmod after reduction: {:02X?}", result); - if result.is_empty() { result = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); } @@ -262,7 +258,7 @@ impl Polynomial { pub fn div(&self, rhs: &Self) -> (Self, Self) { // Div by zero check ommitted since data is guaranteed to be non 0 - eprintln!("{:?}, {:?}", self.polynomial.len(), rhs.polynomial.len()); + //eprintln!("{:?}, {:?}", self.polynomial.len(), rhs.polynomial.len()); if self.polynomial.len() < rhs.polynomial.len() { return ( From fa7d33aaf6c9e482092cca96ca409408d1fafe31 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Wed, 27 Nov 2024 13:47:13 +0100 Subject: [PATCH 45/79] fix: Attempting further ddf fixes --- src/utils/dff.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/utils/dff.rs b/src/utils/dff.rs index 19a6b63..a4ebda8 100644 --- a/src/utils/dff.rs +++ b/src/utils/dff.rs @@ -38,8 +38,6 @@ pub fn ddf(f: Polynomial) -> Vec<(Polynomial, u128)> { if f_star != one_cmp { eprintln!("fstar not one"); z.push((f_star.clone(), f_star.degree() as u128)); - } else if z.len() == 0 { - z.push((f.clone(), 1)); } z From 6532c576c6737cc5500adac328de28ae03792353 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Wed, 27 Nov 2024 14:06:40 +0100 Subject: [PATCH 46/79] fix: Fix incorrect degree calculation --- src/utils/dff.rs | 3 ++- src/utils/poly.rs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/utils/dff.rs b/src/utils/dff.rs index a4ebda8..7ae23e1 100644 --- a/src/utils/dff.rs +++ b/src/utils/dff.rs @@ -19,7 +19,7 @@ pub fn ddf(f: Polynomial) -> Vec<(Polynomial, u128)> { let mut f_star = f.clone(); let one_cmp = Polynomial::one(); - while f_star.degree() as u128 >= (d) { + while f_star.degree() as u128 >= (2 * d) { let h = Polynomial::x().bpow_mod(q.clone().pow(d), f_star.clone()) + Polynomial::x(); let g = gcd(&h, &f_star); @@ -35,6 +35,7 @@ pub fn ddf(f: Polynomial) -> Vec<(Polynomial, u128)> { d += 1; } + if f_star != one_cmp { eprintln!("fstar not one"); z.push((f_star.clone(), f_star.degree() as u128)); diff --git a/src/utils/poly.rs b/src/utils/poly.rs index ef625ce..91d96ac 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -25,7 +25,7 @@ impl Polynomial { } pub fn degree(&self) -> usize { - self.polynomial.len() + self.polynomial.len() - 1 } pub fn one() -> Self { From b898c32ded3389952710f4523cbcf4ca56260fbe Mon Sep 17 00:00:00 2001 From: Alivecow Date: Wed, 27 Nov 2024 14:13:30 +0100 Subject: [PATCH 47/79] fix: Re-Add else-if case --- src/utils/dff.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/utils/dff.rs b/src/utils/dff.rs index 7ae23e1..fe60b9a 100644 --- a/src/utils/dff.rs +++ b/src/utils/dff.rs @@ -39,6 +39,8 @@ pub fn ddf(f: Polynomial) -> Vec<(Polynomial, u128)> { if f_star != one_cmp { eprintln!("fstar not one"); z.push((f_star.clone(), f_star.degree() as u128)); + } else if z.len() == 0 { + z.push((f.clone(), 1)); } z From 39c4d9b80d671f5cbae8c52cbe6095e1adcd6e68 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Thu, 28 Nov 2024 13:17:51 +0100 Subject: [PATCH 48/79] feat: Add edf calculation --- src/utils/dff.rs | 2 +- src/utils/edf.rs | 105 +++++++++++++++++++++++++++++++++++++++++++++ src/utils/field.rs | 6 +++ src/utils/poly.rs | 20 ++++++++- 4 files changed, 131 insertions(+), 2 deletions(-) diff --git a/src/utils/dff.rs b/src/utils/dff.rs index a4ebda8..da41e33 100644 --- a/src/utils/dff.rs +++ b/src/utils/dff.rs @@ -20,7 +20,7 @@ pub fn ddf(f: Polynomial) -> Vec<(Polynomial, u128)> { let one_cmp = Polynomial::one(); while f_star.degree() as u128 >= (d) { - let h = Polynomial::x().bpow_mod(q.clone().pow(d), f_star.clone()) + Polynomial::x(); + let h = Polynomial::x().bpow_mod(q.clone().pow(d), &f_star) + Polynomial::x(); let g = gcd(&h, &f_star); if g != one_cmp { diff --git a/src/utils/edf.rs b/src/utils/edf.rs index e69de29..134a743 100644 --- a/src/utils/edf.rs +++ b/src/utils/edf.rs @@ -0,0 +1,105 @@ +use base64::{prelude::BASE64_STANDARD, Engine}; +use num::{BigUint, FromPrimitive, Integer, One}; +use rand::Rng; + +use crate::utils::{field::FieldElement, poly::non_monic_gcd}; + +use super::poly::{gcd, Polynomial}; + +pub fn edf(f: Polynomial, d: u32) -> Vec { + eprintln!("Starting edf"); + + let q = BigUint::pow(&BigUint::from_u8(2).unwrap(), 128); + let n: u32 = (f.degree() as u32) / (d); + let mut z: Vec = vec![f.clone()]; + let one_cmp = Polynomial::one(); + + while (z.len() as u32) < n { + //eprintln!("z len {}", z.len()); + //eprintln!("n len {}", n); + + let h = Polynomial::rand(&rand::thread_rng().gen_range(0..f.degree())); + //eprintln!("h: {:02X?}", h); + + let exponent = (q.pow(d) - BigUint::one()) / BigUint::from_u8(3).unwrap(); + eprintln!("q before for {:0X?}", exponent); + + let g = h.bpow_mod(exponent, &f) + Polynomial::one(); + //eprintln!("g before for {:0X?}", g); + + //eprintln!("z before for {:0X?}", z); + + for i in 0..z.len() { + if z[i].degree() as u32 > d { + //eprintln!("Inside if"); + let j = gcd(&z[i], &g); + + eprintln!("j: {:02X?}", j); + if j != one_cmp && j != z[i] { + eprintln!("Working on Z"); + let intemediate = z[i].div(&j).0; + z.remove(i); + z.push(j.clone()); + z.push(intemediate); + } + } + } + + //eprintln!("z after for {:0X?}", z); + } + + z +} + +#[cfg(test)] +mod tests { + + use serde_json::json; + + // Note this useful idiom: importing names from outer (for mod tests) scope. + use super::*; + + #[test] + fn test_edf_sheet() { + let json_f = json!([ + "mmAAAAAAAAAAAAAAAAAAAA==", + "AbAAAAAAAAAAAAAAAAAAAA==", + "zgAAAAAAAAAAAAAAAAAAAA==", + "FwAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "gAAAAAAAAAAAAAAAAAAAAA==" + ]); + let d = 3; + let poly_f = Polynomial::from_c_array(&json_f); + + let mut factors = edf(poly_f, d); + factors.sort(); + + let mut result: Vec> = vec![]; + + for factor in factors { + result.push(factor.to_c_array()) + } + + println!("Result: {:?}", result); + + assert_eq!( + result, + vec![ + [ + "iwAAAAAAAAAAAAAAAAAAAA==", + "CAAAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "gAAAAAAAAAAAAAAAAAAAAA==" + ], + [ + "kAAAAAAAAAAAAAAAAAAAAA==", + "CAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", + "gAAAAAAAAAAAAAAAAAAAAA==" + ] + ] + ) + } +} diff --git a/src/utils/field.rs b/src/utils/field.rs index bbdfa91..2dea48b 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -1,4 +1,5 @@ use base64::prelude::*; +use rand::{random, Rng, RngCore}; use std::{u128, u8, usize}; use std::{ @@ -24,6 +25,11 @@ impl FieldElement { 87, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 01, ]; + pub fn rand() -> Self { + let rand_field: [u8; 16] = rand::random(); + FieldElement::new(rand_field.to_vec()) + } + pub fn zero(self) -> Self { FieldElement::new(vec![0]) } diff --git a/src/utils/poly.rs b/src/utils/poly.rs index ef625ce..84194cd 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -41,6 +41,15 @@ impl Polynomial { ]) } + pub fn rand(rng_cap: &usize) -> Self { + let mut rand_poly: Vec = Vec::with_capacity(rng_cap.to_owned()); + for _i in 0..rng_cap.to_owned() { + rand_poly.push(FieldElement::rand()); + } + + Polynomial::new(rand_poly) + } + pub fn zero() -> Self { Polynomial::new(vec![FieldElement::new(vec![0; 16])]) } @@ -141,7 +150,7 @@ impl Polynomial { result } - pub fn bpow_mod(mut self, mut exponent: BigUint, modulus: Polynomial) -> Polynomial { + pub fn bpow_mod(mut self, mut exponent: BigUint, modulus: &Polynomial) -> Polynomial { let mut result: Polynomial = Polynomial::new(vec![FieldElement::new( polynomial_2_block(vec![0], "gcm").unwrap(), )]); @@ -572,6 +581,15 @@ pub fn gcd(a: &Polynomial, b: &Polynomial) -> Polynomial { return gcd(&monic_b, a); } +pub fn non_monic_gcd(a: &Polynomial, b: &Polynomial) -> Polynomial { + if a.is_zero() { + return b.clone(); + } + + let b = b.div(&a).1; + return non_monic_gcd(&b, a); +} + pub fn sort_polynomial_array(mut polys: Vec) -> Result> { // Algorithm to sort polynomials // First sorting round From 444000a10168d2a3f668fc57f66db1cb53b3f025 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Thu, 28 Nov 2024 13:30:44 +0100 Subject: [PATCH 49/79] fix: Adding fix after merge error --- src/utils/dff.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/dff.rs b/src/utils/dff.rs index 2d325a0..be63040 100644 --- a/src/utils/dff.rs +++ b/src/utils/dff.rs @@ -21,7 +21,7 @@ pub fn ddf(f: Polynomial) -> Vec<(Polynomial, u128)> { let one_cmp = Polynomial::one(); while f_star.degree() as u128 >= (2 * d) { - let h = Polynomial::x().bpow_mod(q.clone().pow(d), f_star.clone()) + Polynomial::x(); + let h = Polynomial::x().bpow_mod(q.clone().pow(d), &f_star.clone()) + Polynomial::x(); let g = gcd(&h, &f_star); if g != one_cmp { From 905e905c350fd2beb5b9dbafc42968131f40ccef Mon Sep 17 00:00:00 2001 From: Alivecow Date: Thu, 28 Nov 2024 13:36:56 +0100 Subject: [PATCH 50/79] fix: Add needed dependency --- Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.toml b/Cargo.toml index 8582eed..28fc780 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ openssl = "0.10" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" num = "0.4" +rand = "0.8" [source.crates-io] replace-with = "vendored-sources" From f7f3c44acb8d7d1bc724479b447a6e5622cc7f31 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Thu, 28 Nov 2024 14:00:47 +0100 Subject: [PATCH 51/79] feat: Add testing runner for edf --- src/tasks/mod.rs | 12 +++++++++--- src/tasks/tasks01/pfmath.rs | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index a129f04..84a4f31 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -9,9 +9,9 @@ use tasks01::{ gfmul::gfmul_task, pad_oracle::padding_oracle, pfmath::{ - gfdiv, gfpoly_add, gfpoly_diff, gfpoly_divmod, gfpoly_factor_ddf, gfpoly_factor_sff, - gfpoly_gcd, gfpoly_make_monic, gfpoly_mul, gfpoly_pow, gfpoly_powmod, gfpoly_sort, - gfpoly_sqrt, + gfdiv, gfpoly_add, gfpoly_diff, gfpoly_divmod, gfpoly_factor_ddf, gfpoly_factor_edf, + gfpoly_factor_sff, gfpoly_gcd, gfpoly_make_monic, gfpoly_mul, gfpoly_pow, gfpoly_powmod, + gfpoly_sort, gfpoly_sqrt, }, poly2block::poly2block, sea128::sea128, @@ -170,6 +170,12 @@ pub fn task_deploy(testcase: &Testcase) -> Result { Ok(json) } + "gfpoly_factor_edf" => { + let result = gfpoly_factor_edf(args)?; + let json = json!({"factors" : result}); + + Ok(json) + } _ => Err(anyhow!( "Fatal. No compatible action found. Json data was {:?}. Arguments were; {:?}", diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index dec3b6e..0f5d134 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -9,6 +9,7 @@ use crate::{ utils::{ self, dff::ddf, + edf::edf, field::FieldElement, poly::{gcd, Polynomial}, sff::{sff, Factors}, @@ -159,6 +160,23 @@ pub fn gfpoly_factor_ddf(arsg: &Value) -> Result> { Ok(result) } +pub fn gfpoly_factor_edf(arsg: &Value) -> Result>> { + let poly_f = Polynomial::from_c_array(&arsg["F"].clone()); + let d: u32 = serde_json::from_value(arsg["d"].clone())?; + + let mut factors = edf(poly_f, d); + + factors.sort(); + + let mut result: Vec> = vec![]; + + for factor in factors { + result.push(factor.to_c_array()) + } + + Ok(result) +} + #[cfg(test)] mod tests { use super::*; From dd19c90ae12045774321d3d369874cc92e2cb2d7 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Thu, 28 Nov 2024 15:10:02 +0100 Subject: [PATCH 52/79] refactor: Apply cargo recommended refactoring --- src/tasks/tasks01/pfmath.rs | 12 ++++-------- src/utils/dff.rs | 2 +- src/utils/edf.rs | 4 +--- src/utils/field.rs | 1 - src/utils/poly.rs | 3 +-- 5 files changed, 7 insertions(+), 15 deletions(-) diff --git a/src/tasks/tasks01/pfmath.rs b/src/tasks/tasks01/pfmath.rs index 0f5d134..6830e1a 100644 --- a/src/tasks/tasks01/pfmath.rs +++ b/src/tasks/tasks01/pfmath.rs @@ -1,20 +1,16 @@ -use std::usize; use anyhow::Result; use base64::{prelude::BASE64_STANDARD, Engine}; use serde_json::Value; -use crate::{ - tasks, - utils::{ +use crate::utils::{ self, dff::ddf, edf::edf, field::FieldElement, poly::{gcd, Polynomial}, sff::{sff, Factors}, - }, -}; + }; pub fn gfpoly_add(args: &Value) -> Result { let poly_a = Polynomial::from_c_array(&args["A"].clone()); @@ -126,7 +122,7 @@ pub fn gfpoly_gcd(args: &Value) -> Result { Ok(result) } -pub fn gfpoly_factor_sff(arsg: &Value) -> Result> { +pub fn gfpoly_factor_sff(arsg: &Value) -> Result> { let poly_f = Polynomial::from_c_array(&arsg["F"].clone()); let mut factors = sff(poly_f); @@ -143,7 +139,7 @@ pub fn gfpoly_factor_sff(arsg: &Value) -> Result> { Ok(result) } -pub fn gfpoly_factor_ddf(arsg: &Value) -> Result> { +pub fn gfpoly_factor_ddf(arsg: &Value) -> Result> { let poly_f = Polynomial::from_c_array(&arsg["F"].clone()); let mut factors = ddf(poly_f); diff --git a/src/utils/dff.rs b/src/utils/dff.rs index be63040..bcd1ca0 100644 --- a/src/utils/dff.rs +++ b/src/utils/dff.rs @@ -1,6 +1,6 @@ use std::usize; -use num::{cast::AsPrimitive, pow::Pow, traits::ToBytes, BigUint, FromPrimitive}; +use num::{pow::Pow, BigUint, FromPrimitive}; use serde::{Deserialize, Serialize}; use super::poly::{gcd, Polynomial}; diff --git a/src/utils/edf.rs b/src/utils/edf.rs index 134a743..80f552c 100644 --- a/src/utils/edf.rs +++ b/src/utils/edf.rs @@ -1,8 +1,6 @@ -use base64::{prelude::BASE64_STANDARD, Engine}; -use num::{BigUint, FromPrimitive, Integer, One}; +use num::{BigUint, FromPrimitive, One}; use rand::Rng; -use crate::utils::{field::FieldElement, poly::non_monic_gcd}; use super::poly::{gcd, Polynomial}; diff --git a/src/utils/field.rs b/src/utils/field.rs index 2dea48b..dd2e982 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -1,5 +1,4 @@ use base64::prelude::*; -use rand::{random, Rng, RngCore}; use std::{u128, u8, usize}; use std::{ diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 48242ab..ac2b756 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -1,7 +1,6 @@ use crate::utils::field::ByteArray; -use base64::alphabet::BIN_HEX; use base64::prelude::*; -use num::{BigInt, BigUint, One, Zero}; +use num::{BigUint, One, Zero}; use std::{str::FromStr, u128, u8, usize}; use std::{ From 270abdb7b726ad37166da7b5a5685e53fe16d756 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Thu, 28 Nov 2024 17:45:10 +0100 Subject: [PATCH 53/79] refactor: Change gcd implementation to attempt faster calc --- src/utils/poly.rs | 16 ++++++++++++++-- test_json/sandbox.json | 16 ++++++++-------- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 48242ab..5b4d86f 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -576,9 +576,21 @@ pub fn gcd(a: &Polynomial, b: &Polynomial) -> Polynomial { if a.is_zero() { return b.clone(); } + if b.is_zero() { + return a.clone(); + } - let monic_b = b.div(&a).1.monic(); - return gcd(&monic_b, a); + if a.degree() > b.degree() { + return gcd(b, a); + } + + let (_, remainder) = b.div(a); + + if remainder.is_zero() { + return a.clone().monic(); + } + + gcd(&remainder, a) } pub fn non_monic_gcd(a: &Polynomial, b: &Polynomial) -> Polynomial { diff --git a/test_json/sandbox.json b/test_json/sandbox.json index d0a0f3c..836b3c8 100644 --- a/test_json/sandbox.json +++ b/test_json/sandbox.json @@ -1,18 +1,18 @@ { "testcases": { "sandbox": { - "action": "gfpoly_factor_ddf", + "action": "gfpoly_factor_edf", "arguments": { "F": [ - "tpkgAAAAAAAAAAAAAAAAAA==", - "m6MQAAAAAAAAAAAAAAAAAA==", - "8roAAAAAAAAAAAAAAAAAAA==", - "3dUAAAAAAAAAAAAAAAAAAA==", + "mmAAAAAAAAAAAAAAAAAAAA==", + "AbAAAAAAAAAAAAAAAAAAAA==", + "zgAAAAAAAAAAAAAAAAAAAA==", "FwAAAAAAAAAAAAAAAAAAAA==", - "/kAAAAAAAAAAAAAAAAAAAA==", - "a4AAAAAAAAAAAAAAAAAAAA==", + "AAAAAAAAAAAAAAAAAAAAAA==", + "wAAAAAAAAAAAAAAAAAAAAA==", "gAAAAAAAAAAAAAAAAAAAAA==" - ] + ], + "d": 3 } } } From 5b27a4ad9c9b1dad0ea34e94c03e4578c98243d9 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 29 Nov 2024 13:49:57 +0100 Subject: [PATCH 54/79] feat/refactor: Change unneded vec initialisations and start on possible new gfmul --- src/utils/field.rs | 28 ++++++++++-------- src/utils/poly.rs | 72 +++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 81 insertions(+), 19 deletions(-) diff --git a/src/utils/field.rs b/src/utils/field.rs index 2dea48b..7b4059c 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -9,6 +9,8 @@ use std::{ use anyhow::{anyhow, Ok, Result}; +use crate::utils::poly::bgfmul; + use super::poly::polynomial_2_block; use super::{ math::{reverse_bits_in_bytevec, xor_bytes}, @@ -22,7 +24,7 @@ pub struct FieldElement { impl FieldElement { pub const IRREDUCIBLE_POLYNOMIAL: [u8; 17] = [ - 87, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 01, + 0x87, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 0x01, ]; pub fn rand() -> Self { @@ -30,10 +32,14 @@ impl FieldElement { FieldElement::new(rand_field.to_vec()) } - pub fn zero(self) -> Self { + pub fn zero() -> Self { FieldElement::new(vec![0]) } + pub fn one() -> Self { + FieldElement::new(vec![0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) + } + pub const fn new(field_element: Vec) -> Self { Self { field_element } } @@ -47,8 +53,7 @@ impl FieldElement { } pub fn pow(mut self, mut exponent: u128) -> FieldElement { - let mut result: FieldElement = - FieldElement::new(polynomial_2_block(vec![0], "gcm").unwrap()); + let mut result: FieldElement = FieldElement::one(); if exponent == 1 { eprintln!("special case 1: {:02X?}", self.clone()); @@ -57,7 +62,7 @@ impl FieldElement { } if exponent == 0 { - let result = FieldElement::new(polynomial_2_block(vec![0], "gcm").unwrap()); + let result = FieldElement::one(); eprintln!("Returned value is: {:02X?}", result); return result; @@ -90,8 +95,10 @@ impl FieldElement { } pub fn inv(mut self) -> Self { - let mut inverser: u128 = 0xfffffffffffffffffffffffffffffffe; - let mut inverse: Vec = polynomial_2_block(vec![0], "gcm").unwrap(); + const INVERSER_START: u128 = 0xfffffffffffffffffffffffffffffffe; + + let mut inverser = INVERSER_START; + let mut inverse: Vec = vec![0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; //eprintln!("Inverse start {:02X?}", inverse); while inverser > 0 { @@ -187,7 +194,7 @@ impl Div for FieldElement { type Output = Self; fn div(self, rhs: Self) -> Self::Output { let inverse = rhs.inv(); - self.clone() * inverse + self * inverse } } @@ -195,10 +202,7 @@ impl Div for &FieldElement { type Output = FieldElement; fn div(self, rhs: Self) -> Self::Output { - // First clone and invert the divisor (rhs) - let rhs_inv = rhs.clone().inv(); - // Multiply original number by the inverse - self.clone() * rhs_inv + self.clone() * rhs.clone().inv() } } diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 5b4d86f..82e991a 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -1,6 +1,7 @@ use crate::utils::field::ByteArray; use base64::alphabet::BIN_HEX; use base64::prelude::*; +use num::traits::FromBytes; use num::{BigInt, BigUint, One, Zero}; use std::{str::FromStr, u128, u8, usize}; @@ -13,6 +14,7 @@ use anyhow::{anyhow, Ok, Result}; use serde_json::Value; use super::field::FieldElement; +use super::math::reverse_bits_in_bytevec; #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct Polynomial { @@ -291,10 +293,7 @@ impl Polynomial { } let mut quotient_coeffs = - vec![ - FieldElement::new(polynomial_2_block(vec![0; 16], "gcm").unwrap()); - dividend_deg - divisor_deg + 1 - ]; + vec![FieldElement::new(vec![0; 16]); dividend_deg - divisor_deg + 1]; while remainder.polynomial.len() >= divisor.polynomial.len() { let deg_diff = remainder.polynomial.len() - divisor.polynomial.len(); @@ -305,8 +304,7 @@ impl Polynomial { quotient_coeffs[deg_diff] = quot_coeff.clone(); - let mut subtrahend = - vec![FieldElement::new(polynomial_2_block(vec![0; 16], "gcm").unwrap()); deg_diff]; + let mut subtrahend = vec![FieldElement::new(vec![0; 16]); deg_diff]; subtrahend.extend( divisor .polynomial @@ -658,6 +656,53 @@ pub fn gfmul(poly_a: &Vec, poly_b: &Vec, semantic: &str) -> Result, poly_b: &Vec, semantic: &str) -> Result> { + //TODO: Implement gfmul with bigint + let red_poly_bytes: BigUint = BigUint::from_slice(&[ + 0x87, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 0x01, + ]); + + let mut poly1: BigUint = BigUint::from_le_bytes(&reverse_bits_in_bytevec(poly_a.to_owned())); + + let mut poly2: BigUint = BigUint::from_le_bytes(&reverse_bits_in_bytevec(poly_b.to_owned())); + + /* + if semantic == "gcm" { + poly1.re; + poly2.reverse_bits_in_bytevec(); + } + */ + + let mut result: BigUint = BigUint::zero(); + + if (&poly2 & (BigUint::one() << 127)) == BigUint::one() { + result = &result ^ &poly1; + } + poly2 = &poly2 >> 1; + + while &poly2 != &BigUint::zero() { + poly1 = &poly1 << 1; + + if (&poly1 & (BigUint::one() << 127)) == BigUint::one() { + poly1 = &poly1 ^ &red_poly_bytes; + } + + if &poly2 & BigUint::one() == BigUint::one() { + result = &result ^ &poly1; + } + + poly2 = &poly2 >> 1; + } + + /* + if semantic == "gcm" { + result.reverse_bits_in_bytevec(); + } + */ + + Ok(reverse_bits_in_bytevec(result.to_bytes_le())) +} + pub fn convert_gcm_to_xex(gcm_poly: Vec) -> Result> { let xex_poly = gcm_poly .into_iter() @@ -795,7 +840,7 @@ pub fn coefficient_to_binary(coefficients: Vec) -> u128 { #[cfg(test)] mod tests { - use crate::utils::poly::b64_2_num; + use crate::utils::poly::{b64_2_num, gcd}; use anyhow::Result; use serde_json::json; // Note this useful idiom: importing names from outer (for mod tests) scope. @@ -1429,4 +1474,17 @@ mod tests { assert_eq!(json!(result.to_c_array()), expected); } + + #[test] + fn test_poly_gcd_stress() { + eprintln!("{:?}", Polynomial::one()); + + let poly1 = Polynomial::rand(&(500 as usize)); + let poly2 = Polynomial::rand(&(500 as usize)); + + let result = gcd(&poly1.monic(), &poly2.monic()); + + eprintln!("{:02X?}", result.to_c_array()); + assert!(true); + } } From e8c9cb1ade5853862f2bf63c5902580f2e61b51a Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 29 Nov 2024 14:31:52 +0100 Subject: [PATCH 55/79] refactor: Imrpove gfmul to remove unneded vec manipulation and imporve performanve --- src/utils/poly.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 82e991a..eeffc34 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -613,20 +613,20 @@ pub const RED_POLY: u128 = 0x87000000_00000000_00000000_00000000; pub fn gfmul(poly_a: &Vec, poly_b: &Vec, semantic: &str) -> Result> { let mut red_poly_bytes: ByteArray = ByteArray(RED_POLY.to_be_bytes().to_vec()); - red_poly_bytes.0.push(0x01); + //red_poly_bytes.0.push(0x01); let mut poly1: ByteArray = ByteArray(poly_a.to_owned()); - poly1.0.push(0x00); + //poly1.0.push(0x00); let mut poly2: ByteArray = ByteArray(poly_b.to_owned()); - poly2.0.push(0x00); + //poly2.0.push(0x00); if semantic == "gcm" { poly1.reverse_bits_in_bytevec(); poly2.reverse_bits_in_bytevec(); } - let mut result: ByteArray = ByteArray(vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + let mut result: ByteArray = ByteArray(vec![0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); if poly2.LSB_is_one() { result.xor_byte_arrays(&poly1); @@ -634,9 +634,9 @@ pub fn gfmul(poly_a: &Vec, poly_b: &Vec, semantic: &str) -> Result, poly_b: &Vec, semantic: &str) -> Result Date: Fri, 29 Nov 2024 16:50:19 +0100 Subject: [PATCH 56/79] refactor: Change implementation to only switch semantic once --- src/utils/field.rs | 57 ++++++++++++++++++++++++++-------------- src/utils/poly.rs | 65 +++++++++++++++------------------------------- 2 files changed, 59 insertions(+), 63 deletions(-) diff --git a/src/utils/field.rs b/src/utils/field.rs index 9b9876b..7d40732 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -28,18 +28,24 @@ impl FieldElement { pub fn rand() -> Self { let rand_field: [u8; 16] = rand::random(); - FieldElement::new(rand_field.to_vec()) + FieldElement::new_no_convert(rand_field.to_vec()) } pub fn zero() -> Self { - FieldElement::new(vec![0]) + FieldElement::new_no_convert(vec![0; 16]) } pub fn one() -> Self { - FieldElement::new(vec![0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) + FieldElement::new_no_convert(vec![0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) } - pub const fn new(field_element: Vec) -> Self { + pub fn new(field_element: Vec) -> Self { + Self { + field_element: reverse_bits_in_bytevec(field_element), + } + } + + pub fn new_no_convert(field_element: Vec) -> Self { Self { field_element } } @@ -48,7 +54,7 @@ impl FieldElement { } pub fn to_b64(&self) -> String { - BASE64_STANDARD.encode(&self.field_element) + BASE64_STANDARD.encode(reverse_bits_in_bytevec(self.field_element.to_owned())) } pub fn pow(mut self, mut exponent: u128) -> FieldElement { @@ -97,20 +103,20 @@ impl FieldElement { const INVERSER_START: u128 = 0xfffffffffffffffffffffffffffffffe; let mut inverser = INVERSER_START; - let mut inverse: Vec = vec![0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + let mut inverse: Vec = vec![0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; //eprintln!("Inverse start {:02X?}", inverse); while inverser > 0 { //eprintln!("{:02X}", inverser); if inverser & 1 == 1 { - inverse = gfmul(&self.field_element, &inverse, "gcm").unwrap(); + inverse = gfmul(&self.field_element, &inverse, "xex").unwrap(); } inverser >>= 1; - self.field_element = gfmul(&self.field_element, &self.field_element, "gcm") + self.field_element = gfmul(&self.field_element, &self.field_element, "xex") .expect("Error in sqrmul sqr"); } //eprintln!("Inverse rhs {:?}", inverse); - FieldElement::new(inverse) + FieldElement::new_no_convert(inverse) } pub fn is_zero(&self) -> bool { @@ -118,7 +124,7 @@ impl FieldElement { } pub fn reverse_bits(&self) -> Self { - FieldElement::new(reverse_bits_in_bytevec(self.field_element.clone())) + FieldElement::new_no_convert(reverse_bits_in_bytevec(self.field_element.clone())) } } @@ -126,8 +132,8 @@ impl Mul for FieldElement { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { - FieldElement::new( - gfmul(&self.field_element, &rhs.field_element, "gcm") + FieldElement::new_no_convert( + gfmul(&self.field_element, &rhs.field_element, "xex") .expect("Error during multiplication"), ) } @@ -137,8 +143,8 @@ impl Mul for &FieldElement { type Output = FieldElement; fn mul(self, rhs: &FieldElement) -> FieldElement { - FieldElement::new( - gfmul(&self.field_element, &rhs.field_element, "gcm") + FieldElement::new_no_convert( + gfmul(&self.field_element, &rhs.field_element, "xex") .expect("Error during multiplication"), ) } @@ -147,7 +153,7 @@ impl Mul for &FieldElement { impl Add for FieldElement { type Output = Self; fn add(self, rhs: Self) -> Self::Output { - FieldElement::new( + FieldElement::new_no_convert( xor_bytes(&self.field_element, rhs.field_element).expect("Error in poly add"), ) } @@ -156,7 +162,7 @@ impl Add for FieldElement { impl Add for &FieldElement { type Output = FieldElement; fn add(self, rhs: Self) -> Self::Output { - FieldElement::new( + FieldElement::new_no_convert( xor_bytes(&self.field_element, rhs.field_element.clone()).expect("Error in poly add"), ) } @@ -185,7 +191,7 @@ impl BitXor for FieldElement { .zip(rhs.field_element.iter()) .map(|(&x1, &x2)| x1 ^ x2) .collect(); - FieldElement::new(result) + FieldElement::new_no_convert(result) } } @@ -450,7 +456,7 @@ mod tests { FieldElement::new(BASE64_STANDARD.decode("KryptoanalyseAAAAAAAAA==").unwrap()); let sum = element2 + element1; - assert_eq!(BASE64_STANDARD.encode(sum), "H1d3GuyA9/0OxeYouUpAAA=="); + assert_eq!(sum.to_b64(), "H1d3GuyA9/0OxeYouUpAAA=="); } #[test] @@ -461,6 +467,19 @@ mod tests { FieldElement::new(BASE64_STANDARD.decode("DHBWMannheimAAAAAAAAAA==").unwrap()); let sum = element2 + element1; - assert_eq!(BASE64_STANDARD.encode(sum), "OZuIncPAGEp4tYouDownAA=="); + assert_eq!(sum.to_b64(), "OZuIncPAGEp4tYouDownAA=="); + } + + #[test] + fn test_field_div_01() { + let element1 = + FieldElement::new(BASE64_STANDARD.decode("JAAAAAAAAAAAAAAAAAAAAA==").unwrap()); + + let element2 = + FieldElement::new(BASE64_STANDARD.decode("wAAAAAAAAAAAAAAAAAAAAA==").unwrap()); + + let result = element1 / element2; + + assert_eq!(result.to_b64(), "OAAAAAAAAAAAAAAAAAAAAA=="); } } diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 68edb82..0d7b122 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -32,15 +32,13 @@ impl Polynomial { } pub fn one() -> Self { - Polynomial::new(vec![FieldElement::new( - polynomial_2_block(vec![0], "gcm").unwrap(), - )]) + Polynomial::new(vec![FieldElement::one()]) } pub fn x() -> Self { Polynomial::new(vec![ FieldElement::new(vec![0; 16]), - FieldElement::new(polynomial_2_block(vec![0], "gcm").unwrap()), + FieldElement::new(polynomial_2_block(vec![0], "xex").unwrap()), ]) } @@ -54,7 +52,7 @@ impl Polynomial { } pub fn zero() -> Self { - Polynomial::new(vec![FieldElement::new(vec![0; 16])]) + Polynomial::new(vec![FieldElement::zero()]) } pub fn from_c_array(array: &Value) -> Self { @@ -85,7 +83,7 @@ impl Polynomial { pub fn to_c_array(self) -> Vec { let mut output: Vec = vec![]; for coeff in self.polynomial { - output.push(BASE64_STANDARD.encode(coeff)); + output.push(coeff.to_b64()); } output @@ -219,9 +217,7 @@ impl Polynomial { } if exponent == 0 { - let result = Polynomial::new(vec![FieldElement::new( - polynomial_2_block(vec![0], "gcm").unwrap(), - )]); + let result = Polynomial::new(vec![FieldElement::one()]); eprintln!("Returned value is: {:02X?}", result); return result; @@ -273,10 +269,7 @@ impl Polynomial { //eprintln!("{:?}, {:?}", self.polynomial.len(), rhs.polynomial.len()); if self.polynomial.len() < rhs.polynomial.len() { - return ( - Polynomial::new(vec![FieldElement::new(vec![0; 16])]), - self.clone(), - ); + return (Polynomial::new(vec![FieldElement::zero()]), self.clone()); } let mut remainder = self.clone(); @@ -285,16 +278,10 @@ impl Polynomial { let divisor_deg = divisor.polynomial.len() - 1; if dividend_deg < divisor_deg { - return ( - Polynomial::new(vec![FieldElement::new( - polynomial_2_block(vec![0; 16], "gcm").unwrap(), - )]), - remainder, - ); + return (Polynomial::new(vec![FieldElement::zero()]), remainder); } - let mut quotient_coeffs = - vec![FieldElement::new(vec![0; 16]); dividend_deg - divisor_deg + 1]; + let mut quotient_coeffs = vec![FieldElement::zero(); dividend_deg - divisor_deg + 1]; while remainder.polynomial.len() >= divisor.polynomial.len() { let deg_diff = remainder.polynomial.len() - divisor.polynomial.len(); @@ -305,7 +292,7 @@ impl Polynomial { quotient_coeffs[deg_diff] = quot_coeff.clone(); - let mut subtrahend = vec![FieldElement::new(vec![0; 16]); deg_diff]; + let mut subtrahend = vec![FieldElement::zero(); deg_diff]; subtrahend.extend( divisor .polynomial @@ -330,7 +317,7 @@ impl Polynomial { } if remainder.is_empty() { - remainder = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + remainder = Polynomial::new(vec![FieldElement::zero()]); } (Polynomial::new(quotient_coeffs), remainder) } @@ -431,10 +418,10 @@ impl Mul for Polynomial { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { if self.is_zero() || rhs.is_zero() { - return Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + return Polynomial::zero(); } let mut polynomial: Vec = - vec![FieldElement::new(vec![0; 16]); self.polynomial.len() + rhs.polynomial.len() - 1]; + vec![FieldElement::zero(); self.polynomial.len() + rhs.polynomial.len() - 1]; for i in 0..self.polynomial.len() { for j in 0..rhs.polynomial.len() { polynomial[i + j] = &polynomial[i + j] @@ -449,10 +436,10 @@ impl Mul for &Polynomial { type Output = Polynomial; fn mul(self, rhs: Self) -> Self::Output { if self.is_zero() || rhs.is_zero() { - return Polynomial::new(vec![FieldElement::new(vec![0])]); + return Polynomial::zero(); } let mut polynomial: Vec = - vec![FieldElement::new(vec![0; 16]); self.polynomial.len() + rhs.polynomial.len() - 1]; + vec![FieldElement::zero(); self.polynomial.len() + rhs.polynomial.len() - 1]; for i in 0..self.polynomial.len() { for j in 0..rhs.polynomial.len() { polynomial[i + j] = &polynomial[i + j] @@ -486,7 +473,7 @@ impl Add for Polynomial { } if polynomial.is_empty() { - return Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + return Polynomial::new(vec![FieldElement::zero()]); } Polynomial::new(polynomial) @@ -535,8 +522,8 @@ impl PartialOrd for Polynomial { ); match field_a - .reverse_bits() - .partial_cmp(&field_b.reverse_bits()) + //.reverse_bits() + .partial_cmp(&field_b) .unwrap() { Ordering::Equal => continue, @@ -559,7 +546,10 @@ impl Ord for Polynomial { for (field_a, field_b) in self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) { - match field_a.reverse_bits().cmp(&field_b.reverse_bits()) { + match field_a + //.reverse_bits() + .cmp(&field_b) + { Ordering::Equal => continue, other => return other, } @@ -1136,19 +1126,6 @@ mod tests { //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } - #[test] - fn test_poly_div_01() { - let element1 = - FieldElement::new(BASE64_STANDARD.decode("JAAAAAAAAAAAAAAAAAAAAA==").unwrap()); - - let element2 = - FieldElement::new(BASE64_STANDARD.decode("wAAAAAAAAAAAAAAAAAAAAA==").unwrap()); - - let result = element1 / element2; - - assert_eq!(BASE64_STANDARD.encode(result), "OAAAAAAAAAAAAAAAAAAAAA=="); - } - #[test] fn test_field_poly_div_01() { let json1 = json!([ From 007bbddfcd75532d995909ece70135c026ec36a5 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 29 Nov 2024 17:22:47 +0100 Subject: [PATCH 57/79] fix: Fix incorrect ouput in gfdiv task --- src/tasks/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index 84a4f31..d2c57b7 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -105,7 +105,7 @@ pub fn task_deploy(testcase: &Testcase) -> Result { } "gfdiv" => { let result = gfdiv(args)?; - let out = BASE64_STANDARD.encode(result); + let out = result.to_b64(); let json = json!({"q" : out}); Ok(json) From bf4c3ee4ca71c928e978aafaca2083cdaa7badf7 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 29 Nov 2024 19:02:37 +0100 Subject: [PATCH 58/79] refactor: Remove unneded prints and change gfmul --- Cargo.toml | 4 ++++ src/utils/ciphers.rs | 37 ------------------------------------- src/utils/edf.rs | 6 ------ src/utils/field.rs | 3 --- src/utils/poly.rs | 31 +++++-------------------------- 5 files changed, 9 insertions(+), 72 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 28fc780..9cf5fa2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,3 +18,7 @@ replace-with = "vendored-sources" [source.vendored-sources] directory = "vendor" + +[profile.profiling] +inherits = "release" +debug = true diff --git a/src/utils/ciphers.rs b/src/utils/ciphers.rs index 35181a5..82af34b 100644 --- a/src/utils/ciphers.rs +++ b/src/utils/ciphers.rs @@ -119,10 +119,8 @@ pub fn gcm_encrypt_aes( let mut counter: u32 = 1; nonce.append(counter.to_be_bytes().to_vec().as_mut()); //nonce.append(0u8.to_le_bytes().to_vec().as_mut()); - eprintln!("{:001X?}", nonce); let auth_tag_xor = aes_128_encrypt(&key, &nonce)?; - eprintln!("Y0 {:001X?}", auth_tag_xor); let auth_key_h = aes_128_encrypt(&key, &0u128.to_be_bytes().to_vec())?; @@ -133,8 +131,6 @@ pub fn gcm_encrypt_aes( nonce.drain(12..); nonce.append(counter.to_be_bytes().to_vec().as_mut()); - eprintln!("{:001X?}", nonce); - let inter1 = aes_128_encrypt(&key, &nonce)?; let mut inter2 = xor_bytes(&inter1, chunk.clone())?; @@ -151,7 +147,6 @@ pub fn gcm_encrypt_aes( &ghash(auth_key_h.clone(), ad, ciphertext.clone(), l_field.clone())?, auth_tag_xor, )?; - eprintln!("aes auth tag: {:001X?}", &auth_tag); Ok((ciphertext, auth_tag, l_field, auth_key_h)) } @@ -168,7 +163,6 @@ pub fn gcm_decrypt_aes( let mut counter: u32 = 1; nonce.append(counter.to_be_bytes().to_vec().as_mut()); //nonce.append(0u8.to_le_bytes().to_vec().as_mut()); - eprintln!("{:001X?}", nonce); let auth_tag_xor = aes_128_encrypt(&key, &nonce)?; @@ -181,8 +175,6 @@ pub fn gcm_decrypt_aes( nonce.drain(12..); nonce.append(counter.to_be_bytes().to_vec().as_mut()); - eprintln!("{:001X?}", nonce); - let inter1 = aes_128_encrypt(&key, &nonce)?; let mut inter2 = xor_bytes(&inter1, chunk.clone())?; @@ -201,7 +193,6 @@ pub fn gcm_decrypt_aes( )?; let valid = auth_tag == tag; - eprintln!("aes auth tag: {:001X?}", auth_tag); Ok((plaintext, valid)) } @@ -217,7 +208,6 @@ pub fn gcm_encrypt_sea( let mut counter: u32 = 1; nonce.append(counter.to_be_bytes().to_vec().as_mut()); //nonce.append(0u8.to_le_bytes().to_vec().as_mut()); - eprintln!("{:001X?}", nonce); let auth_tag_xor = sea_128_encrypt(&key, &nonce)?; @@ -230,8 +220,6 @@ pub fn gcm_encrypt_sea( nonce.drain(12..); nonce.append(counter.to_be_bytes().to_vec().as_mut()); - eprintln!("{:001X?}", nonce); - let inter1 = sea_128_encrypt(&key, &nonce)?; let mut inter2 = xor_bytes(&inter1, chunk.clone())?; @@ -264,7 +252,6 @@ pub fn gcm_decrypt_sea( let mut counter: u32 = 1; nonce.append(counter.to_be_bytes().to_vec().as_mut()); //nonce.append(0u8.to_le_bytes().to_vec().as_mut()); - eprintln!("Nonce 1: {:001X?}", nonce); let auth_tag_xor = sea_128_encrypt(&key, &nonce)?; @@ -272,17 +259,11 @@ pub fn gcm_decrypt_sea( let plaintext_chunks: Vec> = ciphertext.chunks(16).map(|x| x.to_vec()).collect(); - eprintln!("{:?}", plaintext_chunks); - counter = 2; for chunk in plaintext_chunks { - eprintln!("Inside loop"); - nonce.drain(12..); nonce.append(counter.to_be_bytes().to_vec().as_mut()); - eprintln!("Nonce 2: {:001X?}", nonce); - let inter1 = sea_128_encrypt(&key, &nonce)?; let mut inter2 = xor_bytes(&inter1, chunk.clone())?; @@ -295,15 +276,11 @@ pub fn gcm_decrypt_sea( let mut c_len: Vec = ((plaintext.len() * 8) as u64).to_be_bytes().to_vec(); l_field.append(c_len.as_mut()); - eprintln!("Ciphertext: {}", BASE64_STANDARD.encode(&ciphertext)); - let auth_tag = xor_bytes( &ghash(auth_key_h.clone(), ad, ciphertext.clone(), l_field.clone())?, auth_tag_xor, )?; - eprintln!("sea dec auth tag: {}", BASE64_STANDARD.encode(&auth_tag)); - let valid = auth_tag == tag; Ok((plaintext, valid)) @@ -317,10 +294,6 @@ pub fn ghash( ) -> Result> { let output: Vec = vec![0; 16]; - eprintln!("{:?}", ad.len() as u8); - eprintln!("{:?}", (ad.len() % 16) as u8); - eprintln!("{:001X?}", ad); - if ad.len() % 16 != 0 || ad.is_empty() { ad.append(vec![0u8; 16 - (ad.len() % 16)].as_mut()); } @@ -329,20 +302,12 @@ pub fn ghash( ciphertext.append(vec![0u8; 16 - (ciphertext.len() % 16)].as_mut()); } - eprintln!("{:001X?}", ad); - eprintln!("{:001X?}", ciphertext); - let mut ad_chunks = ad.chunks(16); - eprintln!("Ad chunks before first next {:001X?}", ad_chunks); - let inter1 = xor_bytes(&output, ad_chunks.next().unwrap().to_vec())?; let mut inter_loop = gfmul(&inter1, &auth_key_h, "gcm")?; - eprintln!("Ad chunks after first next {:001X?}", ad_chunks); for chunk in ad_chunks { - eprintln!("Inside ad chunk loop"); - eprintln!("Ad chunk in loop {:001X?}", chunk); let inter2 = xor_bytes(&inter_loop, chunk.to_vec())?; inter_loop = gfmul(&inter2, &auth_key_h, "gcm")?; } @@ -357,8 +322,6 @@ pub fn ghash( let inter4 = xor_bytes(&inter_loop, l_field)?; inter_loop = gfmul(&inter4, &auth_key_h, "gcm")?; - eprintln!("GHASH auth tag: {:001X?}", inter_loop); - Ok(inter_loop) } diff --git a/src/utils/edf.rs b/src/utils/edf.rs index 80f552c..72f687d 100644 --- a/src/utils/edf.rs +++ b/src/utils/edf.rs @@ -1,12 +1,9 @@ use num::{BigUint, FromPrimitive, One}; use rand::Rng; - use super::poly::{gcd, Polynomial}; pub fn edf(f: Polynomial, d: u32) -> Vec { - eprintln!("Starting edf"); - let q = BigUint::pow(&BigUint::from_u8(2).unwrap(), 128); let n: u32 = (f.degree() as u32) / (d); let mut z: Vec = vec![f.clone()]; @@ -20,7 +17,6 @@ pub fn edf(f: Polynomial, d: u32) -> Vec { //eprintln!("h: {:02X?}", h); let exponent = (q.pow(d) - BigUint::one()) / BigUint::from_u8(3).unwrap(); - eprintln!("q before for {:0X?}", exponent); let g = h.bpow_mod(exponent, &f) + Polynomial::one(); //eprintln!("g before for {:0X?}", g); @@ -32,9 +28,7 @@ pub fn edf(f: Polynomial, d: u32) -> Vec { //eprintln!("Inside if"); let j = gcd(&z[i], &g); - eprintln!("j: {:02X?}", j); if j != one_cmp && j != z[i] { - eprintln!("Working on Z"); let intemediate = z[i].div(&j).0; z.remove(i); z.push(j.clone()); diff --git a/src/utils/field.rs b/src/utils/field.rs index 9b9876b..4876271 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -55,15 +55,12 @@ impl FieldElement { let mut result: FieldElement = FieldElement::one(); if exponent == 1 { - eprintln!("special case 1: {:02X?}", self.clone()); - return self; } if exponent == 0 { let result = FieldElement::one(); - eprintln!("Returned value is: {:02X?}", result); return result; } diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 68edb82..3816dac 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -70,8 +70,6 @@ impl Polynomial { }) .collect(); - eprintln!("{:?}", c_array); - for coefficient in c_array { polynomial.push(FieldElement::new( BASE64_STANDARD @@ -97,8 +95,6 @@ impl Polynomial { )]); if exponent == 1 { - eprintln!("special case 1: {:02X?}", self.clone()); - return self; } @@ -107,7 +103,6 @@ impl Polynomial { polynomial_2_block(vec![0], "gcm").unwrap(), )]); - eprintln!("Returned value is: {:02X?}", result); return result; } @@ -159,8 +154,6 @@ impl Polynomial { )]); if exponent == BigUint::one() { - eprintln!("special case 1: {:02X?}", self.clone().div(&modulus).1); - return self.div(&modulus).1; } @@ -169,7 +162,6 @@ impl Polynomial { polynomial_2_block(vec![0], "gcm").unwrap(), )]); - eprintln!("Returned value is: {:02X?}", result); return result; } @@ -213,8 +205,6 @@ impl Polynomial { )]); if exponent == 1 { - eprintln!("special case 1: {:02X?}", self.clone().div(&modulus).1); - return self.div(&modulus).1; } @@ -223,7 +213,6 @@ impl Polynomial { polynomial_2_block(vec![0], "gcm").unwrap(), )]); - eprintln!("Returned value is: {:02X?}", result); return result; } @@ -243,8 +232,6 @@ impl Polynomial { exponent >>= 1; } - eprintln!("result in powmod before reduction: {:02X?}", result); - while !result.polynomial.is_empty() && result .polynomial @@ -257,8 +244,6 @@ impl Polynomial { result.polynomial.pop(); } - eprintln!("result in powmod after reduction: {:02X?}", result); - if result.is_empty() { result = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); } @@ -528,12 +513,6 @@ impl PartialOrd for Polynomial { for (field_a, field_b) in self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) { - eprintln!( - "Poly partord: {:02X?} {:02X?} ", - self.clone().to_c_array(), - other.clone().to_c_array() - ); - match field_a .reverse_bits() .partial_cmp(&field_b.reverse_bits()) @@ -616,10 +595,10 @@ pub fn gfmul(poly_a: &Vec, poly_b: &Vec, semantic: &str) -> Result, poly_b: &Vec, semantic: &str) -> Result, poly_b: &Vec, semantic: &str) -> Result) -> Result> { From 2623bd9a8d9807c56c58e2ef7f83e59e000d9e62 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 29 Nov 2024 19:31:10 +0100 Subject: [PATCH 59/79] refactor: Change initialisations of field elements to be cleaner --- src/utils/poly.rs | 65 +++++++++++++++-------------------------------- 1 file changed, 21 insertions(+), 44 deletions(-) diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 3816dac..969a144 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -32,15 +32,13 @@ impl Polynomial { } pub fn one() -> Self { - Polynomial::new(vec![FieldElement::new( - polynomial_2_block(vec![0], "gcm").unwrap(), - )]) + Polynomial::new(vec![FieldElement::one()]) } pub fn x() -> Self { Polynomial::new(vec![ FieldElement::new(vec![0; 16]), - FieldElement::new(polynomial_2_block(vec![0], "gcm").unwrap()), + FieldElement::new(polynomial_2_block(vec![0], "xex").unwrap()), ]) } @@ -54,7 +52,7 @@ impl Polynomial { } pub fn zero() -> Self { - Polynomial::new(vec![FieldElement::new(vec![0; 16])]) + Polynomial::new(vec![FieldElement::zero()]) } pub fn from_c_array(array: &Value) -> Self { @@ -83,7 +81,7 @@ impl Polynomial { pub fn to_c_array(self) -> Vec { let mut output: Vec = vec![]; for coeff in self.polynomial { - output.push(BASE64_STANDARD.encode(coeff)); + output.push(coeff.to_b64()); } output @@ -209,9 +207,7 @@ impl Polynomial { } if exponent == 0 { - let result = Polynomial::new(vec![FieldElement::new( - polynomial_2_block(vec![0], "gcm").unwrap(), - )]); + let result = Polynomial::new(vec![FieldElement::one()]); return result; } @@ -258,10 +254,7 @@ impl Polynomial { //eprintln!("{:?}, {:?}", self.polynomial.len(), rhs.polynomial.len()); if self.polynomial.len() < rhs.polynomial.len() { - return ( - Polynomial::new(vec![FieldElement::new(vec![0; 16])]), - self.clone(), - ); + return (Polynomial::new(vec![FieldElement::zero()]), self.clone()); } let mut remainder = self.clone(); @@ -270,16 +263,10 @@ impl Polynomial { let divisor_deg = divisor.polynomial.len() - 1; if dividend_deg < divisor_deg { - return ( - Polynomial::new(vec![FieldElement::new( - polynomial_2_block(vec![0; 16], "gcm").unwrap(), - )]), - remainder, - ); + return (Polynomial::new(vec![FieldElement::zero()]), remainder); } - let mut quotient_coeffs = - vec![FieldElement::new(vec![0; 16]); dividend_deg - divisor_deg + 1]; + let mut quotient_coeffs = vec![FieldElement::zero(); dividend_deg - divisor_deg + 1]; while remainder.polynomial.len() >= divisor.polynomial.len() { let deg_diff = remainder.polynomial.len() - divisor.polynomial.len(); @@ -290,7 +277,7 @@ impl Polynomial { quotient_coeffs[deg_diff] = quot_coeff.clone(); - let mut subtrahend = vec![FieldElement::new(vec![0; 16]); deg_diff]; + let mut subtrahend = vec![FieldElement::zero(); deg_diff]; subtrahend.extend( divisor .polynomial @@ -315,7 +302,7 @@ impl Polynomial { } if remainder.is_empty() { - remainder = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + remainder = Polynomial::new(vec![FieldElement::zero()]); } (Polynomial::new(quotient_coeffs), remainder) } @@ -416,10 +403,10 @@ impl Mul for Polynomial { type Output = Self; fn mul(self, rhs: Self) -> Self::Output { if self.is_zero() || rhs.is_zero() { - return Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + return Polynomial::zero(); } let mut polynomial: Vec = - vec![FieldElement::new(vec![0; 16]); self.polynomial.len() + rhs.polynomial.len() - 1]; + vec![FieldElement::zero(); self.polynomial.len() + rhs.polynomial.len() - 1]; for i in 0..self.polynomial.len() { for j in 0..rhs.polynomial.len() { polynomial[i + j] = &polynomial[i + j] @@ -434,10 +421,10 @@ impl Mul for &Polynomial { type Output = Polynomial; fn mul(self, rhs: Self) -> Self::Output { if self.is_zero() || rhs.is_zero() { - return Polynomial::new(vec![FieldElement::new(vec![0])]); + return Polynomial::zero(); } let mut polynomial: Vec = - vec![FieldElement::new(vec![0; 16]); self.polynomial.len() + rhs.polynomial.len() - 1]; + vec![FieldElement::zero(); self.polynomial.len() + rhs.polynomial.len() - 1]; for i in 0..self.polynomial.len() { for j in 0..rhs.polynomial.len() { polynomial[i + j] = &polynomial[i + j] @@ -471,7 +458,7 @@ impl Add for Polynomial { } if polynomial.is_empty() { - return Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + return Polynomial::new(vec![FieldElement::zero()]); } Polynomial::new(polynomial) @@ -514,8 +501,8 @@ impl PartialOrd for Polynomial { self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) { match field_a - .reverse_bits() - .partial_cmp(&field_b.reverse_bits()) + //.reverse_bits() + .partial_cmp(&field_b) .unwrap() { Ordering::Equal => continue, @@ -538,7 +525,10 @@ impl Ord for Polynomial { for (field_a, field_b) in self.as_ref().iter().rev().zip(other.as_ref().iter().rev()) { - match field_a.reverse_bits().cmp(&field_b.reverse_bits()) { + match field_a + //.reverse_bits() + .cmp(&field_b) + { Ordering::Equal => continue, other => return other, } @@ -1115,19 +1105,6 @@ mod tests { //assert_eq!(BASE64_STANDARD.encode(product), "MoAAAAAAAAAAAAAAAAAAAA=="); } - #[test] - fn test_poly_div_01() { - let element1 = - FieldElement::new(BASE64_STANDARD.decode("JAAAAAAAAAAAAAAAAAAAAA==").unwrap()); - - let element2 = - FieldElement::new(BASE64_STANDARD.decode("wAAAAAAAAAAAAAAAAAAAAA==").unwrap()); - - let result = element1 / element2; - - assert_eq!(BASE64_STANDARD.encode(result), "OAAAAAAAAAAAAAAAAAAAAA=="); - } - #[test] fn test_field_poly_div_01() { let json1 = json!([ From 7dbcf20891716b64dc653dc5b57b5903c17d1009 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Fri, 29 Nov 2024 21:12:42 +0100 Subject: [PATCH 60/79] feat/fix: add initial MT and remove extend from div for performance --- Cargo.toml | 2 ++ src/main.rs | 2 +- src/tasks/mod.rs | 71 +++++++++++++++++++++++++++++++++++++--------- src/utils/parse.rs | 4 +-- src/utils/poly.rs | 28 ++++++------------ 5 files changed, 71 insertions(+), 36 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 9cf5fa2..0d58d2b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,8 @@ serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" num = "0.4" rand = "0.8" +threadpool = "1.8" +num_cpus = "1.16.0" [source.crates-io] replace-with = "vendored-sources" diff --git a/src/main.rs b/src/main.rs index fd69ac4..0bb3127 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,7 +14,7 @@ fn main() -> Result<()> { let json = fs::read_to_string(path_to_workload).unwrap(); let workload = kauma::utils::parse::parse_json(json)?; - let response = kauma::tasks::task_distrubute(&workload)?; + let response = kauma::tasks::task_distribute(&workload)?; println!("{}", serde_json::to_string(&response)?); Ok(()) diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index d2c57b7..d86e661 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -185,16 +185,61 @@ pub fn task_deploy(testcase: &Testcase) -> Result { } } -pub fn task_distrubute(testcases: &Testcases) -> Result { +fn task_distribute_mt(testcases: &Testcases) -> Result { + eprintln!("USING MULTITHREADED"); + let mut responses: HashMap = HashMap::new(); + let pool = threadpool::ThreadPool::default(); + let (tx, rx) = std::sync::mpsc::channel(); + for (key, testcase) in testcases.testcases.clone() { + let tx = tx.clone(); + let testcase = testcase.clone(); + pool.execute(move || { + tx.send((key, task_deploy(&testcase))) + .expect("could not send return value of thread to main thread") + }); + } + + for _ in 0..testcases.testcases.len() { + let result = match rx.recv_timeout(std::time::Duration::from_secs(60 * 5)) { + Ok(r) => r, + Err(e) => { + eprintln!("! Job timed out: {e}"); + return Err(e.into()); + } + }; + match result.1 { + Ok(v) => { + let _ = responses.insert(result.0, v); + } + Err(e) => { + eprintln!("! failed to solve a challenge: {e:#}"); + continue; + } + } + } + + Ok(Responses { responses }) +} + +pub fn task_distribute_st(testcases: &Testcases) -> Result { + //eprintln!("USING SINGLETHREADED"); let mut responses: HashMap = HashMap::new(); for (id, testcase) in &testcases.testcases { responses.insert(id.to_owned(), task_deploy(testcase).unwrap()); } - Ok(Responses { - responses: responses, - }) + Ok(Responses { responses }) +} + +pub fn task_distribute(testcases: &Testcases) -> Result { + let cpus = num_cpus::get(); + //TODO: Deactivate MT for now + if cpus > 10000000000 { + task_distribute_mt(testcases) + } else { + task_distribute_st(testcases) + } } #[cfg(test)] @@ -227,7 +272,7 @@ mod tests { let expected = json!({ "responses": { "b856d760-023d-4b00-bad2-15d2b6da22fe": {"block": "ARIAAAAAAAAAAAAAAAAAgA=="}}}); assert_eq!( - serde_json::to_value(task_distrubute(&parsed)?).unwrap(), + serde_json::to_value(task_distribute(&parsed)?).unwrap(), serde_json::to_value(expected).unwrap() ); @@ -251,7 +296,7 @@ mod tests { }); assert_eq!( - serde_json::to_value(task_distrubute(&parsed)?).unwrap(), + serde_json::to_value(task_distribute(&parsed)?).unwrap(), serde_json::to_value(expected).unwrap() ); @@ -266,7 +311,7 @@ mod tests { let expected = json!({ "responses": { "b856d760-023d-4b00-bad2-15d2b6da22fe": {"product": "hSQAAAAAAAAAAAAAAAAAAA=="}}}); assert_eq!( - serde_json::to_value(task_distrubute(&parsed)?).unwrap(), + serde_json::to_value(task_distribute(&parsed)?).unwrap(), serde_json::to_value(expected).unwrap() ); @@ -284,7 +329,7 @@ mod tests { }}); assert_eq!( - serde_json::to_value(task_distrubute(&parsed)?).unwrap(), + serde_json::to_value(task_distribute(&parsed)?).unwrap(), serde_json::to_value(expected).unwrap() ); @@ -304,7 +349,7 @@ mod tests { }}}); assert_eq!( - serde_json::to_value(task_distrubute(&parsed)?).unwrap(), + serde_json::to_value(task_distribute(&parsed)?).unwrap(), serde_json::to_value(expected).unwrap() ); @@ -324,7 +369,7 @@ mod tests { }}}); assert_eq!( - serde_json::to_value(task_distrubute(&parsed)?).unwrap(), + serde_json::to_value(task_distribute(&parsed)?).unwrap(), serde_json::to_value(expected).unwrap() ); @@ -342,7 +387,7 @@ mod tests { }}}); assert_eq!( - serde_json::to_value(task_distrubute(&parsed)?).unwrap(), + serde_json::to_value(task_distribute(&parsed)?).unwrap(), serde_json::to_value(expected).unwrap() ); @@ -360,7 +405,7 @@ mod tests { }}}); assert_eq!( - serde_json::to_value(task_distrubute(&parsed)?).unwrap(), + serde_json::to_value(task_distribute(&parsed)?).unwrap(), serde_json::to_value(expected).unwrap() ); @@ -378,7 +423,7 @@ mod tests { }}}); assert_eq!( - serde_json::to_value(task_distrubute(&parsed)?).unwrap(), + serde_json::to_value(task_distribute(&parsed)?).unwrap(), serde_json::to_value(expected).unwrap() ); diff --git a/src/utils/parse.rs b/src/utils/parse.rs index 6e5d2dd..4b71b29 100644 --- a/src/utils/parse.rs +++ b/src/utils/parse.rs @@ -8,13 +8,13 @@ pub struct Testcases { pub testcases: HashMap, } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct Testcase { pub action: String, pub arguments: Value, } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct Responses { pub responses: HashMap, } diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 969a144..c294ccb 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -247,12 +247,7 @@ impl Polynomial { result } - // Returns (quotient, remainder) pub fn div(&self, rhs: &Self) -> (Self, Self) { - // Div by zero check ommitted since data is guaranteed to be non 0 - - //eprintln!("{:?}, {:?}", self.polynomial.len(), rhs.polynomial.len()); - if self.polynomial.len() < rhs.polynomial.len() { return (Polynomial::new(vec![FieldElement::zero()]), self.clone()); } @@ -270,24 +265,20 @@ impl Polynomial { while remainder.polynomial.len() >= divisor.polynomial.len() { let deg_diff = remainder.polynomial.len() - divisor.polynomial.len(); - let leading_dividend = remainder.polynomial.last().unwrap(); let leading_divisor = divisor.polynomial.last().unwrap(); let quot_coeff = leading_dividend / leading_divisor; - quotient_coeffs[deg_diff] = quot_coeff.clone(); - let mut subtrahend = vec![FieldElement::zero(); deg_diff]; - subtrahend.extend( - divisor - .polynomial - .iter() - .map(|x| x.clone() * quot_coeff.clone()), - ); - let subtrahend_poly = Polynomial::new(subtrahend); - - remainder = remainder + subtrahend_poly; + let mut pos; + for (i, divisor_coeff) in divisor.polynomial.iter().enumerate() { + pos = deg_diff + i; + let a: &FieldElement = &remainder.polynomial[pos]; + let c: &FieldElement = "_coeff; + remainder.polynomial[pos] = a + &(divisor_coeff * c); + } + // Remove trailing zeros while !remainder.polynomial.is_empty() && remainder .polynomial @@ -301,9 +292,6 @@ impl Polynomial { } } - if remainder.is_empty() { - remainder = Polynomial::new(vec![FieldElement::zero()]); - } (Polynomial::new(quotient_coeffs), remainder) } From 3687733b7f04cb47300e06dc6f36f5972a35b511 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 30 Nov 2024 16:07:11 +0100 Subject: [PATCH 61/79] feat: Enable MT --- src/tasks/mod.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index d86e661..a019cfe 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -234,8 +234,7 @@ pub fn task_distribute_st(testcases: &Testcases) -> Result { pub fn task_distribute(testcases: &Testcases) -> Result { let cpus = num_cpus::get(); - //TODO: Deactivate MT for now - if cpus > 10000000000 { + if cpus > 1 { task_distribute_mt(testcases) } else { task_distribute_st(testcases) From 8064dcb9e805c395235c261a3c8cd3bd5ccc5621 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 30 Nov 2024 16:07:39 +0100 Subject: [PATCH 62/79] fix: Fix incorrect dic output. Remainder could be zero. --- src/utils/poly.rs | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/src/utils/poly.rs b/src/utils/poly.rs index c294ccb..7f9cbe6 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -140,7 +140,7 @@ impl Polynomial { //eprintln!("result in powmod after reduction: {:02X?}", result); if result.is_empty() { - result = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + result = Polynomial::zero(); } result @@ -192,7 +192,7 @@ impl Polynomial { } if result.is_empty() { - result = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + result = Polynomial::zero(); } result @@ -241,7 +241,7 @@ impl Polynomial { } if result.is_empty() { - result = Polynomial::new(vec![FieldElement::new(vec![0; 16])]); + result = Polynomial::zero(); } result @@ -278,20 +278,16 @@ impl Polynomial { remainder.polynomial[pos] = a + &(divisor_coeff * c); } - // Remove trailing zeros - while !remainder.polynomial.is_empty() - && remainder - .polynomial - .last() - .unwrap() - .as_ref() - .iter() - .all(|&x| x == 0) + while !remainder.polynomial.is_empty() && remainder.polynomial.last().unwrap().is_zero() { remainder.polynomial.pop(); } } + if remainder.is_empty() { + remainder = Polynomial::zero(); + } + (Polynomial::new(quotient_coeffs), remainder) } From e2ef29bfd53876afce3df0c8f37de04c6c8b2cab Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 30 Nov 2024 21:16:47 +0100 Subject: [PATCH 63/79] refactor: test with MT disabled --- src/tasks/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index a019cfe..d26cbac 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -234,7 +234,7 @@ pub fn task_distribute_st(testcases: &Testcases) -> Result { pub fn task_distribute(testcases: &Testcases) -> Result { let cpus = num_cpus::get(); - if cpus > 1 { + if cpus > 1000000 { task_distribute_mt(testcases) } else { task_distribute_st(testcases) From e8f4a5873236382d9093e40d0e438deb6ada9308 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 30 Nov 2024 23:46:59 +0100 Subject: [PATCH 64/79] fix: Fix error in random polynomial generation in edf Upper bound wa incorrect --- src/tasks/mod.rs | 2 +- src/utils/edf.rs | 23 ++++++++++++++--------- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index d26cbac..0b9fce7 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -234,7 +234,7 @@ pub fn task_distribute_st(testcases: &Testcases) -> Result { pub fn task_distribute(testcases: &Testcases) -> Result { let cpus = num_cpus::get(); - if cpus > 1000000 { + if cpus > 100000 { task_distribute_mt(testcases) } else { task_distribute_st(testcases) diff --git a/src/utils/edf.rs b/src/utils/edf.rs index 72f687d..da05db5 100644 --- a/src/utils/edf.rs +++ b/src/utils/edf.rs @@ -4,30 +4,34 @@ use rand::Rng; use super::poly::{gcd, Polynomial}; pub fn edf(f: Polynomial, d: u32) -> Vec { + eprintln!("edf started: {:?}", f.clone().to_c_array()); let q = BigUint::pow(&BigUint::from_u8(2).unwrap(), 128); let n: u32 = (f.degree() as u32) / (d); let mut z: Vec = vec![f.clone()]; let one_cmp = Polynomial::one(); while (z.len() as u32) < n { - //eprintln!("z len {}", z.len()); - //eprintln!("n len {}", n); + eprintln!("z len {}", z.len()); + eprintln!("n len {}", n); - let h = Polynomial::rand(&rand::thread_rng().gen_range(0..f.degree())); - //eprintln!("h: {:02X?}", h); + let h = Polynomial::rand(&rand::thread_rng().gen_range(1..=f.degree())); + eprintln!("h: {:02X?}", h); let exponent = (q.pow(d) - BigUint::one()) / BigUint::from_u8(3).unwrap(); let g = h.bpow_mod(exponent, &f) + Polynomial::one(); - //eprintln!("g before for {:0X?}", g); + eprintln!("g before for {:0X?}", g); - //eprintln!("z before for {:0X?}", z); + eprintln!("z before for {:0X?}", z); - for i in 0..z.len() { + for i in (0..z.len()).rev() { if z[i].degree() as u32 > d { - //eprintln!("Inside if"); + eprintln!("Inside if"); let j = gcd(&z[i], &g); + eprintln!("j != one_cmp {:?}", j != one_cmp); + eprintln!("j != z[i] {:?}", j != z[i]); + eprintln!("Inside if"); if j != one_cmp && j != z[i] { let intemediate = z[i].div(&j).0; z.remove(i); @@ -37,9 +41,10 @@ pub fn edf(f: Polynomial, d: u32) -> Vec { } } - //eprintln!("z after for {:0X?}", z); + eprintln!("z after for {:0X?}", z); } + eprintln!("edf finished"); z } From 16b65b0de485f34f582eeb32f9c2ac8c649254c3 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sat, 30 Nov 2024 23:47:41 +0100 Subject: [PATCH 65/79] refactor: re-enable multi threading --- src/tasks/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index 0b9fce7..a019cfe 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -234,7 +234,7 @@ pub fn task_distribute_st(testcases: &Testcases) -> Result { pub fn task_distribute(testcases: &Testcases) -> Result { let cpus = num_cpus::get(); - if cpus > 100000 { + if cpus > 1 { task_distribute_mt(testcases) } else { task_distribute_st(testcases) From 4c9adb9fdcbeeb1d71cbd70061b35bca53195daf Mon Sep 17 00:00:00 2001 From: Alivecow Date: Tue, 3 Dec 2024 16:52:21 +0100 Subject: [PATCH 66/79] feat: add the gcm crack Example testcase is working --- src/tasks/mod.rs | 9 +- src/tasks/tasks01/gcm_crack.rs | 197 +++++++++++++++++++++++++++++++++ src/tasks/tasks01/mod.rs | 1 + src/utils/dff.rs | 6 - src/utils/field.rs | 12 ++ src/utils/poly.rs | 10 +- test_json/sandbox.json | 42 ++++--- 7 files changed, 253 insertions(+), 24 deletions(-) create mode 100644 src/tasks/tasks01/gcm_crack.rs diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index a019cfe..aeca1c7 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -6,6 +6,7 @@ use crate::utils::parse::{Responses, Testcase, Testcases}; use tasks01::{ block2poly::block2poly, gcm::{gcm_decrypt, gcm_encrypt}, + gcm_crack::gcm_crack, gfmul::gfmul_task, pad_oracle::padding_oracle, pfmath::{ @@ -176,6 +177,12 @@ pub fn task_deploy(testcase: &Testcase) -> Result { Ok(json) } + "gcm_crack" => { + let result = gcm_crack(args)?; + let json = json!({"factors" : result}); + + Ok(json) + } _ => Err(anyhow!( "Fatal. No compatible action found. Json data was {:?}. Arguments were; {:?}", @@ -234,7 +241,7 @@ pub fn task_distribute_st(testcases: &Testcases) -> Result { pub fn task_distribute(testcases: &Testcases) -> Result { let cpus = num_cpus::get(); - if cpus > 1 { + if cpus > 1000000 { task_distribute_mt(testcases) } else { task_distribute_st(testcases) diff --git a/src/tasks/tasks01/gcm_crack.rs b/src/tasks/tasks01/gcm_crack.rs new file mode 100644 index 0000000..203b029 --- /dev/null +++ b/src/tasks/tasks01/gcm_crack.rs @@ -0,0 +1,197 @@ +use std::{env::args, fs::canonicalize, slice::Chunks}; + +use anyhow::{Ok, Result}; +use base64::{prelude::BASE64_STANDARD, Engine}; +use openssl::derive; +use serde::{Deserialize, Serialize}; +use serde_json::{map, Value}; + +use crate::utils::{ + self, + ciphers::ghash, + dff::ddf, + edf::edf, + field::FieldElement, + math::{reverse_bits_in_bytevec, xor_bytes}, + poly::Polynomial, + sff::sff, +}; + +#[derive(Debug, Serialize, Deserialize, Clone)] +pub struct CrackAnswer { + tag: String, + H: String, + mask: String, +} + +#[derive(Debug, Serialize, Deserialize, Clone)] +struct Message { + ciphertext: Vec, + ad: Vec, + tag: Vec, + l_field: Vec, +} + +fn parse_message(val: &Value) -> Result<(Message, Polynomial)> { + let ciphertext_text: String = serde_json::from_value(val["ciphertext"].clone())?; + let ciphertext_bytes: Vec = BASE64_STANDARD.decode(ciphertext_text)?; + let mut ciphertext_chunks: Vec = ciphertext_bytes + .chunks(16) + .into_iter() + .map(|chunk| FieldElement::new(chunk.to_vec())) + .collect(); + //ciphertext_chunks; + let ciphertext: Polynomial = Polynomial::new(ciphertext_chunks.clone()); + + let ad_text: String = serde_json::from_value(val["associated_data"].clone())?; + let mut ad_bytes: Vec = BASE64_STANDARD.decode(ad_text)?; + let mut l_field: Vec = ((ad_bytes.len() * 8) as u64).to_be_bytes().to_vec(); + + if ad_bytes.len() % 16 != 0 || ad_bytes.is_empty() { + ad_bytes.append(vec![0u8; 16 - (ad_bytes.len() % 16)].as_mut()); + } + let mut ad_chunks: Vec = ad_bytes + .chunks(16) + .into_iter() + .map(|chunk| FieldElement::new(chunk.to_vec())) + .collect(); + //ad_chunks; + let ad: Polynomial = Polynomial::new(ad_chunks.clone()); + + let tag_text: String = serde_json::from_value(val["tag"].clone()).unwrap_or("".to_string()); + let tag_bytes: Vec = BASE64_STANDARD.decode(tag_text)?; + let tag_field: FieldElement = FieldElement::new(tag_bytes.clone()); + let tag: Polynomial = Polynomial::new(vec![tag_field.clone()]); + + let mut c_len: Vec = ((ciphertext_bytes.len() * 8) as u64).to_be_bytes().to_vec(); + l_field.append(c_len.as_mut()); + + // Combine all data + let mut combined: Vec = + Vec::with_capacity(ad_chunks.len() + ciphertext_chunks.len() + 1); + combined.extend(ad_chunks); + combined.extend(ciphertext_chunks.clone()); + combined.push(FieldElement::new(l_field.clone())); + combined.push(tag_field); + + combined.reverse(); + + let h_poly: Polynomial = Polynomial::new(combined); + + Ok(( + Message { + ciphertext: ciphertext_bytes, + ad: ad_bytes, + tag: tag_bytes, + l_field, + }, + h_poly, + )) +} + +pub fn gcm_crack(args: &Value) -> Result { + let nonce: String = serde_json::from_value(args["nonce"].clone())?; + + let crack_poly: Polynomial = Polynomial::empty(); + + // Prepare first equation + let (m1_data, m1_h_poly) = parse_message(&args["m1"])?; + + let (m2_data, m2_h_poly) = parse_message(&args["m2"])?; + + let (m3_data, m3_h_poly) = parse_message(&args["m3"])?; + + eprintln!("m1 poly: {:?}", m1_h_poly.clone().to_c_array()); + eprintln!("m2 poly: {:?}", m2_h_poly.clone().to_c_array()); + + let combine_poly = m1_h_poly + m2_h_poly; + + eprintln!("combine poly: {:?}", combine_poly.clone().to_c_array()); + + let combine_sff = sff(combine_poly.monic()); + + let mut combine_ddf: Vec<(Polynomial, u128)> = vec![]; + for (factor, _) in combine_sff { + combine_ddf.extend(ddf(factor)); + } + + eprintln!("combine_ddf: {:?}", combine_ddf); + + let mut combine_edf: Vec = vec![]; + for (factor, degree) in combine_ddf { + if degree == 1 { + combine_edf.extend(edf(factor, degree as u32)); + } + } + + eprintln!("combine_edf: {:?}", combine_edf); + + let mut m3_auth_tag: Vec = vec![]; + let mut h_candidate: FieldElement = FieldElement::zero(); + let mut eky0: Vec = vec![]; + for candidate in combine_edf { + if candidate.degree() == 1 { + h_candidate = candidate.extract_component(0); + eprintln!("H candidate: {:02X?}", h_candidate.to_b64()); + let m1_ghash = ghash( + reverse_bits_in_bytevec(h_candidate.to_vec()), + m1_data.ad.clone(), + m1_data.ciphertext.clone(), + m1_data.l_field.clone(), + ) + .unwrap(); + + eky0 = xor_bytes(&m1_data.tag, m1_ghash).unwrap(); + eprintln!("eky0: {:?}", BASE64_STANDARD.encode(eky0.clone())); + + let m3_ghash = ghash( + reverse_bits_in_bytevec(h_candidate.to_vec()), + m3_data.ad.clone(), + m3_data.ciphertext.clone(), + m3_data.l_field.clone(), + ) + .unwrap(); + + m3_auth_tag = xor_bytes(&eky0, m3_ghash).unwrap(); + eprintln!( + "M3 auth tag: {:02X?}", + BASE64_STANDARD.encode(m3_auth_tag.clone()) + ); + + if m3_auth_tag == m3_data.tag { + eprintln!("Candidate valid"); + eprintln!("{:02X?}", m3_auth_tag); + break; + } else { + eprintln!("H candidate not valid"); + } + } + } + + eprintln!( + "M3 Authentication TAG {:02X?}", + BASE64_STANDARD.encode(&m3_auth_tag) + ); + + if m3_auth_tag.is_empty() { + eprintln!("No valid candidate found"); + } + + let (forgery_data, _) = parse_message(&args["forgery"])?; + + let forgery_ghash = ghash( + reverse_bits_in_bytevec(h_candidate.to_vec()), + forgery_data.ad.clone(), + forgery_data.ciphertext.clone(), + forgery_data.l_field.clone(), + ) + .unwrap(); + + let forgery_auth_tag = xor_bytes(&eky0, forgery_ghash).unwrap(); + + Ok(CrackAnswer { + tag: BASE64_STANDARD.encode(forgery_auth_tag), + H: h_candidate.to_b64(), + mask: BASE64_STANDARD.encode(eky0), + }) +} diff --git a/src/tasks/tasks01/mod.rs b/src/tasks/tasks01/mod.rs index 8200de5..64d24da 100644 --- a/src/tasks/tasks01/mod.rs +++ b/src/tasks/tasks01/mod.rs @@ -1,5 +1,6 @@ pub mod block2poly; pub mod gcm; +pub mod gcm_crack; pub mod gfmul; pub mod pad_oracle; pub mod pfmath; diff --git a/src/utils/dff.rs b/src/utils/dff.rs index bcd1ca0..4cd4b39 100644 --- a/src/utils/dff.rs +++ b/src/utils/dff.rs @@ -25,20 +25,14 @@ pub fn ddf(f: Polynomial) -> Vec<(Polynomial, u128)> { let g = gcd(&h, &f_star); if g != one_cmp { - eprintln!("d is: {}", d); - eprintln!("g is: {:?}", &g.clone().to_c_array()); - z.push((g.clone(), d)); f_star = f_star.div(&g).0; } - eprintln!("d outer is: {}", d); - eprintln!("F star degree is {:?}", &f_star.degree()); d += 1; } if f_star != one_cmp { - eprintln!("fstar not one"); z.push((f_star.clone(), f_star.degree() as u128)); } else if z.len() == 0 { z.push((f.clone(), 1)); diff --git a/src/utils/field.rs b/src/utils/field.rs index 7d359c8..13029cd 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -39,6 +39,18 @@ impl FieldElement { FieldElement::new_no_convert(vec![0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) } + pub fn to_vec(&self) -> Vec { + self.field_element.clone() + } + + /* + pub fn padd(&mut self) { + if self.field_element.len() % 16 != 0 || ad.is_empty() { + ad.append(vec![0u8; 16 - (ad.len() % 16)].as_mut()); + } + } + */ + pub fn new(field_element: Vec) -> Self { Self { field_element: reverse_bits_in_bytevec(field_element), diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 7f9cbe6..61109f8 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -1,7 +1,7 @@ use crate::utils::field::ByteArray; use base64::prelude::*; -use num::traits::FromBytes; +use num::traits::{FromBytes, ToBytes}; use num::{BigInt, BigUint, One, Zero}; use std::{str::FromStr, u128, u8, usize}; @@ -31,6 +31,10 @@ impl Polynomial { self.polynomial.len() - 1 } + pub fn empty() -> Polynomial { + Polynomial::new(vec![]) + } + pub fn one() -> Self { Polynomial::new(vec![FieldElement::one()]) } @@ -373,6 +377,10 @@ impl Polynomial { self } + + pub fn extract_component(&self, i: u32) -> FieldElement { + self.polynomial[i as usize].clone() + } } impl Clone for Polynomial { diff --git a/test_json/sandbox.json b/test_json/sandbox.json index 836b3c8..e3f5e1f 100644 --- a/test_json/sandbox.json +++ b/test_json/sandbox.json @@ -1,19 +1,29 @@ { - "testcases": { - "sandbox": { - "action": "gfpoly_factor_edf", - "arguments": { - "F": [ - "mmAAAAAAAAAAAAAAAAAAAA==", - "AbAAAAAAAAAAAAAAAAAAAA==", - "zgAAAAAAAAAAAAAAAAAAAA==", - "FwAAAAAAAAAAAAAAAAAAAA==", - "AAAAAAAAAAAAAAAAAAAAAA==", - "wAAAAAAAAAAAAAAAAAAAAA==", - "gAAAAAAAAAAAAAAAAAAAAA==" - ], - "d": 3 - } + "testcases": { + "gcm_crack1": { + "action": "gcm_crack", + "arguments": { + "nonce": "4gF+BtR3ku/PUQci", + "m1": { + "ciphertext": "CGOkZDnJEt24aVV8mqQq+P4pouVDWhAYj0SN5MDAgg==", + "associated_data": "TmFjaHJpY2h0IDE=", + "tag": "GC9neV3aZLnmznTIWqCC4A==" + }, + "m2": { + "ciphertext": "FnWyLSTfRrO8Y1MuhLIs6A==", + "associated_data": "", + "tag": "gb2ph1vzwU85/FsUg51t3Q==" + }, + "m3": { + "ciphertext": "CGOkZDnJEt25aV58iaMt6O8+8chKVh0Eg1XFxA==", + "associated_data": "TmFjaHJpY2h0IDM=", + "tag": "+/aDjsAzTseDLuM4jt5Q6Q==" + }, + "forgery": { + "ciphertext": "AXe/ZQ==", + "associated_data": "" + } + } + } } - } } From b632e0c803560b95e9b53f11207c1092797451d7 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Tue, 3 Dec 2024 17:00:23 +0100 Subject: [PATCH 67/79] refactor: clen edf code --- src/utils/edf.rs | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/src/utils/edf.rs b/src/utils/edf.rs index da05db5..dfb59cf 100644 --- a/src/utils/edf.rs +++ b/src/utils/edf.rs @@ -4,34 +4,21 @@ use rand::Rng; use super::poly::{gcd, Polynomial}; pub fn edf(f: Polynomial, d: u32) -> Vec { - eprintln!("edf started: {:?}", f.clone().to_c_array()); let q = BigUint::pow(&BigUint::from_u8(2).unwrap(), 128); let n: u32 = (f.degree() as u32) / (d); let mut z: Vec = vec![f.clone()]; let one_cmp = Polynomial::one(); while (z.len() as u32) < n { - eprintln!("z len {}", z.len()); - eprintln!("n len {}", n); - let h = Polynomial::rand(&rand::thread_rng().gen_range(1..=f.degree())); - eprintln!("h: {:02X?}", h); let exponent = (q.pow(d) - BigUint::one()) / BigUint::from_u8(3).unwrap(); let g = h.bpow_mod(exponent, &f) + Polynomial::one(); - eprintln!("g before for {:0X?}", g); - - eprintln!("z before for {:0X?}", z); for i in (0..z.len()).rev() { if z[i].degree() as u32 > d { - eprintln!("Inside if"); let j = gcd(&z[i], &g); - eprintln!("j != one_cmp {:?}", j != one_cmp); - eprintln!("j != z[i] {:?}", j != z[i]); - - eprintln!("Inside if"); if j != one_cmp && j != z[i] { let intemediate = z[i].div(&j).0; z.remove(i); @@ -40,11 +27,8 @@ pub fn edf(f: Polynomial, d: u32) -> Vec { } } } - - eprintln!("z after for {:0X?}", z); } - eprintln!("edf finished"); z } From b348c19c6cb6f87cbea3e0e61e48d3436090cac4 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Tue, 3 Dec 2024 17:09:43 +0100 Subject: [PATCH 68/79] refactor: clean up gcm_crack code --- src/tasks/tasks01/gcm_crack.rs | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/src/tasks/tasks01/gcm_crack.rs b/src/tasks/tasks01/gcm_crack.rs index 203b029..d8aab77 100644 --- a/src/tasks/tasks01/gcm_crack.rs +++ b/src/tasks/tasks01/gcm_crack.rs @@ -35,13 +35,11 @@ struct Message { fn parse_message(val: &Value) -> Result<(Message, Polynomial)> { let ciphertext_text: String = serde_json::from_value(val["ciphertext"].clone())?; let ciphertext_bytes: Vec = BASE64_STANDARD.decode(ciphertext_text)?; - let mut ciphertext_chunks: Vec = ciphertext_bytes + let ciphertext_chunks: Vec = ciphertext_bytes .chunks(16) .into_iter() .map(|chunk| FieldElement::new(chunk.to_vec())) .collect(); - //ciphertext_chunks; - let ciphertext: Polynomial = Polynomial::new(ciphertext_chunks.clone()); let ad_text: String = serde_json::from_value(val["associated_data"].clone())?; let mut ad_bytes: Vec = BASE64_STANDARD.decode(ad_text)?; @@ -50,18 +48,15 @@ fn parse_message(val: &Value) -> Result<(Message, Polynomial)> { if ad_bytes.len() % 16 != 0 || ad_bytes.is_empty() { ad_bytes.append(vec![0u8; 16 - (ad_bytes.len() % 16)].as_mut()); } - let mut ad_chunks: Vec = ad_bytes + let ad_chunks: Vec = ad_bytes .chunks(16) .into_iter() .map(|chunk| FieldElement::new(chunk.to_vec())) .collect(); - //ad_chunks; - let ad: Polynomial = Polynomial::new(ad_chunks.clone()); let tag_text: String = serde_json::from_value(val["tag"].clone()).unwrap_or("".to_string()); let tag_bytes: Vec = BASE64_STANDARD.decode(tag_text)?; let tag_field: FieldElement = FieldElement::new(tag_bytes.clone()); - let tag: Polynomial = Polynomial::new(vec![tag_field.clone()]); let mut c_len: Vec = ((ciphertext_bytes.len() * 8) as u64).to_be_bytes().to_vec(); l_field.append(c_len.as_mut()); @@ -90,16 +85,12 @@ fn parse_message(val: &Value) -> Result<(Message, Polynomial)> { } pub fn gcm_crack(args: &Value) -> Result { - let nonce: String = serde_json::from_value(args["nonce"].clone())?; - - let crack_poly: Polynomial = Polynomial::empty(); - // Prepare first equation let (m1_data, m1_h_poly) = parse_message(&args["m1"])?; - let (m2_data, m2_h_poly) = parse_message(&args["m2"])?; + let (_, m2_h_poly) = parse_message(&args["m2"])?; - let (m3_data, m3_h_poly) = parse_message(&args["m3"])?; + let (m3_data, _) = parse_message(&args["m3"])?; eprintln!("m1 poly: {:?}", m1_h_poly.clone().to_c_array()); eprintln!("m2 poly: {:?}", m2_h_poly.clone().to_c_array()); From 6a2f631e4689ab504c354afda5b6ff467ca17db6 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Tue, 3 Dec 2024 17:51:59 +0100 Subject: [PATCH 69/79] fix: Fix the output of mask if mask is empty --- src/tasks/tasks01/gcm_crack.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/tasks/tasks01/gcm_crack.rs b/src/tasks/tasks01/gcm_crack.rs index d8aab77..6cabe38 100644 --- a/src/tasks/tasks01/gcm_crack.rs +++ b/src/tasks/tasks01/gcm_crack.rs @@ -180,6 +180,10 @@ pub fn gcm_crack(args: &Value) -> Result { let forgery_auth_tag = xor_bytes(&eky0, forgery_ghash).unwrap(); + if eky0.is_empty() { + eky0 = vec![0; 16]; + } + Ok(CrackAnswer { tag: BASE64_STANDARD.encode(forgery_auth_tag), H: h_candidate.to_b64(), From 9e31b6cc5b116800d280d23317f8b2eb3a191754 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Tue, 3 Dec 2024 22:58:10 +0100 Subject: [PATCH 70/79] fix: Add ciphertext padding to gcm_crack --- src/tasks/tasks01/gcm_crack.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/tasks/tasks01/gcm_crack.rs b/src/tasks/tasks01/gcm_crack.rs index 6cabe38..5dc2236 100644 --- a/src/tasks/tasks01/gcm_crack.rs +++ b/src/tasks/tasks01/gcm_crack.rs @@ -34,7 +34,10 @@ struct Message { fn parse_message(val: &Value) -> Result<(Message, Polynomial)> { let ciphertext_text: String = serde_json::from_value(val["ciphertext"].clone())?; - let ciphertext_bytes: Vec = BASE64_STANDARD.decode(ciphertext_text)?; + let mut ciphertext_bytes: Vec = BASE64_STANDARD.decode(ciphertext_text)?; + if ciphertext_bytes.len() % 16 != 0 { + ciphertext_bytes.append(vec![0u8; 16 - (ciphertext_bytes.len() % 16)].as_mut()); + } let ciphertext_chunks: Vec = ciphertext_bytes .chunks(16) .into_iter() From 90d61a655ed60e432b40a78cfa8107d090a50fc8 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Tue, 3 Dec 2024 23:15:42 +0100 Subject: [PATCH 71/79] fix: Fix length field implementation in gcm_crack Length field was calculated after padding --- src/tasks/tasks01/gcm_crack.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/tasks/tasks01/gcm_crack.rs b/src/tasks/tasks01/gcm_crack.rs index 5dc2236..05d8886 100644 --- a/src/tasks/tasks01/gcm_crack.rs +++ b/src/tasks/tasks01/gcm_crack.rs @@ -35,9 +35,12 @@ struct Message { fn parse_message(val: &Value) -> Result<(Message, Polynomial)> { let ciphertext_text: String = serde_json::from_value(val["ciphertext"].clone())?; let mut ciphertext_bytes: Vec = BASE64_STANDARD.decode(ciphertext_text)?; + let mut c_len: Vec = ((ciphertext_bytes.len() * 8) as u64).to_be_bytes().to_vec(); + if ciphertext_bytes.len() % 16 != 0 { ciphertext_bytes.append(vec![0u8; 16 - (ciphertext_bytes.len() % 16)].as_mut()); } + let ciphertext_chunks: Vec = ciphertext_bytes .chunks(16) .into_iter() @@ -61,7 +64,6 @@ fn parse_message(val: &Value) -> Result<(Message, Polynomial)> { let tag_bytes: Vec = BASE64_STANDARD.decode(tag_text)?; let tag_field: FieldElement = FieldElement::new(tag_bytes.clone()); - let mut c_len: Vec = ((ciphertext_bytes.len() * 8) as u64).to_be_bytes().to_vec(); l_field.append(c_len.as_mut()); // Combine all data From 7a0d1219f90a2d083da8931c9fcf0977abbba1a3 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Thu, 5 Dec 2024 15:57:18 +0100 Subject: [PATCH 72/79] fix: Fix GCM crack output --- src/tasks/mod.rs | 2 +- src/tasks/tasks01/gcm_crack.rs | 62 +++++++++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index aeca1c7..d48952d 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -179,7 +179,7 @@ pub fn task_deploy(testcase: &Testcase) -> Result { } "gcm_crack" => { let result = gcm_crack(args)?; - let json = json!({"factors" : result}); + let json = json!(result); Ok(json) } diff --git a/src/tasks/tasks01/gcm_crack.rs b/src/tasks/tasks01/gcm_crack.rs index 05d8886..cce3df6 100644 --- a/src/tasks/tasks01/gcm_crack.rs +++ b/src/tasks/tasks01/gcm_crack.rs @@ -54,6 +54,7 @@ fn parse_message(val: &Value) -> Result<(Message, Polynomial)> { if ad_bytes.len() % 16 != 0 || ad_bytes.is_empty() { ad_bytes.append(vec![0u8; 16 - (ad_bytes.len() % 16)].as_mut()); } + let ad_chunks: Vec = ad_bytes .chunks(16) .into_iter() @@ -128,7 +129,6 @@ pub fn gcm_crack(args: &Value) -> Result { for candidate in combine_edf { if candidate.degree() == 1 { h_candidate = candidate.extract_component(0); - eprintln!("H candidate: {:02X?}", h_candidate.to_b64()); let m1_ghash = ghash( reverse_bits_in_bytevec(h_candidate.to_vec()), m1_data.ad.clone(), @@ -170,6 +170,7 @@ pub fn gcm_crack(args: &Value) -> Result { ); if m3_auth_tag.is_empty() { + assert!(false); eprintln!("No valid candidate found"); } @@ -195,3 +196,62 @@ pub fn gcm_crack(args: &Value) -> Result { mask: BASE64_STANDARD.encode(eky0), }) } + +#[cfg(test)] +mod tests { + + use anyhow::Result; + + use rand::Rng; + + use serde_json::json; + use utils::ciphers::{aes_128_encrypt, gcm_encrypt_aes}; + // Note this useful idiom: importing names from outer (for mod tests) scope. + use super::*; + + #[test] + fn test_random() -> Result<()> { + let key = vec![1, 1, 1, 1]; + let nonce = BASE64_STANDARD.decode("4gF+BtR3ku/PUQci")?; + let ad = vec![0]; + + let input: Vec = Vec::with_capacity(rand::thread_rng().gen_range(0..=60)); + let plain1 = gcm_encrypt_aes(nonce.clone(), key.clone(), input, ad.clone())?; + let input: Vec = Vec::with_capacity(rand::thread_rng().gen_range(0..=60)); + let plain2 = gcm_encrypt_aes(nonce.clone(), key.clone(), input, ad.clone())?; + let input: Vec = Vec::with_capacity(rand::thread_rng().gen_range(0..=60)); + let plain3 = gcm_encrypt_aes(nonce.clone(), key.clone(), input, ad.clone())?; + + let crack_input = json!({ + "testcases": { + "gcm_crack46": { + "action": "gcm_crack", + "arguments": { + "nonce": "4gF+BtR3ku/PUQci", + "m1": { + "ciphertext": BASE64_STANDARD.encode(plain1.0), + "associated_data": "", + "tag": BASE64_STANDARD.encode(plain1.1) + }, + "m2": { + "ciphertext": BASE64_STANDARD.encode(plain2.0), + "associated_data": "", + "tag": BASE64_STANDARD.encode(plain2.1) + }, + "m3": { + "ciphertext": BASE64_STANDARD.encode(plain3.0), + "associated_data": "", + "tag": BASE64_STANDARD.encode(plain3.1) + }, + "forgery": { + "ciphertext": "AXe/ZQ==", + "associated_data": "" + } + } + } + } + }); + + todo!(); + } +} From 6d1b735a0ba0aefcb51d3f2df2074cc9d5c158b5 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Thu, 5 Dec 2024 16:37:54 +0100 Subject: [PATCH 73/79] refactor: remove unneded prints and enable mt --- src/tasks/mod.rs | 2 +- src/tasks/tasks01/gcm_crack.rs | 80 ---------------------------------- 2 files changed, 1 insertion(+), 81 deletions(-) diff --git a/src/tasks/mod.rs b/src/tasks/mod.rs index d48952d..8a8b782 100644 --- a/src/tasks/mod.rs +++ b/src/tasks/mod.rs @@ -241,7 +241,7 @@ pub fn task_distribute_st(testcases: &Testcases) -> Result { pub fn task_distribute(testcases: &Testcases) -> Result { let cpus = num_cpus::get(); - if cpus > 1000000 { + if cpus > 1 { task_distribute_mt(testcases) } else { task_distribute_st(testcases) diff --git a/src/tasks/tasks01/gcm_crack.rs b/src/tasks/tasks01/gcm_crack.rs index cce3df6..89788c7 100644 --- a/src/tasks/tasks01/gcm_crack.rs +++ b/src/tasks/tasks01/gcm_crack.rs @@ -98,13 +98,8 @@ pub fn gcm_crack(args: &Value) -> Result { let (m3_data, _) = parse_message(&args["m3"])?; - eprintln!("m1 poly: {:?}", m1_h_poly.clone().to_c_array()); - eprintln!("m2 poly: {:?}", m2_h_poly.clone().to_c_array()); - let combine_poly = m1_h_poly + m2_h_poly; - eprintln!("combine poly: {:?}", combine_poly.clone().to_c_array()); - let combine_sff = sff(combine_poly.monic()); let mut combine_ddf: Vec<(Polynomial, u128)> = vec![]; @@ -112,8 +107,6 @@ pub fn gcm_crack(args: &Value) -> Result { combine_ddf.extend(ddf(factor)); } - eprintln!("combine_ddf: {:?}", combine_ddf); - let mut combine_edf: Vec = vec![]; for (factor, degree) in combine_ddf { if degree == 1 { @@ -121,8 +114,6 @@ pub fn gcm_crack(args: &Value) -> Result { } } - eprintln!("combine_edf: {:?}", combine_edf); - let mut m3_auth_tag: Vec = vec![]; let mut h_candidate: FieldElement = FieldElement::zero(); let mut eky0: Vec = vec![]; @@ -155,8 +146,6 @@ pub fn gcm_crack(args: &Value) -> Result { ); if m3_auth_tag == m3_data.tag { - eprintln!("Candidate valid"); - eprintln!("{:02X?}", m3_auth_tag); break; } else { eprintln!("H candidate not valid"); @@ -164,16 +153,6 @@ pub fn gcm_crack(args: &Value) -> Result { } } - eprintln!( - "M3 Authentication TAG {:02X?}", - BASE64_STANDARD.encode(&m3_auth_tag) - ); - - if m3_auth_tag.is_empty() { - assert!(false); - eprintln!("No valid candidate found"); - } - let (forgery_data, _) = parse_message(&args["forgery"])?; let forgery_ghash = ghash( @@ -196,62 +175,3 @@ pub fn gcm_crack(args: &Value) -> Result { mask: BASE64_STANDARD.encode(eky0), }) } - -#[cfg(test)] -mod tests { - - use anyhow::Result; - - use rand::Rng; - - use serde_json::json; - use utils::ciphers::{aes_128_encrypt, gcm_encrypt_aes}; - // Note this useful idiom: importing names from outer (for mod tests) scope. - use super::*; - - #[test] - fn test_random() -> Result<()> { - let key = vec![1, 1, 1, 1]; - let nonce = BASE64_STANDARD.decode("4gF+BtR3ku/PUQci")?; - let ad = vec![0]; - - let input: Vec = Vec::with_capacity(rand::thread_rng().gen_range(0..=60)); - let plain1 = gcm_encrypt_aes(nonce.clone(), key.clone(), input, ad.clone())?; - let input: Vec = Vec::with_capacity(rand::thread_rng().gen_range(0..=60)); - let plain2 = gcm_encrypt_aes(nonce.clone(), key.clone(), input, ad.clone())?; - let input: Vec = Vec::with_capacity(rand::thread_rng().gen_range(0..=60)); - let plain3 = gcm_encrypt_aes(nonce.clone(), key.clone(), input, ad.clone())?; - - let crack_input = json!({ - "testcases": { - "gcm_crack46": { - "action": "gcm_crack", - "arguments": { - "nonce": "4gF+BtR3ku/PUQci", - "m1": { - "ciphertext": BASE64_STANDARD.encode(plain1.0), - "associated_data": "", - "tag": BASE64_STANDARD.encode(plain1.1) - }, - "m2": { - "ciphertext": BASE64_STANDARD.encode(plain2.0), - "associated_data": "", - "tag": BASE64_STANDARD.encode(plain2.1) - }, - "m3": { - "ciphertext": BASE64_STANDARD.encode(plain3.0), - "associated_data": "", - "tag": BASE64_STANDARD.encode(plain3.1) - }, - "forgery": { - "ciphertext": "AXe/ZQ==", - "associated_data": "" - } - } - } - } - }); - - todo!(); - } -} From 0da047110f94996cbb76fc30e2cdeeaf0beb4bac Mon Sep 17 00:00:00 2001 From: Alivecow Date: Thu, 5 Dec 2024 17:48:31 +0100 Subject: [PATCH 74/79] feat: enable tcp no delay option --- src/tasks/tasks01/pad_oracle.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/tasks/tasks01/pad_oracle.rs b/src/tasks/tasks01/pad_oracle.rs index 4286e37..6ea7d3e 100644 --- a/src/tasks/tasks01/pad_oracle.rs +++ b/src/tasks/tasks01/pad_oracle.rs @@ -29,6 +29,7 @@ pub fn padding_oracle(args: &Value) -> Result> { for chunk in &cipher_chunks { let mut stream = TcpStream::connect(format!("{}:{}", hostname, port))?; + stream.set_nodelay(true).expect("Error on no delay"); stream.set_nonblocking(false)?; // Track value sent to server From 2f0e265ed69adc1a9a8f684eca5dc22f366f2942 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Thu, 5 Dec 2024 18:12:26 +0100 Subject: [PATCH 75/79] refactor: Change vector init in padding oracle --- src/tasks/tasks01/pad_oracle.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tasks/tasks01/pad_oracle.rs b/src/tasks/tasks01/pad_oracle.rs index 6ea7d3e..60356b4 100644 --- a/src/tasks/tasks01/pad_oracle.rs +++ b/src/tasks/tasks01/pad_oracle.rs @@ -57,7 +57,8 @@ pub fn padding_oracle(args: &Value) -> Result> { // Generate attack blocks // TODO: Collect all and send in one - let mut payload: Vec = l_msg.to_vec(); + let mut payload: Vec = Vec::with_capacity(2 + 16 * 265); + payload.extend(l_msg.to_vec()); for j in 0..q_block_count { // Next byte //eprintln!("Sending attack block: {:02X?}", attack_counter); From b24c70342900eb3f994dcc3179925bb96506c3a8 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Sun, 22 Dec 2024 18:13:23 +0100 Subject: [PATCH 76/79] refactor: Apply general cargo recommendations --- src/tasks/tasks01/gcm_crack.rs | 5 +---- src/utils/ciphers.rs | 1 - src/utils/field.rs | 2 -- src/utils/poly.rs | 5 ++--- 4 files changed, 3 insertions(+), 10 deletions(-) diff --git a/src/tasks/tasks01/gcm_crack.rs b/src/tasks/tasks01/gcm_crack.rs index 89788c7..09ccb2c 100644 --- a/src/tasks/tasks01/gcm_crack.rs +++ b/src/tasks/tasks01/gcm_crack.rs @@ -1,13 +1,10 @@ -use std::{env::args, fs::canonicalize, slice::Chunks}; use anyhow::{Ok, Result}; use base64::{prelude::BASE64_STANDARD, Engine}; -use openssl::derive; use serde::{Deserialize, Serialize}; -use serde_json::{map, Value}; +use serde_json::Value; use crate::utils::{ - self, ciphers::ghash, dff::ddf, edf::edf, diff --git a/src/utils/ciphers.rs b/src/utils/ciphers.rs index 82af34b..f147c5a 100644 --- a/src/utils/ciphers.rs +++ b/src/utils/ciphers.rs @@ -1,6 +1,5 @@ use crate::utils::{field::ByteArray, poly::gfmul}; use anyhow::Result; -use base64::prelude::*; use openssl::symm::{Cipher, Crypter, Mode}; use super::math::xor_bytes; diff --git a/src/utils/field.rs b/src/utils/field.rs index 13029cd..b5a65dc 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -8,9 +8,7 @@ use std::{ use anyhow::{anyhow, Ok, Result}; -use crate::utils::poly::bgfmul; -use super::poly::polynomial_2_block; use super::{ math::{reverse_bits_in_bytevec, xor_bytes}, poly::gfmul, diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 61109f8..361108e 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -2,7 +2,7 @@ use crate::utils::field::ByteArray; use base64::prelude::*; use num::traits::{FromBytes, ToBytes}; -use num::{BigInt, BigUint, One, Zero}; +use num::{BigUint, One, Zero}; use std::{str::FromStr, u128, u8, usize}; @@ -15,7 +15,6 @@ use anyhow::{anyhow, Ok, Result}; use serde_json::Value; use super::field::FieldElement; -use super::math::reverse_bits_in_bytevec; #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct Polynomial { @@ -574,7 +573,7 @@ pub fn sort_polynomial_array(mut polys: Vec) -> Result, poly_b: &Vec, semantic: &str) -> Result> { - let mut red_poly_bytes: ByteArray = ByteArray(RED_POLY.to_be_bytes().to_vec()); + let red_poly_bytes: ByteArray = ByteArray(RED_POLY.to_be_bytes().to_vec()); //red_poly_bytes.0.push(0x01); let mut poly1: ByteArray = ByteArray(poly_a.to_vec()); From c9c26b39712112381b9237eeb7839f7d74812439 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Mon, 23 Dec 2024 10:27:23 +0100 Subject: [PATCH 77/79] refactor: remove commented code --- src/tasks/tasks01/block2poly.rs | 1 - src/tasks/tasks01/pad_oracle.rs | 37 -------------------------- src/tasks/tasks01/sea128.rs | 5 ---- src/utils/ciphers.rs | 9 ------- src/utils/field.rs | 23 ---------------- src/utils/poly.rs | 47 ++------------------------------- 6 files changed, 2 insertions(+), 120 deletions(-) diff --git a/src/tasks/tasks01/block2poly.rs b/src/tasks/tasks01/block2poly.rs index 3e636eb..3377bf6 100644 --- a/src/tasks/tasks01/block2poly.rs +++ b/src/tasks/tasks01/block2poly.rs @@ -19,7 +19,6 @@ pub fn block2poly(val: &Value) -> Result> { #[cfg(test)] mod tests { use serde_json::json; - use std::str::FromStr; // Note this useful idiom: importing names from outer (for mod tests) scope. use super::*; diff --git a/src/tasks/tasks01/pad_oracle.rs b/src/tasks/tasks01/pad_oracle.rs index 60356b4..067a55f 100644 --- a/src/tasks/tasks01/pad_oracle.rs +++ b/src/tasks/tasks01/pad_oracle.rs @@ -40,7 +40,6 @@ pub fn padding_oracle(args: &Value) -> Result> { let q_block_count: u16 = 256; //Send the first ciphertext chunk - //eprintln!("Sending Ciphertext chunk: {:002X?}", chunk); stream.flush()?; stream.write_all(&chunk)?; stream.flush()?; @@ -50,10 +49,6 @@ pub fn padding_oracle(args: &Value) -> Result> { // FIXME: Assignment is redundant for now // TODO: Goal is to maybe add speed increase in the future let l_msg: [u8; 2] = q_block_count.to_le_bytes(); - //eprintln!("Sending l_msg: {:02X?}", l_msg); - //stream.write_all(&l_msg)?; - //stream.flush()?; - //eprintln!("L_msg sent"); // Generate attack blocks // TODO: Collect all and send in one @@ -61,14 +56,9 @@ pub fn padding_oracle(args: &Value) -> Result> { payload.extend(l_msg.to_vec()); for j in 0..q_block_count { // Next byte - //eprintln!("Sending attack block: {:02X?}", attack_counter); - - //thread::sleep(Duration::from_millis(1000)); payload.extend(&attack_counter); - //eprintln!("I in q builder {}", i); attack_counter[i as usize] += 1; } - //eprintln!("Time for qblocks: {:?}", start.elapsed()); stream.write_all(&payload)?; stream.flush()?; @@ -76,7 +66,6 @@ pub fn padding_oracle(args: &Value) -> Result> { // Read server response let mut server_q_resp = [0u8; 256]; stream.read_exact(&mut server_q_resp)?; - //eprintln!("{:02X?}", buf); // extract valid position let valid_val = server_q_resp @@ -86,7 +75,6 @@ pub fn padding_oracle(args: &Value) -> Result> { if valid_val == 0x00 { eprintln!("No valid found in main loop"); } - //eprintln!("Valid value found: {:02X?}", valid_val); // Craft next attack vector padding; 0x01, 0x02, ... attack_counter[i as usize] = valid_val; @@ -100,15 +88,10 @@ pub fn padding_oracle(args: &Value) -> Result> { l_msg_check.extend(check_q_block.as_slice()); stream.write_all(&l_msg_check)?; - //stream.write_all(&check_q_block)?; let mut buf = [0u8; 0x01]; stream.read(&mut buf)?; - //eprintln!("I = {}", i); - //eprintln!("Buffer from pad check: {:02X?}", buf); if buf == [0x01] { - //eprintln!("Valid padding"); } else { - //eprintln!("Invalid padding"); // Search for second hit let valid_val = 255 - server_q_resp @@ -119,38 +102,21 @@ pub fn padding_oracle(args: &Value) -> Result> { if valid_val == 0x00 { eprintln!("No valid found"); } - //eprintln!("Valid value found: {:02X?}", valid_val); // Craft next attack vector padding; 0x01, 0x02, ... attack_counter[i as usize] = valid_val; } } if chunk_counter + 1 < cipher_chunks.len() { - //eprintln!("XOR Next Ciph block"); plaintext.push( cipher_chunks[chunk_counter + 1][i] ^ (attack_counter[i as usize] ^ (15 - i as u8 + 1)), ); } else { - //seprintln!("XOR IV"); - plaintext.push(iv[i] ^ (attack_counter[i as usize] ^ (15 - i as u8 + 1))); } - //eprintln!("Attack counter after set: {:02X?}", attack_counter); let range = i; for pos in range..=15 { - //eprintln!("i is: {:02X?}", i); - //eprintln!("i + 1 is: {:02X?}", ((16 - i) as u8).to_le()); - /* - eprintln!( - "attack_counter[pos as usize]: {:02X?}", - attack_counter[pos as usize] - ); - eprintln!( - "attack_counter[pos as usize] ^ 0x02 {:02X?}", - attack_counter[pos as usize] ^ (15 - i as u8 + 1) - ); - */ let intermediate = attack_counter[pos as usize] ^ (15 - i as u8 + 1); attack_counter[pos as usize] = intermediate ^ ((15 - i as u8 + 1) + 1); @@ -159,13 +125,10 @@ pub fn padding_oracle(args: &Value) -> Result> { stream.flush()?; // Write plaintext - //eprintln!("{:02X?}", plaintext); } chunk_counter += 1; stream.flush()?; - // break; drop(stream); - //eprintln!("Time rest of calc: {:?}", start.elapsed()); } plaintext.reverse(); diff --git a/src/tasks/tasks01/sea128.rs b/src/tasks/tasks01/sea128.rs index 6d76909..2a6a7e2 100644 --- a/src/tasks/tasks01/sea128.rs +++ b/src/tasks/tasks01/sea128.rs @@ -6,18 +6,13 @@ use crate::utils::ciphers::{sea_128_decrypt, sea_128_encrypt}; pub fn sea128(args: &Value) -> Result { let key_string: String = serde_json::from_value(args["key"].clone())?; - //let key: &[u8] = b64_2_num(key_string)?.to_ne_bytes(); let key = BASE64_STANDARD.decode(key_string)?; - //eprintln!("{:?}", key); let input_string: String = serde_json::from_value(args["input"].clone())?; - //let plaintexts: &[u8] = &b64_2_num(plaintexts_string)?.to_ne_bytes(); let input = BASE64_STANDARD.decode(input_string)?; let mode: String = serde_json::from_value(args["mode"].clone())?; match mode.as_str() { "encrypt" => { - //eprintln!("{:?}", plaintexts); - let output = BASE64_STANDARD.encode(sea_128_encrypt(&key, &input)?); Ok(output) diff --git a/src/utils/ciphers.rs b/src/utils/ciphers.rs index f147c5a..0b558af 100644 --- a/src/utils/ciphers.rs +++ b/src/utils/ciphers.rs @@ -161,7 +161,6 @@ pub fn gcm_decrypt_aes( let mut counter: u32 = 1; nonce.append(counter.to_be_bytes().to_vec().as_mut()); - //nonce.append(0u8.to_le_bytes().to_vec().as_mut()); let auth_tag_xor = aes_128_encrypt(&key, &nonce)?; @@ -250,7 +249,6 @@ pub fn gcm_decrypt_sea( let mut counter: u32 = 1; nonce.append(counter.to_be_bytes().to_vec().as_mut()); - //nonce.append(0u8.to_le_bytes().to_vec().as_mut()); let auth_tag_xor = sea_128_encrypt(&key, &nonce)?; @@ -324,13 +322,6 @@ pub fn ghash( Ok(inter_loop) } -/* -* let mut bytes: [u8; 16] = [0u8; 16]; - bytes.copy_from_slice(&ciphertext); - let number: u128 = ::from_be_bytes(bytes); - -* */ - #[cfg(test)] mod tests { use super::*; diff --git a/src/utils/field.rs b/src/utils/field.rs index b5a65dc..0a06662 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -8,7 +8,6 @@ use std::{ use anyhow::{anyhow, Ok, Result}; - use super::{ math::{reverse_bits_in_bytevec, xor_bytes}, poly::gfmul, @@ -41,14 +40,6 @@ impl FieldElement { self.field_element.clone() } - /* - pub fn padd(&mut self) { - if self.field_element.len() % 16 != 0 || ad.is_empty() { - ad.append(vec![0u8; 16 - (ad.len() % 16)].as_mut()); - } - } - */ - pub fn new(field_element: Vec) -> Self { Self { field_element: reverse_bits_in_bytevec(field_element), @@ -80,29 +71,18 @@ impl FieldElement { return result; } - //eprintln!("Initial result: {:?}", result); while exponent > 0 { - //eprintln!("Current exponent: {:02X}", exponent); if exponent & 1 == 1 { let temp = &self * &result; - //eprintln!("Mult"); - //eprintln!("After mod: {:?}", temp); result = temp } let temp_square = &self * &self; - // eprintln!("Square"); - // eprintln!("After squaring: {:?}", temp_square); self = temp_square; - //eprintln!("After mod: {:?}", self); exponent >>= 1; } - // eprintln!("result in powmod before reduction: {:02X?}", result); - - // eprintln!("result in powmod after reduction: {:02X?}", result); - result } @@ -111,10 +91,8 @@ impl FieldElement { let mut inverser = INVERSER_START; let mut inverse: Vec = vec![0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - //eprintln!("Inverse start {:02X?}", inverse); while inverser > 0 { - //eprintln!("{:02X}", inverser); if inverser & 1 == 1 { inverse = gfmul(&self.field_element, &inverse, "xex").unwrap(); } @@ -122,7 +100,6 @@ impl FieldElement { self.field_element = gfmul(&self.field_element, &self.field_element, "xex") .expect("Error in sqrmul sqr"); } - //eprintln!("Inverse rhs {:?}", inverse); FieldElement::new_no_convert(inverse) } diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 361108e..90ef5e0 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -1,14 +1,14 @@ use crate::utils::field::ByteArray; use base64::prelude::*; -use num::traits::{FromBytes, ToBytes}; +use num::traits::FromBytes; use num::{BigUint, One, Zero}; use std::{str::FromStr, u128, u8, usize}; use std::{ cmp::Ordering, - ops::{Add, Div, Mul}, + ops::{Add, Mul}, }; use anyhow::{anyhow, Ok, Result}; @@ -107,27 +107,18 @@ impl Polynomial { return result; } - //eprintln!("Initial result: {:?}", result); while exponent > 0 { - //eprintln!("Current exponent: {:02X}", exponent); if exponent & 1 == 1 { let temp = &self * &result; - //eprintln!("Mult"); - //eprintln!("After mod: {:?}", temp); result = temp } let temp_square = &self * &self; - //eprintln!("Square"); - //eprintln!("After squaring: {:?}", temp_square); self = temp_square; - //eprintln!("After mod: {:?}", self); exponent >>= 1; } - //eprintln!("result in powmod before reduction: {:02X?}", result); - while !result.polynomial.is_empty() && result .polynomial @@ -140,8 +131,6 @@ impl Polynomial { result.polynomial.pop(); } - //eprintln!("result in powmod after reduction: {:02X?}", result); - if result.is_empty() { result = Polynomial::zero(); } @@ -166,19 +155,13 @@ impl Polynomial { return result; } - //eprintln!("Initial result: {:?}", result); while &exponent > &BigUint::zero() { - //eprintln!("Current exponent: {:02X}", exponent); if &exponent & BigUint::one() == BigUint::one() { let temp = &self * &result; - //eprintln!("After multiplication: {:?}", temp); result = temp.div(&modulus).1; - //eprintln!("After mod: {:?}", result); } let temp_square = &self * &self; - //eprintln!("After squaring: {:?}", temp_square); self = temp_square.div(&modulus).1; - //eprintln!("After mod: {:?}", self); exponent >>= 1; } @@ -215,19 +198,13 @@ impl Polynomial { return result; } - //eprintln!("Initial result: {:?}", result); while exponent > 0 { - //eprintln!("Current exponent: {:02X}", exponent); if exponent & 1 == 1 { let temp = &self * &result; - //eprintln!("After multiplication: {:?}", temp); result = temp.div(&modulus).1; - //eprintln!("After mod: {:?}", result); } let temp_square = &self * &self; - //eprintln!("After squaring: {:?}", temp_square); self = temp_square.div(&modulus).1; - //eprintln!("After mod: {:?}", self); exponent >>= 1; } @@ -574,13 +551,10 @@ pub const RED_POLY: u128 = 0x87000000_00000000_00000000_00000000; pub fn gfmul(poly_a: &Vec, poly_b: &Vec, semantic: &str) -> Result> { let red_poly_bytes: ByteArray = ByteArray(RED_POLY.to_be_bytes().to_vec()); - //red_poly_bytes.0.push(0x01); let mut poly1: ByteArray = ByteArray(poly_a.to_vec()); - //poly1.0.push(0x00); let mut poly2: ByteArray = ByteArray(poly_b.to_vec()); - //poly2.0.push(0x00); if semantic == "gcm" { poly1.reverse_bits_in_bytevec(); @@ -618,7 +592,6 @@ pub fn gfmul(poly_a: &Vec, poly_b: &Vec, semantic: &str) -> Result, poly_b: &Vec, semantic: &str) -> Result> { - //TODO: Implement gfmul with bigint let red_poly_bytes: BigUint = BigUint::from_slice(&[ 0x87, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 0x01, ]); @@ -627,13 +600,6 @@ pub fn bgfmul(poly_a: &Vec, poly_b: &Vec, semantic: &str) -> Result, poly_b: &Vec, semantic: &str) -> Result> 1; } - /* - if semantic == "gcm" { - result.reverse_bits_in_bytevec(); - } - */ - Ok(result.to_bytes_le()) } @@ -676,8 +636,6 @@ pub fn convert_gcm_to_xex(gcm_poly: Vec) -> Result> { pub fn get_alpha_rep(num: u128) -> String { let powers: Vec = get_coefficients(num); - //println!("{:?}", powers); - let mut alpha_rep = String::new(); if powers.len() == 1 { @@ -704,7 +662,6 @@ pub fn b64_2_num(string: &String) -> Result { pub fn get_coefficients(num: u128) -> Vec { let mut powers: Vec = vec![]; for shift in 0..128 { - //println!("{:?}", ((num >> shift) & 1)); if ((num >> shift) & 1) == 1 { powers.push(shift); } From 848ad15bb8ed531ab246777f76635528b90d2612 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Mon, 23 Dec 2024 10:29:12 +0100 Subject: [PATCH 78/79] refactor: Remove unneded imports --- src/tasks/tasks01/gfmul.rs | 1 - src/tasks/tasks01/pad_oracle.rs | 3 +-- src/tasks/tasks01/poly2block.rs | 2 +- src/utils/dff.rs | 2 +- src/utils/field.rs | 1 - src/utils/poly.rs | 2 +- src/utils/sff.rs | 2 +- 7 files changed, 5 insertions(+), 8 deletions(-) diff --git a/src/tasks/tasks01/gfmul.rs b/src/tasks/tasks01/gfmul.rs index 70ab788..8bca55f 100644 --- a/src/tasks/tasks01/gfmul.rs +++ b/src/tasks/tasks01/gfmul.rs @@ -21,7 +21,6 @@ pub fn gfmul_task(args: &Value) -> Result> { #[cfg(test)] mod tests { use serde_json::json; - use std::str::FromStr; // Note this useful idiom: importing names from outer (for mod tests) scope. use super::*; diff --git a/src/tasks/tasks01/pad_oracle.rs b/src/tasks/tasks01/pad_oracle.rs index 067a55f..234babf 100644 --- a/src/tasks/tasks01/pad_oracle.rs +++ b/src/tasks/tasks01/pad_oracle.rs @@ -54,7 +54,7 @@ pub fn padding_oracle(args: &Value) -> Result> { // TODO: Collect all and send in one let mut payload: Vec = Vec::with_capacity(2 + 16 * 265); payload.extend(l_msg.to_vec()); - for j in 0..q_block_count { + for _j in 0..q_block_count { // Next byte payload.extend(&attack_counter); attack_counter[i as usize] += 1; @@ -140,7 +140,6 @@ pub fn padding_oracle(args: &Value) -> Result> { #[cfg(test)] mod tests { use super::*; - use serde_json::json; #[test] fn test_connection() -> Result<()> { diff --git a/src/tasks/tasks01/poly2block.rs b/src/tasks/tasks01/poly2block.rs index 6d5ad95..7557981 100644 --- a/src/tasks/tasks01/poly2block.rs +++ b/src/tasks/tasks01/poly2block.rs @@ -1,4 +1,4 @@ -use crate::utils::poly::{polynomial_2_block}; +use crate::utils::poly::polynomial_2_block; use anyhow::{Ok, Result}; use serde_json::Value; diff --git a/src/utils/dff.rs b/src/utils/dff.rs index 4cd4b39..21dde69 100644 --- a/src/utils/dff.rs +++ b/src/utils/dff.rs @@ -75,7 +75,7 @@ mod tests { } println!("Result: {:?}", result); - let bit_indices: Vec = vec![0]; + let _bit_indices: Vec = vec![0]; assert!(false) } } diff --git a/src/utils/field.rs b/src/utils/field.rs index 0a06662..739b466 100644 --- a/src/utils/field.rs +++ b/src/utils/field.rs @@ -337,7 +337,6 @@ impl ByteArray { #[cfg(test)] mod tests { use super::*; - use serde_json::json; #[test] fn test_byte_array_shift1() { diff --git a/src/utils/poly.rs b/src/utils/poly.rs index 90ef5e0..f2e7d33 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -788,7 +788,7 @@ mod tests { #[test] fn coeff_to_binary() { let coefficients: Vec = vec![12, 127, 9, 0]; - let b64: &str = "ARIAAAAAAAAAAAAAAAAAgA=="; + let _b64: &str = "ARIAAAAAAAAAAAAAAAAAgA=="; let calculated_num: u128 = coefficient_to_binary(coefficients); assert_eq!( BASE64_STANDARD.encode(calculated_num.to_ne_bytes()), diff --git a/src/utils/sff.rs b/src/utils/sff.rs index e7a154a..de2bef6 100644 --- a/src/utils/sff.rs +++ b/src/utils/sff.rs @@ -86,7 +86,7 @@ mod tests { } println!("{:?}", result); - let bit_indices: Vec = vec![0]; + let _bit_indices: Vec = vec![0]; assert!(false) } } From 0a573d84da8d0984f4ea5d14a04f27c0f7fb14e9 Mon Sep 17 00:00:00 2001 From: Alivecow Date: Mon, 23 Dec 2024 10:30:21 +0100 Subject: [PATCH 79/79] refactor: Remove unused function --- src/utils/poly.rs | 33 --------------------------------- 1 file changed, 33 deletions(-) diff --git a/src/utils/poly.rs b/src/utils/poly.rs index f2e7d33..6a61853 100644 --- a/src/utils/poly.rs +++ b/src/utils/poly.rs @@ -591,39 +591,6 @@ pub fn gfmul(poly_a: &Vec, poly_b: &Vec, semantic: &str) -> Result, poly_b: &Vec, semantic: &str) -> Result> { - let red_poly_bytes: BigUint = BigUint::from_slice(&[ - 0x87, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 0x01, - ]); - - let mut poly1: BigUint = BigUint::from_le_bytes(poly_a); - - let mut poly2: BigUint = BigUint::from_le_bytes(poly_b); - - let mut result: BigUint = BigUint::zero(); - - if (&poly2 & (BigUint::one() << 127)) == BigUint::one() { - result = &result ^ &poly1; - } - poly2 = &poly2 >> 1; - - while &poly2 != &BigUint::zero() { - poly1 = &poly1 << 1; - - if (&poly1 & (BigUint::one() << 127)) == BigUint::one() { - poly1 = &poly1 ^ &red_poly_bytes; - } - - if &poly2 & BigUint::one() == BigUint::one() { - result = &result ^ &poly1; - } - - poly2 = &poly2 >> 1; - } - - Ok(result.to_bytes_le()) -} - pub fn convert_gcm_to_xex(gcm_poly: Vec) -> Result> { let xex_poly = gcm_poly .into_iter()