plain-aes 0.1.1

An implementation of Rijndael's cipher, commonly known as AES.
Documentation
use std::fmt;

use crate::CipherVersion;

use super::RIJNDAEL_S_BOX;
/// The round constant lookup table.
const RCON: [u8; 256] = [
    0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
    0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39,
    0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
    0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8,
    0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef,
    0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
    0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b,
    0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
    0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
    0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20,
    0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
    0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
    0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
    0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63,
    0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd,
    0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d,
];
#[derive(Debug)]
/// A set of generated keys to account for each round of the said cipher version encryption/decryption process.
pub struct ExpandedKey {
    content: Vec<u8>,
    original_key: Vec<u8>,
    round_num: usize,
}
#[derive(Debug, PartialEq)]
/// An error produced during a key expansion.
pub enum KeyExpansionError {
    /// The given key's length does not match the cipher version provided.
    InvalidKeyLength { expected: usize, actual: usize },
}

impl fmt::Display for KeyExpansionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl std::error::Error for KeyExpansionError {}
impl ExpandedKey {
    /// Expands the given key based on the specified cipher version.
    pub fn new(cipher_version: &CipherVersion) -> Result<ExpandedKey, KeyExpansionError> {
        let key = cipher_version.key();
        match cipher_version {
            &CipherVersion::Aes128(_, _) => {
                if key.len() != 16 {
                    return Err(KeyExpansionError::InvalidKeyLength {
                        expected: 16,
                        actual: key.len(),
                    });
                }
            }
            &CipherVersion::Aes192(_, _) => {
                if key.len() != 24 {
                    return Err(KeyExpansionError::InvalidKeyLength {
                        expected: 24,
                        actual: key.len(),
                    });
                }
            }
        };
        let mut expanded_key = Vec::new();
        expanded_key.extend(&key);
        let mut rcon_iteration = 1;
        let mut bytes_generated = key.len(); // We've already included the original key.
        let mut temp: [u8; 4] = [0; 4];
        while bytes_generated < cipher_version.expanded_key_size() {
            for i in 0..4 {
                // Load the last 4 keys of the expanded key into the temp variable.
                temp[i] = expanded_key[i + bytes_generated - 4];
            }
            if bytes_generated % key.len() == 0 {
                // Call the core everytime we've generated a new key.
                ExpandedKey::key_schedule_core(&mut temp, rcon_iteration);
                rcon_iteration = rcon_iteration + 1;
            }
            for i in 0..4 {
                expanded_key.push(expanded_key[bytes_generated - key.len()] ^ temp[i]);
                bytes_generated = bytes_generated + 1;
            }
        }
        Ok(ExpandedKey {
            original_key: key,
            content: expanded_key,
            round_num: match cipher_version {
                CipherVersion::Aes128(_, _) => 10,
                CipherVersion::Aes192(_, _) => 12,
            },
        })
    }
    pub fn original_key(&self) -> &Vec<u8> {
        &self.original_key
    }
    pub fn content(&self) -> &Vec<u8> {
        &self.content
    }
    /// The number of rounds used in the chosen cipher version.
    pub fn round_num(&self) -> usize {
        self.round_num
    }
    /// Substitute a word from the key with it's equivalant from Rijndael's S-box.
    ///
    /// A word is a 4 byte sequence.
    fn sub_word(word: &mut [u8; 4]) {
        for i in 0..4 {
            word[i] = RIJNDAEL_S_BOX[word[i] as usize];
        }
    }
    /// Rotate a word of the key by one position to the left.
    fn rot_word(word: &mut [u8; 4]) {
        let tmp = word[0];
        for i in 0..3 {
            word[i] = word[i + 1];
        }
        word[3] = tmp;
    }

    /// AES key schedule core function, applies [ExpandedKey::sub_word], [ExpandedKey::sub_word] and [RCON].
    fn key_schedule_core(word: &mut [u8; 4], rcon_iteration: usize) {
        ExpandedKey::rot_word(word);
        ExpandedKey::sub_word(word);
        word[0] = word[0] ^ RCON[rcon_iteration];
    }
}

#[cfg(test)]
mod tests {
    use crate::ModeOfOperation;

    use super::*;
    #[test]
    /// Mock word taken from the AES standard, Appendix A.1, temp=09cf4f3c.
    fn rot_word_test() {
        let mut mock_word = [0x09, 0xcf, 0x4f, 0x3c];
        let rot_word_expected = [0xcf, 0x4f, 0x3c, 0x09];
        ExpandedKey::rot_word(&mut mock_word);
        assert!(rot_word_expected.iter().eq(&mock_word));
    }

    #[test]
    /// Mock word taken from the AES standard, Appendix A.1, RotWord(temp)=cf4f3c09.
    fn sub_word_test() {
        let mut mock_word = [0xcf, 0x4f, 0x3c, 0x09];
        let sub_word_expected = [0x8a, 0x84, 0xeb, 0x01];
        ExpandedKey::sub_word(&mut mock_word);
        assert!(sub_word_expected.iter().eq(&mock_word));
    }

    #[test]
    /// Mock word taken from the AES standard, Appendix A.1, temp=2a6c7605, Rcon[i/Nk]=2.
    fn key_schedule_core_test() {
        let mut mock_word = [0x2a, 0x6c, 0x76, 0x05];
        let key_schedule_core_expected = [0x52, 0x38, 0x6b, 0xe5];
        ExpandedKey::key_schedule_core(&mut mock_word, 2);
        assert!(key_schedule_core_expected.iter().eq(&mock_word));
    }

    #[test]
    fn expand_key_aes128_test() {
        let mock_key = [
            0x54, 0x68, 0x69, 0x73, 0x20, 0x6C, 0x69, 0x62, 0x20, 0x69, 0x73, 0x20, 0x63, 0x6F,
            0x6F, 0x6C,
        ]; // This lib is cool
        let expand_key_expected = [
            0x54, 0x68, 0x69, 0x73, 0x20, 0x6c, 0x69, 0x62, 0x20, 0x69, 0x73, 0x20, 0x63, 0x6f,
            0x6f, 0x6c, 0xfd, 0xc0, 0x39, 0x88, 0xdd, 0xac, 0x50, 0xea, 0xfd, 0xc5, 0x23, 0xca,
            0x9e, 0xaa, 0x4c, 0xa6, 0x53, 0xe9, 0x1d, 0x83, 0x8e, 0x45, 0x4d, 0x69, 0x73, 0x80,
            0x6e, 0xa3, 0xed, 0x2a, 0x22, 0x05, 0xb2, 0x7a, 0x76, 0xd6, 0x3c, 0x3f, 0x3b, 0xbf,
            0x4f, 0xbf, 0x55, 0x1c, 0xa2, 0x95, 0x77, 0x19, 0x90, 0x8f, 0xa2, 0xec, 0xac, 0xb0,
            0x99, 0x53, 0xe3, 0x0f, 0xcc, 0x4f, 0x41, 0x9a, 0xbb, 0x56, 0x38, 0x65, 0x13, 0x6f,
            0x94, 0xd5, 0x8a, 0x3c, 0x77, 0xda, 0x46, 0x73, 0x36, 0x40, 0xfd, 0x25, 0x11, 0x31,
            0x2c, 0x6a, 0x85, 0xe4, 0xa6, 0x56, 0xf2, 0x3e, 0xe0, 0x25, 0xc4, 0x7e, 0x1d, 0x00,
            0xa2, 0x95, 0x4f, 0x76, 0x27, 0x71, 0xe9, 0x20, 0xd5, 0x4f, 0x09, 0x05, 0x11, 0x31,
            0x14, 0x05, 0xe5, 0x6f, 0x24, 0xf4, 0xc2, 0x1e, 0xcd, 0xd4, 0x17, 0x51, 0xc4, 0xd1,
            0x06, 0x60, 0xd0, 0xd4, 0x2e, 0x1f, 0x6c, 0x9b, 0xec, 0x01, 0xa1, 0x4f, 0xfb, 0x50,
            0x65, 0x9e, 0xfd, 0x30, 0xb5, 0x4a, 0x1c, 0xca, 0xba, 0xcf, 0xf0, 0xcb, 0x1b, 0x80,
            0x0b, 0x9b, 0x7e, 0x1e, 0xf6, 0xab, 0xcb, 0x54,
        ];
        let cipher_version = CipherVersion::Aes128(&mock_key[..], ModeOfOperation::ECB);
        let expand_key_result = ExpandedKey::new(&cipher_version).unwrap();
        assert!(expand_key_expected.iter().eq(expand_key_result.content()));
    }
    #[test]
    fn expand_key_aes128_invalid_key_length() {
        let mock_key = [
            0x54, 0x68, 0x69, 0x73, 0x20, 0x6C, 0x69, 0x62, 0x20, 0x69, 0x73, 0x20, 0x63, 0x6F,
        ]; // Key's length is invalid for AES-128.
        let cipher_version = CipherVersion::Aes128(&mock_key[..], ModeOfOperation::ECB);
        let expand_key_result = ExpandedKey::new(&cipher_version).unwrap_err();
        println!("{}", expand_key_result);
        assert_eq!(
            expand_key_result,
            KeyExpansionError::InvalidKeyLength {
                expected: 16,
                actual: 14
            }
        )
    }
    #[test]
    /// Based on the FIPS test vector.
    fn expand_key_aes192_test() {
        let mock_key = [
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
            0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
        ];
        let expand_key_expected = [
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
            0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x58, 0x46, 0xf2, 0xf9,
            0x5c, 0x43, 0xf4, 0xfe, 0x54, 0x4a, 0xfe, 0xf5, 0x58, 0x47, 0xf0, 0xfa, 0x48, 0x56,
            0xe2, 0xe9, 0x5c, 0x43, 0xf4, 0xfe, 0x40, 0xf9, 0x49, 0xb3, 0x1c, 0xba, 0xbd, 0x4d,
            0x48, 0xf0, 0x43, 0xb8, 0x10, 0xb7, 0xb3, 0x42, 0x58, 0xe1, 0x51, 0xab, 0x04, 0xa2,
            0xa5, 0x55, 0x7e, 0xff, 0xb5, 0x41, 0x62, 0x45, 0x08, 0x0c, 0x2a, 0xb5, 0x4b, 0xb4,
            0x3a, 0x02, 0xf8, 0xf6, 0x62, 0xe3, 0xa9, 0x5d, 0x66, 0x41, 0x0c, 0x08, 0xf5, 0x01,
            0x85, 0x72, 0x97, 0x44, 0x8d, 0x7e, 0xbd, 0xf1, 0xc6, 0xca, 0x87, 0xf3, 0x3e, 0x3c,
            0xe5, 0x10, 0x97, 0x61, 0x83, 0x51, 0x9b, 0x69, 0x34, 0x15, 0x7c, 0x9e, 0xa3, 0x51,
            0xf1, 0xe0, 0x1e, 0xa0, 0x37, 0x2a, 0x99, 0x53, 0x09, 0x16, 0x7c, 0x43, 0x9e, 0x77,
            0xff, 0x12, 0x05, 0x1e, 0xdd, 0x7e, 0x0e, 0x88, 0x7e, 0x2f, 0xff, 0x68, 0x60, 0x8f,
            0xc8, 0x42, 0xf9, 0xdc, 0xc1, 0x54, 0x85, 0x9f, 0x5f, 0x23, 0x7a, 0x8d, 0x5a, 0x3d,
            0xc0, 0xc0, 0x29, 0x52, 0xbe, 0xef, 0xd6, 0x3a, 0xde, 0x60, 0x1e, 0x78, 0x27, 0xbc,
            0xdf, 0x2c, 0xa2, 0x23, 0x80, 0x0f, 0xd8, 0xae, 0xda, 0x32, 0xa4, 0x97, 0x0a, 0x33,
            0x1a, 0x78, 0xdc, 0x09, 0xc4, 0x18, 0xc2, 0x71, 0xe3, 0xa4, 0x1d, 0x5d,
        ];
        let cipher_version = CipherVersion::Aes192(&mock_key[..], ModeOfOperation::ECB);
        let expand_key_result = ExpandedKey::new(&cipher_version).unwrap();
        assert!(expand_key_expected.iter().eq(expand_key_result.content()))
    }
}