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

fixed

parent 53912102
Loading
Loading
Loading
Loading
+143 −110
Changes for src/des.cpp: 143 added lines, 110 removed lines.
Original line number Diff line number Diff line
@@ -28,6 +28,7 @@
#include <numeric>
#include <cstring>
#include <iostream>
#include <iomanip>

#include "des.h"

@@ -38,7 +39,7 @@ using namespace std;
// ==============================================================================
// (Table definitions remain here, outside the class and namespace, or inside an anonymous namespace)
// ... [IP, FP, PC1, SHIFTS, PC2, E, P, S tables remain unchanged]
namespace {
namespace netplus{
    // ... [Permutation and Substitution Tables]
// Initial Permutation (IP) table
const int IP[] = {
@@ -69,9 +70,10 @@ const int SHIFTS[] = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};

// Permuted Choice 2 (PC-2) - selects 48 bits from the 56-bit shifted key
const int PC2[] = {
    14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4,
    26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40,
    51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32
    14,17,11,24, 1, 5, 3,28,15, 6,21,10,
    23,19,12, 4,26, 8,16, 7,27,20,13, 2,
    41,52,31,37,47,55,30,40,51,45,33,48,
    44,49,39,56,34,53,46,42,50,36,29,32
};

// Expansion Permutation (E) - expands 32 bits to 48 bits
@@ -111,7 +113,7 @@ namespace netplus {
    uint64_t vecToU64(const block64& vec) {
        uint64_t val = 0;
        for (size_t i = 0; i < 8; ++i) {
            val = (val << 8) | vec[i];
             val = (val << 8) | vec[i]; // This correctly reads vec[0] as MSB
        }
        return val;
    }
@@ -128,116 +130,123 @@ namespace netplus {
        return vec;
    }

    // Original 64-bit getBit (for 64-bit blocks/keys)
    inline uint64_t getBit(uint64_t block, int bit_pos, int total_bits) {
        int index = total_bits - bit_pos;
        return (block >> index) & 1;
    }
    static inline uint64_t getBitBytesMSB(const uint8_t* bytes, int bit_pos_1based) {
        int bit_index = bit_pos_1based - 1;   // 0..63
        int byte_index = bit_index / 8;        // 0..7
        int bit_in_byte = bit_index % 8;       // 0..7 (MSB first)

    // Overloaded 32-bit getBit (for R-half, 32-bit)
    inline uint64_t getBit(uint32_t block, int bit_pos, int total_bits) {
        int index = total_bits - bit_pos;
        return (block >> index) & 1;
        return (bytes[byte_index] >> (7 - bit_in_byte)) & 1ULL;
    }

    // Original 64-bit setBit (for 64-bit blocks/keys)
    inline void setBit(uint64_t& target, int bit_pos, int total_bits, uint64_t bit_val) {
        int index = total_bits - bit_pos;
        if (bit_val) {
            target |= (1ULL << index);
        } else {
            target &= ~(1ULL << index);
        }

    static inline uint64_t getBitMSB(uint64_t x, int bit_pos_1based, int total_bits) {
        return (x >> (total_bits - bit_pos_1based)) & 1ULL;
    }

    // Overloaded 32-bit setBit (for R-half, 32-bit)
    inline void setBit(uint32_t& target, int bit_pos, int total_bits, uint64_t bit_val) {
        int index = total_bits - bit_pos;
        if (bit_val) {
            target |= (1U << index); // Use 1U for 32-bit mask
        } else {
            target &= ~(1U << index);
    uint64_t permuteBytes(const uint8_t* in, const int* table, int out_len) {
        uint64_t result = 0;
        for (int i = 0; i < out_len; ++i) {
            result <<= 1;
            result |= getBitBytesMSB(in, table[i]);
        }
        return result;
    }

    // ... [permute function remains here, updated to use the appropriate getBit/setBit overload] ...
    uint64_t permute(uint64_t input, const int* table, int out_len, int in_len) {
        uint64_t result = 0;
        for (int i = 0; i < out_len; ++i) {
            uint64_t bit = getBit(input, table[i], in_len);
            setBit(result, i + 1, out_len, bit);
            result <<= 1;
            result |= getBitMSB(input, table[i], in_len);
        }
        return result;
    }

// ... (rest of the des.cpp code)
    uint64_t permuteU64(uint64_t input, const int* table, int out_len, int in_len = 64) {
        if (in_len < 64) input <<= (64 - in_len); // left-align window

        uint8_t bytes[8] = {
            (uint8_t)((input >> 56) & 0xFF),
            (uint8_t)((input >> 48) & 0xFF),
            (uint8_t)((input >> 40) & 0xFF),
            (uint8_t)((input >> 32) & 0xFF),
            (uint8_t)((input >> 24) & 0xFF),
            (uint8_t)((input >> 16) & 0xFF),
            (uint8_t)((input >>  8) & 0xFF),
            (uint8_t)((input >>  0) & 0xFF)
        };

        uint64_t result = 0;
        for (int i = 0; i < out_len; ++i) {
            result <<= 1;
            result |= getBitBytesMSB(bytes, table[i]); // NO offset
        }
        return result;
    }

    // ==============================================================================
    // 3. DES CLASS IMPLEMENTATION (WRAPPED IN netplus)
    // ==============================================================================

    DES::DES(const block64& key) {
    des::des(const block64& key) {
        if (key.size() != 8) {
            throw std::invalid_argument("DES key must be exactly 8 bytes (64 bits).");
        }
        m_masterKey = vecToU64(key);
        generateSubKeys();
        m_masterKey = vecToU64(key);        generateSubKeys();
    }

    DES::~DES() = default;
    des::~des() = default;

    // --- Key Schedule ---

    void DES::generateSubKeys() {
    void netplus::des::generateSubKeys() {
        // 1. Apply PC-1 (64-bit key -> 56-bit key)
        uint64_t key56 = permute(m_masterKey, PC1, 56, 64);

        // CRITICAL FIX: Ensure key56 is exactly 56 bits for clean split
        const uint64_t MASK_56_BIT = 0x00FFFFFFFFFFFFFFULL;
        key56 &= MASK_56_BIT;

        // Split into C0 (MSB 28 bits) and D0 (LSB 28 bits)
        uint32_t C = (key56 >> 28) & 0x0FFFFFFF;
        uint32_t D = key56 & 0x0FFFFFFF;
        uint32_t C = static_cast<uint32_t>((key56 >> 28) & 0x0FFFFFFF);
        uint32_t D = static_cast<uint32_t>(key56 & 0x0FFFFFFF);

        m_roundKeys.resize(16);
        const uint32_t MASK_28_BIT = 0x0FFFFFFF;

        for (int i = 0; i < 16; ++i) {
            // 2. Circular Left Shift
            int shift = SHIFTS[i];

            C = ((C << shift) | (C >> (28 - shift))) & 0x0FFFFFFF;
            D = ((D << shift) | (D >> (28 - shift))) & 0x0FFFFFFF;
            // CANONICAL 28-BIT CIRCULAR LEFT SHIFT
            // Performs rotation and masks the result to guarantee only 28 bits remain.
            C = ((C << shift) | (C >> (28 - shift))) & MASK_28_BIT;
            D = ((D << shift) | (D >> (28 - shift))) & MASK_28_BIT;

            // 3. Combine C and D (56 bits)
            uint64_t CD56 = (static_cast<uint64_t>(C) << 28) | D;

            uint64_t CD56 = ((static_cast<uint64_t>(C) << 28) | D) & 0x00FFFFFFFFFFFFFFULL;
            // 4. Apply PC-2 (56-bit key -> 48-bit round key)
            uint64_t roundKey48 = permute(CD56, PC2, 48, 56);

            // Store the 48-bit key as a 6-byte vector (block64)
            block64 key_vec(6);
            for(int j = 0; j < 6; ++j) {
                key_vec[j] = static_cast<uint8_t>((roundKey48 >> (40 - j * 8)) & 0xFF);
            // Store the 48-bit key as a 6-byte vector (block64), MSB first
            m_roundKeys48[i] = roundKey48 & 0xFFFFFFFFFFFFULL;
        }
            m_roundKeys[i] = key_vec;
    }
    }

    // --- Permutation Steps ---

    block64 DES::initialPermutation(const block64& block) const {
        uint64_t u64_block = vecToU64(block);
        uint64_t permuted = permute(u64_block, IP, 64, 64);
        return u64ToVec(permuted);
    // In des::initialPermutation:
    uint64_t des::initialPermutation(const block64& block) const {
        return permuteBytes(block.data(), IP, 64);
    }

    block64 DES::finalPermutation(const block64& block) const {
        uint64_t u64_block = vecToU64(block);
        uint64_t permuted = permute(u64_block, FP, 64, 64);
        return u64ToVec(permuted);
    // In des::finalPermutation:
    block64 des::finalPermutation(const uint64_t preoutput) const {
        block64 out(8);
        uint64_t p = permuteU64(preoutput, FP, 64); // or use byte variant
        for (int i = 7; i >= 0; --i) {
            out[i] = p & 0xFF;
            p >>= 8;
        }
        return out;
    }

    // --- Feistel Function (F) ---

    block64 DES::feistelFunction(const block64& rightHalf, const block64& roundKey) const {
    // This method is part of the netplus::DES class in des.cpp
    netplus::block64 netplus::des::feistelFunction(const netplus::block64& rightHalf,uint64_t roundKey48) const {

        // Right half is 32 bits (4 bytes)
        uint32_t R = (static_cast<uint32_t>(rightHalf[0]) << 24) |
                    (static_cast<uint32_t>(rightHalf[1]) << 16) |
@@ -245,38 +254,34 @@ namespace netplus {
                    static_cast<uint32_t>(rightHalf[3]);

        // 1. Expansion Permutation (E) - 32 bits to 48 bits
        uint64_t E_expanded = 0;
        for (int i = 0; i < 48; ++i) {
            uint64_t bit = getBit(R, E[i], 32);
            setBit(E_expanded, i + 1, 48, bit);
        }
        uint64_t E_expanded = permute(static_cast<uint64_t>(R), E, 48, 32) & 0xFFFFFFFFFFFFULL;

        // 2. XOR with Round Key (48 bits)
        uint64_t K_round = vecToU64(roundKey) >> 8;
        uint64_t B = E_expanded ^ K_round;
        uint64_t K_round = roundKey48 & 0xFFFFFFFFFFFFULL;
        uint64_t B = (E_expanded & 0xFFFFFFFFFFFFULL) ^ K_round;

        // 3. S-Box Substitution (48 bits -> 32 bits)
        // 3. S-Box Substitution (48 -> 32), MSB-first
        uint32_t S_output = 0;
        for (int i = 0; i < 8; ++i) { // 8 S-boxes
            uint8_t box_input = static_cast<uint8_t>((B >> (42 - i * 6)) & 0x3F);

        for (int i = 0; i < 8; ++i) {
            // S1 takes the top 6 bits, S8 takes the bottom 6 bits
            uint8_t box_input = static_cast<uint8_t>((B >> (42 - 6*i)) & 0x3F);

            int row = ((box_input & 0x20) >> 4) | (box_input & 0x01);
            int col = (box_input >> 1) & 0x0F;
            int col = (box_input & 0x1E) >> 1;

            uint32_t sub_val = S[i][row * 16 + col];
            uint32_t sub_val = static_cast<uint32_t>(S[i][row * 16 + col]);

            S_output |= (sub_val << (28 - i * 4));
            // pack nibbles MSB-first into 32-bit
            S_output |= (sub_val << (28 - 4*i));
        }


        // 4. P-Box Permutation (32 bits)
        uint32_t P_permuted = 0;
        for (int i = 0; i < 32; ++i) {
            uint64_t bit = getBit(S_output, P[i], 32);
            setBit(P_permuted, i + 1, 32, bit);
        }
        uint32_t P_permuted = static_cast<uint32_t>(permute(static_cast<uint64_t>(S_output), P, 32, 32));


        // Convert 32-bit result back to block64 (4 bytes)
        block64 result(4);
        netplus::block64 result(4);
        result[0] = static_cast<uint8_t>((P_permuted >> 24) & 0xFF);
        result[1] = static_cast<uint8_t>((P_permuted >> 16) & 0xFF);
        result[2] = static_cast<uint8_t>((P_permuted >> 8) & 0xFF);
@@ -285,15 +290,12 @@ namespace netplus {
        return result;
    }

    // --- Main DES Operations ---

    block64 DES::encrypt(const block64& plaintext) const {
    block64 des::encrypt(const block64& plaintext) const {
        if (plaintext.size() != 8) {
            throw std::invalid_argument("Plaintext block must be 8 bytes (64 bits).");
        }

        // 1. Initial Permutation (IP)
        block64 currentBlock = initialPermutation(plaintext);
        block64 currentBlock = u64ToVec(initialPermutation(plaintext));

        // Split into L0 (Left) and R0 (Right) (32 bits / 4 bytes each)
        block64 L(currentBlock.begin(), currentBlock.begin() + 4);
@@ -301,16 +303,32 @@ namespace netplus {

        // 2. 16 Rounds of Feistel Network
        for (int i = 0; i < 16; ++i) {
            block64 tempL = L;
            // Step 1: Get the previous L-half (L_i-1) as a 32-bit integer (for XOR in step 4)
            uint32_t L_prev_u32 = (static_cast<uint32_t>(L[0]) << 24) |
                                (static_cast<uint32_t>(L[1]) << 16) |
                                (static_cast<uint32_t>(L[2]) << 8) |
                                static_cast<uint32_t>(L[3]);

            // Step 2: L_i = R_i-1 (The standard swap)
            L = R;

            block64 feistelResult = feistelFunction(R, m_roundKeys[i]);
            // Step 3: Calculate F = f(R_i-1, K_i)
            block64 feistelResult = feistelFunction(R, m_roundKeys48[i]);

            for(size_t j = 0; j < tempL.size(); ++j) {
                tempL[j] ^= feistelResult[j];
            }
            R = tempL;
            // Step 4a: Convert F-result to a 32-bit integer
            uint32_t F_u32 = (static_cast<uint32_t>(feistelResult[0]) << 24) |
                            (static_cast<uint32_t>(feistelResult[1]) << 16) |
                            (static_cast<uint32_t>(feistelResult[2]) << 8) |
                            static_cast<uint32_t>(feistelResult[3]);

            // Step 4b: R_i = L_i-1 XOR F
            uint32_t R_new_u32 = L_prev_u32 ^ F_u32;

            // Step 5: Convert the new R-half back to the block64 R vector
            R[0] = static_cast<uint8_t>((R_new_u32 >> 24) & 0xFF);
            R[1] = static_cast<uint8_t>((R_new_u32 >> 16) & 0xFF);
            R[2] = static_cast<uint8_t>((R_new_u32 >> 8) & 0xFF);
            R[3] = static_cast<uint8_t>(R_new_u32 & 0xFF);
        }

        // 3. Final Swap (The Feistel network ends with R_16 || L_16)
@@ -318,17 +336,15 @@ namespace netplus {
        combinedBlock.insert(combinedBlock.end(), L.begin(), L.end());

        // 4. Final Permutation (Inverse IP)
        return finalPermutation(combinedBlock);
        return finalPermutation(vecToU64(combinedBlock));
    }

    block64 DES::decrypt(const block64& ciphertext) const {
    block64 des::decrypt(const block64& ciphertext) const {
        if (ciphertext.size() != 8) {
            throw std::invalid_argument("Ciphertext block must be 8 bytes (64 bits).");
        }

        // Decryption is the same as encryption, but with round keys used in reverse order.

        block64 currentBlock = initialPermutation(ciphertext);
        block64 currentBlock = u64ToVec(initialPermutation(ciphertext));

        // Split into L0 (Left) and R0 (Right) (32 bits / 4 bytes each)
        block64 L(currentBlock.begin(), currentBlock.begin() + 4);
@@ -336,16 +352,33 @@ namespace netplus {

        // 2. 16 Rounds, using keys K_16 down to K_1
        for (int i = 15; i >= 0; --i) {
            block64 tempL = L;
            // Step 1: Get the previous L-half (L_i-1) as a 32-bit integer (for XOR in step 4)
            uint32_t L_prev_u32 = (static_cast<uint32_t>(L[0]) << 24) |
                                (static_cast<uint32_t>(L[1]) << 16) |
                                (static_cast<uint32_t>(L[2]) << 8) |
                                static_cast<uint32_t>(L[3]);

            // Step 2: L_i = R_i-1 (The standard swap)
            L = R;

            block64 feistelResult = feistelFunction(R, m_roundKeys[i]);
            // Step 3: Calculate F = f(R_i-1, K_i)
            // The m_roundKeys[i] is K_16 down to K_1
            block64 feistelResult = feistelFunction(R, m_roundKeys48[i]);

            for(size_t j = 0; j < tempL.size(); ++j) {
                tempL[j] ^= feistelResult[j];
            }
            R = tempL;
            // Step 4a: Convert F-result to a 32-bit integer
            uint32_t F_u32 = (static_cast<uint32_t>(feistelResult[0]) << 24) |
                            (static_cast<uint32_t>(feistelResult[1]) << 16) |
                            (static_cast<uint32_t>(feistelResult[2]) << 8) |
                            static_cast<uint32_t>(feistelResult[3]);

            // Step 4b: R_i = L_i-1 XOR F
            uint32_t R_new_u32 = L_prev_u32 ^ F_u32;

            // Step 5: Convert the new R-half back to the block64 R vector
            R[0] = static_cast<uint8_t>((R_new_u32 >> 24) & 0xFF);
            R[1] = static_cast<uint8_t>((R_new_u32 >> 16) & 0xFF);
            R[2] = static_cast<uint8_t>((R_new_u32 >> 8) & 0xFF);
            R[3] = static_cast<uint8_t>(R_new_u32 & 0xFF);
        }

        // 3. Final Swap (R_16 || L_16)
@@ -353,6 +386,6 @@ namespace netplus {
        combinedBlock.insert(combinedBlock.end(), L.begin(), L.end());

        // 4. Final Permutation (Inverse IP)
        return finalPermutation(combinedBlock);
        return finalPermutation(vecToU64(combinedBlock));
    }
} // namespace netplus
+8 −15
Changes for src/des.h: 8 added lines, 15 removed lines.
Original line number Diff line number Diff line
@@ -25,12 +25,7 @@

#pragma once

#include <iostream>
#include <cstdint>
#include <vector>
#ifndef DES_H
#define DES_H

#include <array>
#include <iostream>
#include <cstdint>
#include <vector>
@@ -43,16 +38,16 @@ namespace netplus {
    /**
     * @brief Implements the Data Encryption Standard (DES) algorithm.
     */
    class DES {
    class des {
    public:
        /**
         * @brief Constructor for the DES class.
         * @param key The 64-bit key (only 56 bits are used, 8 bits are parity).
         */
        DES(const block64& key);
        des(const block64& key);

        // Destructor
        ~DES();
        ~des();

        /**
         * @brief Encrypts a 64-bit data block.
@@ -70,14 +65,12 @@ namespace netplus {

    private:
        uint64_t m_masterKey;
        std::vector<block64> m_roundKeys; // Storage for 16 round keys (48-bit, stored as 6-byte block64)
        std::array<uint64_t, 16> m_roundKeys48{}; // Storage for 16 round keys (48-bit, stored as 6-byte block64)

        // --- Core DES Algorithm Steps ---
        void generateSubKeys();
        block64 initialPermutation(const block64& block) const;
        block64 finalPermutation(const block64& block) const;
        block64 feistelFunction(const block64& rightHalf, const block64& roundKey) const;
        uint64_t initialPermutation(const block64& block) const;
        block64 finalPermutation(const uint64_t preoutput) const;
        block64 feistelFunction(const block64& rightHalf,uint64_t roundKey48) const;
    };
} // namespace netplus

#endif // DES_H
+6 −6
Changes for test/des.cpp: 6 added lines, 6 removed lines.
Original line number Diff line number Diff line
@@ -87,7 +87,7 @@ int test_key_size_validation() {
    bool exceptionCaught = false;

    try {
        DES des(invalidKey); // netplus::DES
        netplus::des des(invalidKey); // netplus::DES
    } catch (const std::invalid_argument& e) {
        exceptionCaught = true;
    } catch (...) {
@@ -101,7 +101,7 @@ int test_key_size_validation() {
    exceptionCaught = false;

    try {
        DES des(validKey); // netplus::DES
        netplus::des des(validKey); // netplus::DES
    } catch (const std::invalid_argument& e) {
        exceptionCaught = true;
    } catch (...) {
@@ -116,7 +116,7 @@ int test_key_size_validation() {
int test_encryption_roundtrip() {
    std::cout << "Running test_encryption_roundtrip..." << std::endl;

    const std::string KEY_HEX = "133457799BBCCDFF";
    const std::string KEY_HEX = "133457799BBCDFF1";
    const std::string PLAINTEXT_HEX = "0123456789ABCDEF";

    // Updated to use block64
@@ -124,7 +124,7 @@ int test_encryption_roundtrip() {
    block64 plaintext = hexDecode(PLAINTEXT_HEX);

    try {
        DES des(key); // netplus::DES
        netplus::des des(key); // netplus::DES

        block64 ciphertext = des.encrypt(plaintext);
        CTEST_ASSERT(ciphertext.size() == 8, "Ciphertext size is not 8 bytes.")
@@ -149,7 +149,7 @@ int test_encryption_roundtrip() {
int test_standard_vector_check() {
    std::cout << "Running test_standard_vector_check..." << std::endl;

    const std::string KEY_HEX = "133457799BBCCDFF";
    const std::string KEY_HEX = "133457799BBCDFF1";
    const std::string PLAINTEXT_HEX = "0123456789ABCDEF";
    const std::string EXPECTED_CIPHERTEXT_HEX = "85E813540F0AB405"; // NIST SP 800-67 Rev. 2

@@ -158,7 +158,7 @@ int test_standard_vector_check() {
    block64 plaintext = hexDecode(PLAINTEXT_HEX);

    try {
        DES des(key); // netplus::DES
        netplus::des des(key); // netplus::DES
        block64 actualCiphertext = des.encrypt(plaintext);

        std::string actualHex = hexEncode(actualCiphertext);