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

added des

parent 5bbbfdb1
Loading
Loading
Loading
Loading

src/des.cpp

0 → 100644
+358 −0
Changes for src/des.cpp: 358 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 <stdexcept>
#include <algorithm>
#include <numeric>
#include <cstring>
#include <iostream>

#include "des.h"

using namespace std;

// ==============================================================================
// 1. DES PERMUTATION AND SUBSTITUTION TABLES (UNMODIFIED)
// ==============================================================================
// (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 {
    // ... [Permutation and Substitution Tables]
// Initial Permutation (IP) table
const int IP[] = {
    58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4,
    62, 54, 46, 38, 30, 22, 14, 6, 64, 56, 48, 40, 32, 24, 16, 8,
    57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3,
    61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7
};

// Final Permutation (Inverse IP) table
const int FP[] = {
    40, 8, 48, 16, 56, 24, 64, 32, 39, 7, 47, 15, 55, 23, 63, 31,
    38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29,
    36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27,
    34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25
};

// Permuted Choice 1 (PC-1) - selects 56 bits from the 64-bit key
const int PC1[] = {
    57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2,
    59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39,
    31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37,
    29, 21, 13, 5, 28, 20, 12, 4
};

// Shift schedule for the 16 rounds
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
};

// Expansion Permutation (E) - expands 32 bits to 48 bits
const int E[] = {
    32, 1, 2, 3, 4, 5, 4, 5, 6, 7, 8, 9, 8, 9, 10, 11,
    12, 13, 12, 13, 14, 15, 16, 17, 16, 17, 18, 19, 20, 21, 20, 21,
    22, 23, 24, 25, 24, 25, 26, 27, 28, 29, 28, 29, 30, 31, 32, 1
};

// Permutation P
const int P[] = {
    16, 7, 20, 21, 29, 12, 28, 17, 1, 15, 23, 26, 5, 18, 31, 10,
    2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25
};

// S-Boxes (8 boxes, each 4x16 -> 64 values)
const int S[8][64] = {
    {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13},
    {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9},
    {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12},
    {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14},
    {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3},
    {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13},
    {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12},
    {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}
};
} // end anonymous namespace

// ==============================================================================
// 2. BIT MANIPULATION HELPERS (UPDATED TO USE netplus::block64)
// ==============================================================================

namespace netplus {
    /**
     * @brief Converts a 64-bit vector (block64) into a 64-bit unsigned integer (uint64_t).
     */
    uint64_t vecToU64(const block64& vec) {
        uint64_t val = 0;
        for (size_t i = 0; i < 8; ++i) {
            val = (val << 8) | vec[i];
        }
        return val;
    }

    /**
     * @brief Converts a 64-bit unsigned integer (uint64_t) into a 64-bit vector (block64).
     */
    block64 u64ToVec(uint64_t val) {
        block64 vec(8);
        for (int i = 7; i >= 0; --i) {
            vec[i] = static_cast<uint8_t>(val & 0xFF);
            val >>= 8;
        }
        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;
    }

    // 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;
    }

    // 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);
        }
    }

    // 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);
        }
    }

    // ... [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);
        }
        return result;
    }

// ... (rest of the des.cpp code)


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

    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();
    }

    DES::~DES() = default;

    // --- Key Schedule ---

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

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

        m_roundKeys.resize(16);

        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;

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

            // 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);
            }
            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);
    }

    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);
    }

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

    block64 DES::feistelFunction(const block64& rightHalf, const block64& roundKey) 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) |
                     (static_cast<uint32_t>(rightHalf[2]) << 8) |
                     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);
        }

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

        // 3. S-Box Substitution (48 bits -> 32 bits)
        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);

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

            uint32_t sub_val = S[i][row * 16 + col];

            S_output |= (sub_val << (28 - i * 4));
        }

        // 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);
        }

        // Convert 32-bit result back to block64 (4 bytes)
        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);
        result[3] = static_cast<uint8_t>(P_permuted & 0xFF);

        return result;
    }

    // --- Main DES Operations ---

    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);

        // Split into L0 (Left) and R0 (Right) (32 bits / 4 bytes each)
        block64 L(currentBlock.begin(), currentBlock.begin() + 4);
        block64 R(currentBlock.begin() + 4, currentBlock.end());

        // 2. 16 Rounds of Feistel Network
        for (int i = 0; i < 16; ++i) {
            block64 tempL = L;

            L = R;

            block64 feistelResult = feistelFunction(R, m_roundKeys[i]);

            for(size_t j = 0; j < tempL.size(); ++j) {
                tempL[j] ^= feistelResult[j];
            }
            R = tempL;
        }

        // 3. Final Swap (The Feistel network ends with R_16 || L_16)
        block64 combinedBlock = R;
        combinedBlock.insert(combinedBlock.end(), L.begin(), L.end());

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

    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);

        // Split into L0 (Left) and R0 (Right) (32 bits / 4 bytes each)
        block64 L(currentBlock.begin(), currentBlock.begin() + 4);
        block64 R(currentBlock.begin() + 4, currentBlock.end());

        // 2. 16 Rounds, using keys K_16 down to K_1
        for (int i = 15; i >= 0; --i) {
            block64 tempL = L;

            L = R;

            block64 feistelResult = feistelFunction(R, m_roundKeys[i]);

            for(size_t j = 0; j < tempL.size(); ++j) {
                tempL[j] ^= feistelResult[j];
            }
            R = tempL;
        }

        // 3. Final Swap (R_16 || L_16)
        block64 combinedBlock = R;
        combinedBlock.insert(combinedBlock.end(), L.begin(), L.end());

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

src/des.h

0 → 100644
+83 −0
Changes for src/des.h: 83 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 <iostream>
#include <cstdint>
#include <vector>
#ifndef DES_H
#define DES_H

#include <iostream>
#include <cstdint>
#include <vector>

namespace netplus {
    // Define DES constants and types
    using block64 = std::vector<uint8_t>; // 64-bit data block (8 bytes)
    using key56 = std::vector<uint8_t>;   // 56-bit effective key (8 bytes, where 8th bit is parity)

    /**
     * @brief Implements the Data Encryption Standard (DES) algorithm.
     */
    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);

        // Destructor
        ~DES();

        /**
         * @brief Encrypts a 64-bit data block.
         * @param plaintext The 64-bit block to encrypt.
         * @return The 64-bit ciphertext block.
         */
        block64 encrypt(const block64& plaintext) const;

        /**
         * @brief Decrypts a 64-bit data block.
         * @param ciphertext The 64-bit block to decrypt.
         * @return The 64-bit plaintext block.
         */
        block64 decrypt(const block64& ciphertext) const;

    private:
        uint64_t m_masterKey;
        std::vector<block64> m_roundKeys; // 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;
    };
} // namespace netplus

#endif // DES_H
+7 −0
Changes for test/CMakeLists.txt: 7 added lines, 0 removed lines.
Original line number Diff line number Diff line
enable_testing()

add_executable(base64 base64.cpp)

target_link_libraries(base64 netplus-static)
@@ -5,3 +7,8 @@ target_link_libraries(base64 netplus-static)
add_executable(des des.cpp)

target_link_libraries(des netplus-static)

add_test(
    NAME dest_test
    COMMAND des
)

test/des.cpp

0 → 100644
+194 −0

File added.

Preview size limit exceeded, changes collapsed.