mycodee_enigma/
enigma.rs

1use crate::rotor::Rotor;
2
3#[derive(Debug, Clone)]
4pub struct Enigma {
5    pub rotors: Vec<Rotor>,
6}
7
8impl Enigma {
9    #[allow(dead_code)]
10    pub fn new(rotors: Vec<Rotor>) -> Enigma {
11        Enigma {
12            rotors
13        }
14    }
15    #[allow(dead_code)]
16    fn encrypt_byte(&mut self, byte: u8) -> u8 {
17        let mut byte = byte;
18        for rotor in self.rotors.iter_mut() {
19            byte += rotor.index as u8;
20
21            rotor.round_up()
22        }
23
24        byte
25    }
26    #[allow(dead_code)]
27    fn decrypt_byte(&mut self, byte: u8) -> u8 {
28        let mut byte = byte;
29        for rotor in self.rotors.iter_mut() {
30            byte -= rotor.index as u8;
31
32            rotor.round_up()
33        }
34
35        byte
36    }
37    #[allow(dead_code)]
38    pub fn encrypt(&mut self, message: String) -> String {
39        let bytes = message.as_bytes();
40        let mut encrypted: Vec<u8> = Vec::with_capacity(bytes.len().clone());
41
42        for byte in bytes.iter() {
43            encrypted.push(self.encrypt_byte(byte.clone()))
44        }
45        for rotor in self.rotors.iter_mut() {
46            rotor.default();
47        }
48        String::from_utf8(encrypted).expect("Failed to encrypted to String convertion")
49    }
50    #[allow(dead_code)]
51    pub fn decrypt(&mut self, message: String) -> String {
52        let bytes = message.as_bytes();
53        let mut decrypted: Vec<u8> = Vec::with_capacity(bytes.len().clone());
54
55        for byte in bytes.iter() {
56            decrypted.push(self.decrypt_byte(byte.clone()))
57        }
58        for rotor in self.rotors.iter_mut() {
59            rotor.default();
60        }
61        String::from_utf8(decrypted).expect("Failed to decrypted to String convertion")
62    }
63
64   
65}