Commit 9c1f774c authored by jan.koester's avatar jan.koester
Browse files

test

parent 38ca148c
Loading
Loading
Loading
Loading
+0 −12
Changes for src/connection.cpp: 0 added lines, 12 removed lines.
Original line number Diff line number Diff line
@@ -77,18 +77,6 @@ netplus::condata<char>::const_iterator netplus::condata<char>::end() const{
    return std::vector<char,condataAlloc<char>>::end();
}

void netplus::condata<char>::resize(size_t size_c){
   size_t rs = size();

   std::move(
             begin()+size_c,
             end(),
             begin()
    );

   std::vector<char,condataAlloc<char>>::resize(rs-size_c);
}

void netplus::condata<char>::append(const char* data, size_t datalen){
   if ( !data || data == data + datalen)
        return;
+1 −1
Changes for src/connection.h: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -145,7 +145,7 @@ namespace netplus {
            const_iterator end() const;


            void        resize(size_t size_c);
            void        resize(size_t size_c)=delete;
            void        append(const char *data,size_t datalen);
            size_t      search(const char *word);
            size_t      search(const char *word,size_t pos);
+27 −57
Changes for src/crypto/aes.cpp: 27 added lines, 57 removed lines.
Original line number Diff line number Diff line
@@ -571,87 +571,57 @@ namespace netplus {
     * @param iv: 16-byte Initialization Vector
     * @return: Encrypted ciphertext (length will be multiple of 16)
     */
    std::vector<uint8_t> aes::encryptCBC(const std::vector<uint8_t>& plaintext, const std::vector<uint8_t>& iv) {
        if (iv.size() != 16) {
            throw std::invalid_argument("AES CBC requires a 16-byte IV.");
        }

        // 1. Handle PKCS#7 Padding
        // Even if data is 16 bytes, we add a full block of padding per standard
        std::vector<uint8_t> data = plaintext;
        uint8_t paddingLen = 16 - (data.size() % 16);
        for (int i = 0; i < paddingLen; ++i) {
            data.push_back(paddingLen);
        }
    std::vector<uint8_t> netplus::aes::encryptCBC(const std::vector<uint8_t>& plaintext,
                                                const std::vector<uint8_t>& iv) {
        if (iv.size() != 16) throw std::invalid_argument("AES CBC requires 16-byte IV.");
        if (plaintext.empty() || (plaintext.size() % 16) != 0)
            throw std::invalid_argument("AES-CBC plaintext must be multiple of 16 (TLS adds padding).");

        std::vector<uint8_t> ciphertext;
        ciphertext.reserve(data.size());

        // The "previous" block for the first iteration is the IV
        block128 previousBlock(16);
        std::copy(iv.begin(), iv.end(), previousBlock.begin());
        ciphertext.reserve(plaintext.size());

        // 2. Process block by block
        for (size_t i = 0; i < data.size(); i += 16) {
            block128 currentBlock(16);
        block128 prev(16);
        std::copy(iv.begin(), iv.end(), prev.begin());

            // XOR current plaintext block with the previous ciphertext block (or IV)
            for (int j = 0; j < 16; ++j) {
                currentBlock[j] = data[i + j] ^ previousBlock[j];
            }

            // Encrypt the XORed block using your existing AES-128 core
            block128 encrypted = encrypt(currentBlock);
        for (size_t i = 0; i < plaintext.size(); i += 16) {
            block128 in(16);
            for (int j = 0; j < 16; ++j) in[j] = plaintext[i + j] ^ prev[j];

            // Store result and update 'previousBlock' for the next chain link
            ciphertext.insert(ciphertext.end(), encrypted.begin(), encrypted.end());
            previousBlock = encrypted;
            block128 out = encrypt(in);
            ciphertext.insert(ciphertext.end(), out.begin(), out.end());
            prev = out;
        }

        return ciphertext;
    }


    /**
     * decryptCBC
     * @param ciphertext: The encrypted data
     * @param iv: 16-byte Initialization Vector
     * @return: Decrypted and unpadded plaintext
     */
    std::vector<uint8_t> aes::decryptCBC(const std::vector<uint8_t>& ciphertext, const std::vector<uint8_t>& iv) {
        if (ciphertext.size() % 16 != 0 || ciphertext.empty()) {
            throw std::invalid_argument("Ciphertext length must be a multiple of 16.");
        }
    std::vector<uint8_t> netplus::aes::decryptCBC(const std::vector<uint8_t>& ciphertext,
                                                const std::vector<uint8_t>& iv) {
        if (iv.size() != 16) throw std::invalid_argument("AES CBC requires 16-byte IV.");
        if (ciphertext.empty() || (ciphertext.size() % 16) != 0)
            throw std::invalid_argument("AES-CBC ciphertext must be multiple of 16.");

        std::vector<uint8_t> plaintext;
        plaintext.reserve(ciphertext.size());

        block128 previousBlock(16);
        std::copy(iv.begin(), iv.end(), previousBlock.begin());
        block128 prev(16);
        std::copy(iv.begin(), iv.end(), prev.begin());

        for (size_t i = 0; i < ciphertext.size(); i += 16) {
            block128 currentCipherBlock(16);
            std::copy(ciphertext.begin() + i, ciphertext.begin() + i + 16, currentCipherBlock.begin());

            // Decrypt the block first
            block128 decrypted = decrypt(currentCipherBlock);
            block128 c(16);
            std::copy(ciphertext.begin() + i, ciphertext.begin() + i + 16, c.begin());

            // XOR with the previous ciphertext block (or IV) to get plaintext
            for (int j = 0; j < 16; ++j) {
                plaintext.push_back(decrypted[j] ^ previousBlock[j]);
            }
            block128 d = decrypt(c);
            for (int j = 0; j < 16; ++j) plaintext.push_back(d[j] ^ prev[j]);

            // Update previousBlock to the current ciphertext block for the next iteration
            previousBlock = currentCipherBlock;
            prev = c;
        }

        // 3. Remove PKCS#7 Padding
        if (!plaintext.empty()) {
            uint8_t paddingLen = plaintext.back();
            if (paddingLen > 0 && paddingLen <= 16) {
                plaintext.resize(plaintext.size() - paddingLen);
            }
        }

        return plaintext;
    }

+237 −36
Changes for src/crypto/rsa.cpp: 237 added lines, 36 removed lines.
Original line number Diff line number Diff line
@@ -54,7 +54,7 @@ namespace netplus {
        if (this == &other) return *this; // Self-assignment check

        // 1. Reallocate if the current capacity is too small
        if (capacity < other.used) {
        if (capacity < other.capacity) {
            data = std::make_unique<uint32_t[]>(other.capacity);
            capacity = other.capacity;
        }
@@ -72,25 +72,35 @@ namespace netplus {
    }

    void rsa::bigInt::shiftLeft(size_t n) {
        if (n == 0 || used == 0) return;
        if (n == 0 || isZero()) return;

        size_t wordShift = n / 32;
        size_t bitShift  = n % 32;

        if (used + wordShift + 1 > capacity) reserve(used + wordShift + 1);
        size_t newUsed = used + wordShift + (bitShift ? 1 : 0);
        reserve(newUsed);

        if (bitShift > 0) {
            for (size_t i = used; i > 0; --i) {
                data[i + wordShift] = (data[i + wordShift] << bitShift) | (data[i + wordShift - 1] >> (32 - bitShift));
            }
            data[wordShift] = (data[wordShift] << bitShift);
        // temp copy of current limbs
        std::vector<uint32_t> old(used);
        std::copy(data.get(), data.get() + used, old.data());

        // zero destination
        std::fill(data.get(), data.get() + newUsed, 0);

        uint32_t carry = 0;
        for (size_t i = 0; i < old.size(); ++i) {
            uint64_t v = old[i];
            if (bitShift) {
                uint64_t shifted = (v << bitShift) | carry;
                data[i + wordShift] = (uint32_t)shifted;
                carry = (uint32_t)(v >> (32 - bitShift));
            } else {
            for (size_t i = used; i > 0; --i) {
                data[i + wordShift - 1] = data[i - 1];
                data[i + wordShift] = (uint32_t)v;
            }
        }
        // Zero out new lower words
        for (size_t i = 0; i < wordShift; ++i) data[i] = 0;
        used += wordShift + (bitShift > 0 ? 1 : 0);
        if (bitShift) data[old.size() + wordShift] = carry;

        used = newUsed;
        while (used > 1 && data[used - 1] == 0) used--;
    }

@@ -146,11 +156,10 @@ namespace netplus {

    // Sets the bigInt value from a standard 64-bit integer
    void netplus::rsa::bigInt::fromUint64(uint64_t val) {
        reserve(2); // uint64_t fits in two 32-bit words
        data[0] = static_cast<uint32_t>(val & 0xFFFFFFFF);
        data[1] = static_cast<uint32_t>(val >> 32);
        used = (data[1] > 0) ? 2 : (data[0] > 0 ? 1 : 0);
        if (used == 0) used = 1; // Always at least one word (0)
        reserve(2);
        data[0] = (uint32_t)(val & 0xFFFFFFFFu);
        data[1] = (uint32_t)(val >> 32);
        used = (data[1] ? 2 : 1);   // zero becomes used=1, data[0]=0
    }

    // Simple equality check for assertions without needing strings
@@ -179,39 +188,87 @@ namespace netplus {
        return ss.str();
    }

    rsa::bigInt rsa::bigInt::operator*(const rsa::bigInt& other) const {
        bigInt res(this->capacity + other.capacity);
        rsa::multiply(*this, other, res);
        return res;
    }

    rsa::bigInt rsa::bigInt::operator%(const rsa::bigInt& mod) const {
        bigInt q(this->capacity), r(mod.capacity);
        rsa::divide(*this, mod, q, r);
        return r;
    }


    rsa::rsa(){
    }

    // R = 2^(32*nwords), so R2 = R*R mod N
    rsa::bigInt rsa::calculateR2Mod(const bigInt& mod) {
        bigInt r(mod.used * 4 + 2);
        r.fromUint64(1);
        r.shiftLeft(mod.used * 64); // 2*(32*nwords)
        bigInt q(r.used + 1), rem(mod.used + 1);
        divide(r, mod, q, rem);
        return rem;
    }

    void rsa::add(const bigInt& a, const bigInt& b, bigInt& res) {
        uint64_t carry = 0;
        size_t max_len = std::max(a.used, b.used);

        res.reserve(max_len + 1); // important
        res.used = 0;

        for (size_t i = 0; i < max_len || carry; ++i) {
            uint64_t sum = carry + (i < a.used ? a.data[i] : 0)
            uint64_t sum = carry
                + (i < a.used ? a.data[i] : 0)
                + (i < b.used ? b.data[i] : 0);

            res.data[i] = (uint32_t)sum;
            carry = sum >> 32;
            res.used++;
        }

        if (res.used == 0) { res.used = 1; res.data[0] = 0; }
    }


    void rsa::multiply(const bigInt& a, const bigInt& b, bigInt& res) {
        std::fill(res.data.get(), res.data.get() + res.capacity, 0);

        for (size_t i = 0; i < a.used; ++i) {
            uint64_t carry = 0;
            for (size_t j = 0; j < b.used; ++j) {
                uint64_t cur = (uint64_t)res.data[i + j] +
                            (uint64_t)a.data[i] * b.data[j] + carry;
                uint64_t cur =
                    (uint64_t)res.data[i + j] +
                    (uint64_t)a.data[i] * (uint64_t)b.data[j] +
                    carry;

                res.data[i + j] = (uint32_t)cur;
                carry = cur >> 32;
            }
            res.data[i + b.used] = (uint32_t)carry;

            // ADD carry to existing limb, then propagate if overflow
            size_t k = i + b.used;
            uint64_t cur = (uint64_t)res.data[k] + carry;
            res.data[k] = (uint32_t)cur;
            carry = cur >> 32;

            while (carry) {
                ++k;
                uint64_t cur2 = (uint64_t)res.data[k] + carry;
                res.data[k] = (uint32_t)cur2;
                carry = cur2 >> 32;
            }
        }

        res.used = a.used + b.used;
        while (res.used > 1 && res.data[res.used - 1] == 0) res.used--;
    }


    int rsa::compare(const bigInt& a, const bigInt& b) {
        if (a.used != b.used)
            return (a.used > b.used) ? 1 : -1;
@@ -251,25 +308,98 @@ namespace netplus {
        while (res.used > 1 && res.data[res.used - 1] == 0) res.used--;
    }

    rsa::bigInt rsa::modPow(const bigInt& base, const bigInt& exp, const bigInt& mod) {
        bigInt res(mod.capacity);
        res.data[0] = 1; res.used = 1;
    netplus::rsa::bigInt netplus::rsa::modPow(const netplus::rsa::bigInt& base,
                                    const netplus::rsa::bigInt& exp,
                                    const netplus::rsa::bigInt& mod)
    {
        using bigInt = netplus::rsa::bigInt;

        // Handle mod == 0 or 1 edge cases
        if (mod.used == 1 && mod.data[0] == 0) {
            throw std::runtime_error("modPow: modulus is zero");
        }
        if (mod.used == 1 && mod.data[0] == 1) {
            bigInt z(1U, 1);
            z.data[0] = 0;
            z.used = 1;
            return z;
        }

        // exp == 0 => 1 mod mod
        if (exp.isZero()) {
            bigInt one(1U, 1);
            // one % mod
            bigInt q(one.capacity), r(mod.capacity);
            netplus::rsa::divide(one, mod, q, r);
            return r;
        }

        // Montgomery requires odd modulus
        if (mod.isEven()) {
            // Fallback to classic square-and-multiply if needed (not expected for RSA)
            bigInt result(1U, mod.capacity);
            bigInt a = base % mod;

            for (size_t i = exp.bitLength(); i-- > 0; ) {
                result = (result * result) % mod;
                if (exp.isBitSet(i)) result = (result * a) % mod;
            }
            return result;
        }

        // n_prime = -N^{-1} mod 2^32 (uses least significant limb)
        uint32_t n_prime = netplus::rsa::calculateNPrime(mod.data[0]);

        // Helper: compute (2^(32*mod.used)) mod mod  == R mod N
        auto calculateRMod = [&](const bigInt& N) -> bigInt {
            bigInt r(N.used * 2 + 2);
            r.fromUint64(1);
            r.shiftLeft(N.used * 32);

            bigInt q(r.used + 1), rem(N.used + 2);
            netplus::rsa::divide(r, N, q, rem);
            return rem;
        };

        // Helper: compute (2^(64*mod.used)) mod mod == R^2 mod N
        auto calculateR2Mod = [&](const bigInt& N) -> bigInt {
            bigInt r(N.used * 4 + 2);
            r.fromUint64(1);
            r.shiftLeft(N.used * 64);

            bigInt q(r.used + 1), rem(N.used + 2);
            netplus::rsa::divide(r, N, q, rem);
            return rem;
        };

        // Montgomery multiply: returns (a*b*R^{-1}) mod N
        auto montMul = [&](const bigInt& a, const bigInt& b) -> bigInt {
            return netplus::rsa::montgomeryMultiply(a, b, mod, n_prime);
        };

        // Convert into Montgomery domain correctly:
        // a_bar = a * R mod N
        // Using montMul(a, R^2) = a*R^2*R^{-1} = a*R (mod N)
        bigInt a = base % mod;
        bigInt R2 = calculateR2Mod(mod);

        bigInt a = base;
        size_t bits = exp.bitLength();
        bigInt a_bar = montMul(a, R2);

        for (size_t i = 0; i < bits; ++i) {
        // res_bar = 1 * R mod N  (Montgomery form of 1)
        // Either R mod N directly, or montMul(1, R2)
        bigInt one(1U, 1);
        bigInt res_bar = montMul(one, R2);

        // Exponentiation (left-to-right square-and-multiply)
        for (size_t i = exp.bitLength(); i-- > 0; ) {
            res_bar = montMul(res_bar, res_bar);
            if (exp.isBitSet(i)) {
                bigInt tmpMul(res.capacity + a.capacity);
                bigInt q(tmpMul.capacity); // Quotient (discarded)
                multiply(res, a, tmpMul);
                divide(tmpMul, mod, q, res); // Remainder goes into res
                res_bar = montMul(res_bar, a_bar);
            }
            bigInt tmpSq(a.capacity * 2);
            multiply(a, a, tmpSq);
            divide(tmpSq, mod, a,res); // a = tmpSq % mod
        }
        return res;

        // Convert out of Montgomery domain: montMul(res_bar, 1) = res_bar*1*R^{-1} = result
        return montMul(res_bar, one);
    }

    void rsa::divide(const bigInt& dividend, const bigInt& divisor, bigInt& quotient, bigInt& remainder) {
@@ -533,4 +663,75 @@ namespace netplus {

    rsa::bigInt rsa::encrypt(const bigInt& m) { return modPow(m, e, n); }
    rsa::bigInt rsa::decrypt(const bigInt& c) { return modPow(c, d, n); }

    // This is used to "clear" the lower bits during reduction
    uint32_t rsa::calculateNPrime(uint32_t n0) {
        uint32_t inv = 1;
        for (int i = 0; i < 32; i++) {
            inv *= 2 - n0 * inv;
        }
        return -inv;
    }

    // 2. Calculate R mod N (where R = 2^(32 * mod.used))
    rsa::bigInt rsa::calculateRMod(const bigInt& mod) {
        bigInt r(mod.used * 2 + 1);
        r.fromUint64(1);

        // Shift 1 left by (32 * mod.used) bits, then mod N
        // This is equivalent to R mod N
        r.shiftLeft(mod.used * 32);

        bigInt q(r.used), remainder(mod.used);
        divide(r, mod, q, remainder);
        return remainder;
    }

    // 3. Montgomery Multiplication: (a * b * R^-1) mod N
    // This is the core "speed" function that avoids long division.
    rsa::bigInt rsa::montgomeryMultiply(const bigInt& a, const bigInt& b, const bigInt& mod, uint32_t n_prime) {
        size_t n = mod.used;
        bigInt res(2 * n + 1);

        // Perform standard schoolbook multiplication (res = a * b)
        multiply(a, b, res);
        res.reserve(2 * n + 1);

        // Montgomery Reduction
        for (size_t i = 0; i < n; i++) {
            uint32_t m = res.data[i] * n_prime;
            uint64_t carry = 0;
            for (size_t j = 0; j < n; j++) {
                uint64_t cur = (uint64_t)res.data[i + j] + (uint64_t)m * mod.data[j] + carry;
                res.data[i + j] = (uint32_t)cur;
                carry = cur >> 32;
            }
            // Propagate the carry
            size_t k = i + n;
            while (carry > 0) {
                uint64_t cur = (uint64_t)res.data[k] + carry;
                res.data[k] = (uint32_t)cur;
                carry = cur >> 32;
                k++;
            }
        }

        // Shift right by N words (divide by R)
        bigInt final_res(n + 1);
        for (size_t i = 0; i < n + 1; i++) {
            final_res.data[i] = res.data[i + n];
        }
        final_res.used = n + 1;
        while (final_res.used > 1 && final_res.data[final_res.used - 1] == 0) final_res.used--;

        // Final step: if res >= mod, subtract mod
        if (compare(final_res, mod) >= 0) {
            bigInt actual_final(mod.capacity);
            subtract(final_res, mod, actual_final);
            return actual_final;
        }

        return final_res;
    }

};
+14 −9
Changes for src/crypto/rsa.h: 14 added lines, 9 removed lines.
Original line number Diff line number Diff line
@@ -40,17 +40,18 @@ namespace netplus {
                size_t used; // number of 32-bit words used
                size_t capacity;

                explicit bigInt(size_t cap_words = 64) : used(0), capacity(cap_words) {
                explicit bigInt(size_t cap_words = 64) : used(1), capacity(std::max<size_t>(1, cap_words)) {
                    data = std::make_unique<uint32_t[]>(capacity);
                    std::fill(data.get(), data.get() + capacity, 0);
                }

                bigInt(uint32_t val, size_t cap) : used(val > 0 ? 1 : 0), capacity(cap) {
                bigInt(uint32_t val, size_t cap) : used(1), capacity(std::max<size_t>(1, cap)) {
                    data = std::make_unique<uint32_t[]>(capacity);
                    std::fill(data.get(), data.get() + capacity, 0);
                    if (used > 0) data[0] = val;
                    data[0] = val;
                }


                bigInt(const bigInt& other);

                netplus::rsa::bigInt& operator=(const bigInt& other);
@@ -58,13 +59,9 @@ namespace netplus {
                // Helper to check bit state for modPow
                bool isBitSet(size_t bit) const;

                bool isEven() const {
                    return used > 0 && (data[0] & 1) == 0;
                }
                bool isZero() const { return used == 1 && data[0] == 0; }
                bool isEven() const { return (data[0] & 1) == 0; } // safe if used>=1 always

                bool isZero() const {
                    return used == 0 || (used == 1 && data[0] == 0);
                }

                size_t bitLength() const;

@@ -75,6 +72,10 @@ namespace netplus {
                void fromUint64(uint64_t val);
                bool equalsUint64(uint64_t val) const;
                std::string toHexString() const;

                // Inside struct bigInt
                bigInt operator*(const bigInt& other) const;
                bigInt operator%(const bigInt& mod) const;
            };

        rsa();
@@ -110,6 +111,10 @@ namespace netplus {
        static bigInt modPow(const bigInt& base, const bigInt& exp, const bigInt& mod);
        static bigInt modInverse(const bigInt& e, const bigInt& phi);
        static bigInt gcd(bigInt a, bigInt b);
        static uint32_t calculateNPrime(uint32_t n0);
        static bigInt calculateRMod(const bigInt& mod);
        static bigInt calculateR2Mod(const bigInt& mod);
        static bigInt montgomeryMultiply(const bigInt& a, const bigInt& b, const bigInt& mod, uint32_t n_prime);
        friend class x509cert;
        friend class ssl;
    };
Loading