Commit a588cf2d authored by jan.koester's avatar jan.koester
Browse files

initial aes

parent a0c84459
Loading
Loading
Loading
Loading

src/aes.cpp

0 → 100644
+393 −0
Changes for src/aes.cpp: 393 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
 * Copyright (c) 2025, Jan Koester jan.koester@gmx.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * Neither the name of the <organization> nor the
 *      names of its contributors may be used to endorse or promote products
 *      derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************/

#include <algorithm>
#include <cstring> // For memcpy or related functions if needed

#include "aes.h"

namespace netplus {

// --- Global AES Tables Definition ---
// You MUST populate these tables with the correct FIPS 197 standard values.
//
// FIPS 197 Standard S-Box
const uint8_t S_BOX[256] = {
    0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
    0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
    0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
    0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
    0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
    0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
    0xd0, 0xee, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f,
    0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3,
    0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19,
    0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b,
    0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4,
    0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae,
    0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b,
    0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d,
    0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28,
    0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb
};

// FIPS 197 Standard Inverse S-Box
const uint8_t INV_S_BOX[256] = {
    0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
    0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
    0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
    0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
    0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
    0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
    0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
    0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
    0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
    0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
    0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
    0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
    0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
    0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
    0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
    0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d
};

// FIPS 197 Standard Rcon (only the first byte of each word is non-zero)
// Rcon[i] = { Rcon_i, 0x00, 0x00, 0x00 }
const uint8_t RCON[10] = {
    0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36
};

// --- Helper Functions ---

// Simple Galois Field multiplication (gmul) for MixColumns
uint8_t aes::gmul(uint8_t a, uint8_t b) const{
    uint8_t p = 0;
    uint8_t hi_bit_set;
    for (int i = 0; i < 8; i++) {
        if ((b & 1) == 1) {
            p ^= a;
        }
        hi_bit_set = (a & 0x80);
        a <<= 1;
        if (hi_bit_set) {
            a ^= 0x1b; /* XOR with 0x11b (Rijndael's irreducible polynomial) */
        }
        b >>= 1;
    }
    return p;
}

// RotWord (Cyclic shift left by 1 byte)
uint32_t aes::rotWord(uint32_t word) {
    return (word << 8) | (word >> 24);
}

// SubWord (Substitutes each byte of the word using the S-Box)
uint32_t aes::subWord(uint32_t word) {
    uint32_t result = 0;
    result |= S_BOX[(word >> 24) & 0xFF] << 24;
    result |= S_BOX[(word >> 16) & 0xFF] << 16;
    result |= S_BOX[(word >> 8) & 0xFF] << 8;
    result |= S_BOX[word & 0xFF];
    return result;
}


// --- Key Expansion ---
void aes::keyExpansion(const key128& key) {
    auto bytesToWord = [] (const uint8_t* bytes) {
        return (static_cast<uint32_t>(bytes[0]) << 24) |
            (static_cast<uint32_t>(bytes[1]) << 16) |
            (static_cast<uint32_t>(bytes[2]) << 8) |
            static_cast<uint32_t>(bytes[3]);
    };

    // Helper to convert a single 32-bit Word into 4 bytes
    auto wordToBytes = [] (uint32_t word, uint8_t* bytes) {
        bytes[0] = static_cast<uint8_t>((word >> 24) & 0xFF);
        bytes[1] = static_cast<uint8_t>((word >> 16) & 0xFF);
        bytes[2] = static_cast<uint8_t>((word >> 8) & 0xFF);
        bytes[3] = static_cast<uint8_t>(word & 0xFF);
    };

    const int Nk = 4; // Key length in Words (128 bits / 32 = 4)
    const int Nr = 10; // Number of rounds
    const int Nb = 4; // Block size in Words (128 bits / 32 = 4)
    const int KEY_WORDS = (Nr + 1) * Nb; // Total words needed: 11 * 4 = 44

    std::vector<uint32_t> w(KEY_WORDS);
    int i = 0;

    // 1. Initialize the first Nk words (W[0] through W[3]) directly from the key
    while (i < Nk) {
        w[i] = bytesToWord(&key[i * 4]);
        i++;
    }

    // 2. Generate the remaining words
    while (i < KEY_WORDS) {
        uint32_t temp = w[i - 1];

        // Apply transformation to the first word of every key (when i is a multiple of Nk, i.e., 4, 8, 12, ...)
        if (i % Nk == 0) {
            // RotWord: Cyclic shift left by 1 byte
            temp = rotWord(temp);

            // SubWord: Substitute each byte using the S-Box
            temp = subWord(temp);

            // XOR with Rcon[i/Nk - 1] (The Rcon table is only 10 bytes long)
            // The Rcon value is only applied to the MSB of the word.
            uint32_t rcon_value = static_cast<uint32_t>(RCON[i / Nk - 1]) << 24;
            temp ^= rcon_value;
        }

        // The new word is the previous word XORed with the word Nk positions before (w[i-Nk])
        w[i] = w[i - Nk] ^ temp;
        i++;
    }

    // 3. Populate m_roundKeys from the generated Words
    m_roundKeys.clear();
    for (int k = 0; k <= Nr; ++k) {
        block128 roundKey(16); // Each round key is 16 bytes
        for (int j = 0; j < Nb; ++j) {
            wordToBytes(w[k * Nb + j], &roundKey[j * 4]);
        }
        m_roundKeys.push_back(roundKey);
    }
}


// --- Constructor ---
aes::aes(const key128& key) {
    if (key.size() != 16) {
        throw std::invalid_argument("aes-128 key must be 16 bytes.");
    }
    keyExpansion(key);
}

// --- Encryption Implementation ---
void aes::addRoundKey(block128& state, const block128& roundKey) const{
    for (int i = 0; i < 16; ++i) {
        state[i] ^= roundKey[i];
    }
}

void aes::subBytes(block128& state) const{
    for (int i = 0; i < 16; ++i) {
        state[i] = S_BOX[state[i]];
    }
}

void aes::shiftRows(block128& state) const{
    // The state is conceptually a 4x4 matrix, stored column-major:
    // [0] [4] [8] [12]
    // [1] [5] [9] [13]
    // [2] [6] [10] [14]
    // [3] [7] [11] [15]

    // We use a temporary array because the shifts must be applied simultaneously.
    uint8_t temp[16];
    std::copy(state.begin(), state.end(), temp);

    // Row 0: No shift
    // temp[0] = state[0], temp[4] = state[4], temp[8] = state[8], temp[12] = state[12];

    // Row 1: Shift left by 1 byte (indices 1, 5, 9, 13)
    // New indices: 5, 9, 13, 1
    state[1] = temp[5];
    state[5] = temp[9];
    state[9] = temp[13];
    state[13] = temp[1];

    // Row 2: Shift left by 2 bytes (indices 2, 6, 10, 14)
    // New indices: 10, 14, 2, 6
    state[2] = temp[10];
    state[6] = temp[14];
    state[10] = temp[2];
    state[14] = temp[6];

    // Row 3: Shift left by 3 bytes (indices 3, 7, 11, 15)
    // New indices: 15, 3, 7, 11
    state[3] = temp[15];
    state[7] = temp[3];
    state[11] = temp[7];
    state[15] = temp[11];
}

// In aes.cpp

void aes::mixColumns(block128& state) const{
    uint8_t temp[16];
    std::copy(state.begin(), state.end(), temp);

    // Iterate over the four columns (c = 0 to 3)
    for (int c = 0; c < 4; ++c) {
        // Shorthands for the original column bytes
        uint8_t s0 = temp[4 * c + 0];
        uint8_t s1 = temp[4 * c + 1];
        uint8_t s2 = temp[4 * c + 2];
        uint8_t s3 = temp[4 * c + 3];

        // The four equations from the matrix multiplication:
        // s'0 = (02)s0 + (03)s1 + (01)s2 + (01)s3
        state[4 * c + 0] = gmul(0x02, s0) ^ gmul(0x03, s1) ^ gmul(0x01, s2) ^ gmul(0x01, s3);

        // s'1 = (01)s0 + (02)s1 + (03)s2 + (01)s3
        state[4 * c + 1] = gmul(0x01, s0) ^ gmul(0x02, s1) ^ gmul(0x03, s2) ^ gmul(0x01, s3);

        // s'2 = (01)s0 + (01)s1 + (02)s2 + (03)s3
        state[4 * c + 2] = gmul(0x01, s0) ^ gmul(0x01, s1) ^ gmul(0x02, s2) ^ gmul(0x03, s3);

        // s'3 = (03)s0 + (01)s1 + (01)s2 + (02)s3
        state[4 * c + 3] = gmul(0x03, s0) ^ gmul(0x01, s1) ^ gmul(0x01, s2) ^ gmul(0x02, s3);
    }
}

block128 aes::encrypt(const block128& plaintext) const {
    block128 state = plaintext;
    const int NUM_ROUNDS = 10;

    // 1. Initial AddRoundKey (Round 0)
    addRoundKey(state, m_roundKeys[0]);

    // 2. Main Rounds (1 to 9)
    for (int i = 1; i < NUM_ROUNDS; ++i) {
        subBytes(state);
        shiftRows(state);
        mixColumns(state);
        addRoundKey(state, m_roundKeys[i]);
    }

    // 3. Final Round (Round 10 - No MixColumns)
    subBytes(state);
    shiftRows(state);
    addRoundKey(state, m_roundKeys[NUM_ROUNDS]);

    return state;
}

// --- Decryption Implementation ---
void aes::invSubBytes(block128& state) const{
    for (int i = 0; i < 16; ++i) {
        state[i] = INV_S_BOX[state[i]];
    }
}

// In aes.cpp

void aes::invShiftRows(block128& state) const{
    // We use a temporary array because the shifts must be applied simultaneously.
    uint8_t temp[16];
    std::copy(state.begin(), state.end(), temp);

    // Row 0: No shift (Indices 0, 4, 8, 12 remain unchanged in 'state')

    // Row 1: Shift right by 1 byte (Indices 1, 5, 9, 13)
    // Original -> New: 13 -> 1, 1 -> 5, 5 -> 9, 9 -> 13
    state[1] = temp[13];
    state[5] = temp[1];
    state[9] = temp[5];
    state[13] = temp[9];

    // Row 2: Shift right by 2 bytes (Indices 2, 6, 10, 14)
    // Original -> New: 10 -> 2, 14 -> 6, 2 -> 10, 6 -> 14
    state[2] = temp[10];
    state[6] = temp[14];
    state[10] = temp[2];
    state[14] = temp[6];

    // Row 3: Shift right by 3 bytes (Indices 3, 7, 11, 15)
    // Original -> New: 7 -> 3, 11 -> 7, 15 -> 11, 3 -> 15
    state[3] = temp[7];
    state[7] = temp[11];
    state[11] = temp[15];
    state[15] = temp[3];
}

// In aes.cpp (Note: The function signature below is NON-const,
// as it must modify the 'state' passed by reference)

void aes::invMixColumns(block128& state) const {
    uint8_t temp[16];
    // Copy the original state to a temporary buffer before modification.
    // This is crucial because modifications to one column depend on the original values
    // of all bytes in that column.
    std::copy(state.begin(), state.end(), temp);

    // Iterate over the four columns (c = 0 to 3)
    for (int c = 0; c < 4; ++c) {
        // Shorthands for the original column bytes (from 'temp')
        uint8_t s0 = temp[4 * c + 0];
        uint8_t s1 = temp[4 * c + 1];
        uint8_t s2 = temp[4 * c + 2];
        uint8_t s3 = temp[4 * c + 3];

        // The four equations from the inverse matrix multiplication:
        // All additions are XORs. gmul is GF(2^8) multiplication.

        // s'0 = (0E)s0 + (0B)s1 + (0D)s2 + (09)s3
        state[4 * c + 0] = gmul(0x0E, s0) ^ gmul(0x0B, s1) ^ gmul(0x0D, s2) ^ gmul(0x09, s3);

        // s'1 = (09)s0 + (0E)s1 + (0B)s2 + (0D)s3
        state[4 * c + 1] = gmul(0x09, s0) ^ gmul(0x0E, s1) ^ gmul(0x0B, s2) ^ gmul(0x0D, s3);

        // s'2 = (0D)s0 + (09)s1 + (0E)s2 + (0B)s3
        state[4 * c + 2] = gmul(0x0D, s0) ^ gmul(0x09, s1) ^ gmul(0x0E, s2) ^ gmul(0x0B, s3);

        // s'3 = (0B)s0 + (0D)s1 + (09)s2 + (0E)s3
        state[4 * c + 3] = gmul(0x0B, s0) ^ gmul(0x0D, s1) ^ gmul(0x09, s2) ^ gmul(0x0E, s3);
    }
}

block128 aes::decrypt(const block128& ciphertext) const {
    block128 state = ciphertext;
    const int NUM_ROUNDS = 10;

    // 1. Initial AddRoundKey (using the last round key)
    addRoundKey(state, m_roundKeys[NUM_ROUNDS]);

    // 2. Inverse Final Round (Round 9)
    invShiftRows(state);
    invSubBytes(state);

    // 3. Inverse Main Rounds (9 down to 1)
    for (int i = NUM_ROUNDS - 1; i >= 1; --i) {
        addRoundKey(state, m_roundKeys[i]);
        invMixColumns(state);
        invShiftRows(state);
        invSubBytes(state);
    }

    // 4. Final AddRoundKey (Round 0)
    addRoundKey(state, m_roundKeys[0]);

    return state;
}

} // namespace netplus

src/aes.h

0 → 100644
+94 −0
Changes for src/aes.h: 94 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
 * Copyright (c) 2025, Jan Koester jan.koester@gmx.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * Neither the name of the <organization> nor the
 *      names of its contributors may be used to endorse or promote products
 *      derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************/

#pragma once

#include <vector>
#include <stdexcept>
#include <cstdint>

namespace netplus {

// Type aliases for clarity (AES operates on 128-bit blocks/keys)
using block128 = std::vector<uint8_t>;
using key128 = std::vector<uint8_t>;

// --- Global AES Tables (Defined in the header for easy access) ---
// Note: You must fill these arrays with the correct 256-byte values.
extern const uint8_t S_BOX[256];
extern const uint8_t INV_S_BOX[256];
extern const uint8_t RCON[10]; // Rcon values for key expansion (only 10 needed for AES-128)

class aes {
private:
    // Stores the expanded round keys (11 keys * 16 bytes = 176 bytes for AES-128)
    std::vector<block128> m_roundKeys;

    // --- Core AES Functions ---

    // Key Expansion and related helpers
    void keyExpansion(const key128& key);
    uint32_t subWord(uint32_t word);
    uint32_t rotWord(uint32_t word);

    // Round operations
    void subBytes(block128& state) const;
    void shiftRows(block128& state) const;
    void mixColumns(block128& state) const;
    void addRoundKey(block128& state, const block128& roundKey) const;

    // Inverse Round operations
    void invSubBytes(block128& state) const;
    void invShiftRows(block128& state) const;
    void invMixColumns(block128& state) const;

    // Helper function for Galois Field multiplication in mixColumns
    uint8_t gmul(uint8_t a, uint8_t b) const;

public:
    /**
     * @brief Constructor for the aes class (AES-128). Performs key expansion.
     * @param key The 128-bit master key (16 bytes).
     */
    explicit aes(const key128& key);

    /**
     * @brief Encrypts a 128-bit block of plaintext.
     * @param plaintext The 16-byte input block.
     * @return The 16-byte ciphertext block.
     */
    block128 encrypt(const block128& plaintext) const;

    /**
     * @brief Decrypts a 128-bit block of ciphertext.
     * @param ciphertext The 16-byte input block.
     * @return The 16-byte plaintext block.
     */
    block128 decrypt(const block128& ciphertext) const;
};

} // namespace netplus
+9 −0
Changes for test/CMakeLists.txt: 9 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -8,7 +8,16 @@ add_executable(des des.cpp)

target_link_libraries(des netplus-static)

add_executable(aes aes.cpp)

target_link_libraries(aes netplus-static)

add_test(
    NAME dest_test
    COMMAND des
)

add_test(
    NAME aes_test
    COMMAND aes
)

test/aes.cpp

0 → 100644
+98 −0
Changes for test/aes.cpp: 98 added lines, 0 removed lines.
Original line number Diff line number Diff line
#include <iostream>
#include <vector>
#include <iomanip>
#include <stdexcept>
#include <algorithm>

#include "../src/aes.h"  // Adjust path as necessary

using namespace netplus;

// --- FIPS 197 AES-128 Test Vector ---

// KEY: 2b7e151628aed2a6abf7158809cf4f3c
const key128 KEY = {
    0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6,
    0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c
};

// PLAINTEXT: 3243f6a8885a308d313198a2e0370734
const block128 PLAINTEXT = {
    0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d,
    0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34
};

// EXPECTED CIPHERTEXT (After one round of encryption): 3925841d02dc09fba28026741ee4b82d
const block128 EXPECTED_CIPHERTEXT = {
    0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb,
    0xa2, 0x80, 0x26, 0x74, 0x1e, 0xe4, 0xb8, 0x2d
};

// EXPECTED PLAINTEXT (After one round of decryption of the Ciphertext)
// This should be the original PLAINTEXT
const block128 EXPECTED_PLAINTEXT = PLAINTEXT;


// Helper function to print a block in hexadecimal
void print_block(const block128& block) {
    for (const auto& byte : block) {
        std::cout << std::hex << std::setw(2) << std::setfill('0') << (int)byte;
    }
    std::cout << std::dec;
}

// Unit Test Function
void test_aes_standard_vector() {
    std::cout << "Running AES Standard Vector Check..." << std::endl;

    // 1. Initialize AES with the test key
    aes cipher(KEY);

    // 2. Encrypt the plaintext
    block128 ciphertext = cipher.encrypt(PLAINTEXT);

    // 3. Verify Encryption
    if (std::equal(ciphertext.begin(), ciphertext.end(), EXPECTED_CIPHERTEXT.begin())) {
        std::cout << "  Encryption PASSED." << std::endl;
    } else {
        std::cout << "  TEST FAILED: Encryption" << std::endl;
        std::cout << "    Expected: ";
        print_block(EXPECTED_CIPHERTEXT);
        std::cout << std::endl;
        std::cout << "    Got:      ";
        print_block(ciphertext);
        std::cout << std::endl;
        exit(1); // Fail the test
    }

    // 4. Decrypt the ciphertext
    block128 plaintext_recovered = cipher.decrypt(ciphertext);

    // 5. Verify Decryption (Roundtrip)
    if (std::equal(plaintext_recovered.begin(), plaintext_recovered.end(), EXPECTED_PLAINTEXT.begin())) {
        std::cout << "  Decryption PASSED (Roundtrip check)." << std::endl;
    } else {
        std::cout << "  TEST FAILED: Decryption Roundtrip" << std::endl;
        std::cout << "    Expected: ";
        print_block(EXPECTED_PLAINTEXT);
        std::cout << std::endl;
        std::cout << "    Got:      ";
        print_block(plaintext_recovered);
        std::cout << std::endl;
        exit(1); // Fail the test
    }
}

int main() {
    try {
        test_aes_standard_vector();
        std::cout << "All AES unit tests passed." << std::endl;
        return 0;
    } catch (const std::exception& e) {
        std::cerr << "AES Test FAILED due to exception: " << e.what() << std::endl;
        return 1;
    } catch (...) {
        std::cerr << "AES Test FAILED due to unknown exception." << std::endl;
        return 1;
    }
}
+4 −6
Changes for test/des.cpp: 4 added lines, 6 removed lines.
Original line number Diff line number Diff line
@@ -284,12 +284,6 @@ int test_3des_standard_vector_check() {
    block64 key3 = hexDecode(K3_HEX);
    block64 plaintext = hexDecode(PLAINTEXT_HEX);

    dump_3des_variants(plaintext,key1,key2,key3,EXPECTED_CIPHERTEXT_HEX);

    netplus::des d1(key1), d2(key2), d3(key3);
    auto ref = d1.encrypt(d2.decrypt(d3.encrypt(plaintext)));
    std::cout << "REF(K1-K2-K3 EDE)=" << hexEncode(ref) << "\n";

    try {
        netplus::trippledes tdes(key1, key2, key3);

@@ -308,6 +302,10 @@ int test_3des_standard_vector_check() {
            "3DES KAT DECRYPT FAILED. Expected: " + PLAINTEXT_HEX + ", Got: " + ptHex)

    } catch (const std::exception& e) {
        dump_3des_variants(plaintext,key1,key2,key3,EXPECTED_CIPHERTEXT_HEX);
        netplus::des d1(key1), d2(key2), d3(key3);
        auto ref = d1.encrypt(d2.decrypt(d3.encrypt(plaintext)));
        std::cout << "REF(K1-K2-K3 EDE)=" << hexEncode(ref) << "\n";
        CTEST_ASSERT(false, std::string("Exception during 3DES KAT: ") + e.what())
    }