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

tripple des added

parent 0992fd63
Loading
Loading
Loading
Loading
+112 −72
Changes for src/des.cpp: 112 added lines, 72 removed lines.
Original line number Diff line number Diff line
@@ -29,6 +29,7 @@
#include <cstring>
#include <iostream>
#include <iomanip>
#include <sstream>

#include "des.h"

@@ -182,12 +183,23 @@ namespace netplus {
        return result;
    }

    netplus::block64 byte_reverse_64(const netplus::block64& block) {
        if (block.size() != 8) {
            // Handle error or return copy
            return block;
        }
        netplus::block64 reversed_block = block;
        // std::reverse swaps bytes: 01 23 45 67 89 AB CD EF -> EF CD AB 89 67 45 23 01
        std::reverse(reversed_block.begin(), reversed_block.end());
        return reversed_block;
    }

    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;
@@ -289,102 +301,130 @@ namespace netplus {
        return result;
    }

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

        block64 currentBlock = u64ToVec(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) {
            // 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;
        netplus::block64 ipBlock = u64ToVec(initialPermutation(plaintext));

            // Step 3: Calculate F = f(R_i-1, K_i)
            block64 feistelResult = feistelFunction(R, m_roundKeys48[i]);
        uint32_t L = (uint32_t(ipBlock[0]) << 24) |
                    (uint32_t(ipBlock[1]) << 16) |
                    (uint32_t(ipBlock[2]) <<  8) |
                    uint32_t(ipBlock[3]);

            // 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]);
        uint32_t R = (uint32_t(ipBlock[4]) << 24) |
                    (uint32_t(ipBlock[5]) << 16) |
                    (uint32_t(ipBlock[6]) <<  8) |
                    uint32_t(ipBlock[7]);

            // 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);
        for (int i = 0; i < 16; ++i) {
            netplus::block64 Rbytes(4);
            Rbytes[0] = uint8_t((R >> 24) & 0xFF);
            Rbytes[1] = uint8_t((R >> 16) & 0xFF);
            Rbytes[2] = uint8_t((R >>  8) & 0xFF);
            Rbytes[3] = uint8_t((R >>  0) & 0xFF);

            netplus::block64 f = feistelFunction(Rbytes, m_roundKeys48[i]);
            uint32_t F = (uint32_t(f[0]) << 24) |
                        (uint32_t(f[1]) << 16) |
                        (uint32_t(f[2]) <<  8) |
                        uint32_t(f[3]);

            uint32_t newL = R;
            uint32_t newR = L ^ F;
            L = newL;
            R = newR;
        }

        // 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(vecToU64(combinedBlock));
        uint64_t preoutput = (uint64_t(R) << 32) | uint64_t(L);
        return finalPermutation(preoutput);
    }

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

        block64 currentBlock = u64ToVec(initialPermutation(ciphertext));
        // IP
        netplus::block64 ipBlock = u64ToVec(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());
        // Split into L and R (32 bits each)
        uint32_t L = (uint32_t(ipBlock[0]) << 24) |
                    (uint32_t(ipBlock[1]) << 16) |
                    (uint32_t(ipBlock[2]) <<  8) |
                    uint32_t(ipBlock[3]);

        // 2. 16 Rounds, using keys K_16 down to K_1
        uint32_t R = (uint32_t(ipBlock[4]) << 24) |
                    (uint32_t(ipBlock[5]) << 16) |
                    (uint32_t(ipBlock[6]) <<  8) |
                    uint32_t(ipBlock[7]);

        // 16 rounds with keys reversed
        for (int i = 15; i >= 0; --i) {
            // 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]);
            // Build R half as 4 bytes for feistelFunction (expects block64 of size 4)
            netplus::block64 Rbytes(4);
            Rbytes[0] = uint8_t((R >> 24) & 0xFF);
            Rbytes[1] = uint8_t((R >> 16) & 0xFF);
            Rbytes[2] = uint8_t((R >>  8) & 0xFF);
            Rbytes[3] = uint8_t((R >>  0) & 0xFF);

            // F(R, K_i)
            netplus::block64 f = feistelFunction(Rbytes, m_roundKeys48[i]);
            uint32_t F = (uint32_t(f[0]) << 24) |
                        (uint32_t(f[1]) << 16) |
                        (uint32_t(f[2]) <<  8) |
                        uint32_t(f[3]);

            // Standard Feistel step: (L, R) := (R, L XOR F(R, K_i))
            uint32_t newL = R;
            uint32_t newR = L ^ F;
            L = newL;
            R = newR;
        }

        // Final swap: R16 || L16
        uint64_t preoutput = (uint64_t(R) << 32) | uint64_t(L);

        // FP
        return finalPermutation(preoutput);
    }

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

            // 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]);
    // Revert to direct assignment (which passed the 3DES Roundtrip Test)
    trippledes::trippledes(const block64& key1, const block64& key2, const block64& key3)
        : m_des1(key1), m_des2(key2), m_des3(key3) {}

            // 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);
    /**
     * @brief Encrypts a 64-bit block using Triple DES EDE (Encrypt-Decrypt-Encrypt) mode: C = E_K3(D_K2(E_K1(P))).
     *
     * @param plaintext The 8-byte (64-bit) block to encrypt.
     * @return The 8-byte (64-bit) ciphertext block.
     */
    block64 trippledes::encrypt(const block64& plaintext) const {
        if (plaintext.size() != 8) {
            throw std::invalid_argument("Plaintext block must be 8 bytes (64 bits) for Triple DES.");
        }
        // Matches dump label K1-K2-K3: C = E_K3(D_K2(E_K1(P)))
        return m_des3.encrypt(m_des2.decrypt(m_des1.encrypt(plaintext)));
    }

        // 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(vecToU64(combinedBlock));


    /**
     * @brief Decrypts a 64-bit block using Triple DES EDE (Encrypt-Decrypt-Encrypt) mode (Decryption): P = D_K1(E_K2(D_K3(C))).
     *
     * @param ciphertext The 8-byte (64-bit) block to decrypt.
     * @return The 8-byte (64-bit) plaintext block.
     */
    block64 trippledes::decrypt(const block64& ciphertext) const {
        if (ciphertext.size() != 8) {
            throw std::invalid_argument("Ciphertext block must be 8 bytes (64 bits) for Triple DES.");
        }
        // Inverse: P = D_K1(E_K2(D_K3(C)))
        return m_des1.decrypt(m_des2.encrypt(m_des3.decrypt(ciphertext)));
    }
} // namespace netplus
+23 −0
Changes for src/des.h: 23 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -73,4 +73,27 @@ namespace netplus {
        block64 finalPermutation(const uint64_t preoutput) const;
        block64 feistelFunction(const block64& rightHalf,uint64_t roundKey48) const;
    };

    class trippledes {
    public:
        trippledes(const block64& key1, const block64& key2, const block64& key3);
         /**
         * @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:
        des m_des1; // DES instance for K1
        des m_des2; // DES instance for K2
        des m_des3; // DES instance for K3
    };

} // namespace netplus
+144 −0
Changes for test/des.cpp: 144 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -176,14 +176,158 @@ int test_standard_vector_check() {
    return 0; // Success
}

static std::string hex8(const netplus::block64& b) {
    std::ostringstream oss;
    oss << std::hex << std::uppercase << std::setfill('0');
    for (auto x : b) oss << std::setw(2) << (int)x;
    return oss.str();
}

static netplus::block64 E(const netplus::des& d, const netplus::block64& x) { return d.encrypt(x); }
static netplus::block64 D(const netplus::des& d, const netplus::block64& x) { return d.decrypt(x); }

static void dump_3des_variants(const netplus::block64& P,
                               const netplus::block64& K1,
                               const netplus::block64& K2,
                               const netplus::block64& K3,
                               const std::string& expectedHex)
{
    struct Key { const char* name; netplus::block64 k; };
    std::array<Key,3> keys{{ {"K1",K1}, {"K2",K2}, {"K3",K3} }};

    std::array<std::array<int,3>,6> perms{{
        {{0,1,2}}, {{0,2,1}}, {{1,0,2}},
        {{1,2,0}}, {{2,0,1}}, {{2,1,0}}
    }};

    for (auto p : perms) {
        netplus::des A(keys[p[0]].k), B(keys[p[1]].k), C(keys[p[2]].k);

        // A,B,C are the 1st,2nd,3rd stages (left-to-right)
        auto ede = E(C, D(B, E(A, P)));  // E D E
        auto eee = E(C, E(B, E(A, P)));  // E E E

        auto edeHex = hex8(ede);
        auto eeeHex = hex8(eee);

        std::cout << keys[p[0]].name << "-" << keys[p[1]].name << "-" << keys[p[2]].name
                  << "  EDE=" << edeHex << (edeHex == expectedHex ? "  <-- MATCH" : "")
                  << "  EEE=" << eeeHex << (eeeHex == expectedHex ? "  <-- MATCH" : "")
                  << "\n";
    }
}

/**
 * @brief Test standard Triple DES EDE (3-Key) encryption and decryption roundtrip.
 * * Uses the same key for all three DES stages (K1=K2=K3) for simplicity in roundtrip test,
 * though a true 3DES application would use three unique keys.
 */
int test_3des_encryption_roundtrip() {
    std::cout << "Running test_3des_encryption_roundtrip..." << std::endl;

    // A single 8-byte key, used three times (K1=K2=K3)
    const std::string KEY_HEX = "133457799BBCDFF1";
    const std::string PLAINTEXT_HEX = "0123456789ABCDEF";

    block64 key = hexDecode(KEY_HEX);
    block64 plaintext = hexDecode(PLAINTEXT_HEX);

    try {
        // Initialize 3DES with K1, K2, K3 (all equal to 'key' for this test)
        netplus::trippledes tdes(key, key, key);

        block64 ciphertext = tdes.encrypt(plaintext);
        CTEST_ASSERT(ciphertext.size() == 8, "3DES Ciphertext size is not 8 bytes.")

        block64 decryptedPlaintext = tdes.decrypt(ciphertext);

        std::string actualHex = hexEncode(decryptedPlaintext);
        std::string expectedHex = PLAINTEXT_HEX;

        CTEST_ASSERT(actualHex == expectedHex,
            "3DES Roundtrip failed: Expected " + expectedHex + ", Got " + actualHex)

    } catch (const std::exception& e) {
        std::string message = "Exception during 3DES roundtrip test: ";
        message += e.what();
        CTEST_ASSERT(false, message)
    }

    return 0; // Success
}

/**
 * @brief Known-answer test for 3-key Triple DES (TDEA / EDE3) in ECB mode.
 *
 * Source: NIST SP 800-67 (original), Appendix B.1 (Example of TDEA Forward Cipher Operations - ECB).
 * Keys (Keying Option 1 / 3-key):
 *   K1 = 0123456789ABCDEF
 *   K2 = 23456789ABCDEF01
 *   K3 = 456789ABCDEF0123
 *
 * Test block:
 *   P1 = 5468652071756663  ("The quic")
 *   C1 = A826FD8CE53B855F
 */
int test_3des_standard_vector_check() {
    std::cout << "Running test_3des_standard_vector_check (EDE3 KAT)..." << std::endl;

    const std::string K1_HEX = "0123456789ABCDEF";
    const std::string K2_HEX = "23456789ABCDEF01";
    const std::string K3_HEX = "456789ABCDEF0123";

    const std::string PLAINTEXT_HEX          = "5468652071756663"; // "The quic"
    const std::string EXPECTED_CIPHERTEXT_HEX = "A826FD8CE53B855F";

    block64 key1 = hexDecode(K1_HEX);
    block64 key2 = hexDecode(K2_HEX);
    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);

        // --- Encrypt KAT ---
        block64 ct = tdes.encrypt(plaintext);
        std::string ctHex = hexEncode(ct);

        CTEST_ASSERT(ctHex == EXPECTED_CIPHERTEXT_HEX,
            "3DES KAT ENCRYPT FAILED. Expected: " + EXPECTED_CIPHERTEXT_HEX + ", Got: " + ctHex)

        // --- Decrypt KAT ---
        block64 pt2 = tdes.decrypt(ct);
        std::string ptHex = hexEncode(pt2);

        CTEST_ASSERT(ptHex == PLAINTEXT_HEX,
            "3DES KAT DECRYPT FAILED. Expected: " + PLAINTEXT_HEX + ", Got: " + ptHex)

    } catch (const std::exception& e) {
        CTEST_ASSERT(false, std::string("Exception during 3DES KAT: ") + e.what())
    }

    return 0;
}


// --- Main Entry Point for CTest ---
int main() {
    int result = 0;

    // DES tests
    result |= test_key_size_validation();
    result |= test_encryption_roundtrip();
    result |= test_standard_vector_check();

    // 3DES tests
    result |= test_3des_encryption_roundtrip();
    result |= test_3des_standard_vector_check();

    if (result != 0) {
        std::cerr << "\nOne or more unit tests failed." << std::endl;
        return 1;