Commit 37746f24 authored by jan.koester's avatar jan.koester
Browse files

added rsa

parent d0d7f8c3
Loading
Loading
Loading
Loading
+2 −0
Changes for src/CMakeLists.txt: 2 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -8,6 +8,7 @@ list(APPEND netplussrc
    crypto/des.cpp
    crypto/aes.cpp
    crypto/rc4.cpp
    crypto/rsa.cpp
)

if(${CMAKE_HOST_SYSTEM_NAME} STREQUAL "Windows")
@@ -47,6 +48,7 @@ set(headers
    crypto/des.h
    crypto/aes.h
    crypto/rc4.h
    crypto/rsa.h
)

add_library(netplus SHARED ${netplussrc} ${headers})

src/crypto/rsa.cpp

0 → 100644
+268 −0
Changes for src/crypto/rsa.cpp: 268 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 "rsa.h"

namespace netplus {

    // --- bigInt Implementation ---

    rsa::bigInt::bigInt(size_t cap) : size(0), capacity(cap) {
        digits = std::make_unique<int[]>(capacity);
        for (size_t i = 0; i < capacity; ++i) digits[i] = 0;
    }

    rsa::bigInt::bigInt(const bigInt& other) : size(other.size), capacity(other.capacity) {
        digits = std::make_unique<int[]>(capacity);
        for (size_t i = 0; i < capacity; ++i) digits[i] = other.digits[i];
    }

    rsa::bigInt::bigInt(bigInt&& other) noexcept
        : digits(std::move(other.digits)), size(other.size), capacity(other.capacity) {
        other.size = 0;
        other.capacity = 0;
    }

    rsa::bigInt& rsa::bigInt::operator=(const bigInt& other) {
        if (this != &other) {
            if (capacity < other.size) {
                digits = std::make_unique<int[]>(other.capacity);
                capacity = other.capacity;
            }
            size = other.size;
            for (size_t i = 0; i < capacity; ++i)
                digits[i] = (i < other.size) ? other.digits[i] : 0;
        }
        return *this;
    }

    rsa::bigInt& rsa::bigInt::operator=(bigInt&& other) noexcept {
        if (this != &other) {
            digits = std::move(other.digits);
            size = other.size;
            capacity = other.capacity;
            other.size = 0;
            other.capacity = 0;
        }
        return *this;
    }

    void rsa::bigInt::fromString(const std::string& s) {
        size = s.length();
        if (size > capacity) {
            digits = std::make_unique<int[]>(size);
            capacity = size;
        }
        for (size_t i = 0; i < size; ++i) {
            digits[i] = s[size - 1 - i] - '0';
        }
        while (size > 0 && digits[size - 1] == 0) size--;
    }

    std::string rsa::bigInt::toString() const {
        if (isZero()) return "0";
        std::string s = "";
        for (int i = (int)size - 1; i >= 0; i--) s += (digits[i] + '0');
        return s;
    }

    bool rsa::bigInt::isZero() const { return size == 0; }
    bool rsa::bigInt::isEven() const { return size == 0 || digits[0] % 2 == 0; }

    // --- RSA Math Engine ---

    rsa::rsa() : n(1024), e(1024), d(1024) {}

    int rsa::compare(const bigInt& a, const bigInt& b) {
        if (a.size != b.size) return a.size < b.size ? -1 : 1;
        for (int i = (int)a.size - 1; i >= 0; i--) {
            if (a.digits[i] != b.digits[i]) return a.digits[i] < b.digits[i] ? -1 : 1;
        }
        return 0;
    }

    void rsa::add(const bigInt& a, const bigInt& b, bigInt& res) {
        int carry = 0;
        size_t nSize = std::max(a.size, b.size);
        for (size_t i = 0; i < nSize || carry; ++i) {
            int val = carry + (i < a.size ? a.digits[i] : 0) + (i < b.size ? b.digits[i] : 0);
            res.digits[i] = val % 10;
            carry = val / 10;
            res.size = i + 1;
        }
    }

    void rsa::subtract(const bigInt& a, const bigInt& b, bigInt& res) {
        int borrow = 0;
        for (size_t i = 0; i < a.size; ++i) {
            int sub = a.digits[i] - borrow - (i < b.size ? b.digits[i] : 0);
            if (sub < 0) { sub += 10; borrow = 1; } else borrow = 0;
            res.digits[i] = sub;
        }
        res.size = a.size;
        while (res.size > 0 && res.digits[res.size - 1] == 0) res.size--;
    }

    void rsa::multiply(const bigInt& a, const bigInt& b, bigInt& res) {
        for (size_t k = 0; k < res.capacity; ++k) res.digits[k] = 0;
        for (size_t i = 0; i < a.size; ++i) {
            int carry = 0;
            for (size_t j = 0; j < b.size || carry; ++j) {
                long long cur = res.digits[i + j] + a.digits[i] * 1LL * (j < b.size ? b.digits[j] : 0) + carry;
                res.digits[i + j] = cur % 10;
                carry = (int)(cur / 10);
            }
        }
        res.size = a.size + b.size;
        while (res.size > 0 && res.digits[res.size - 1] == 0) res.size--;
    }

    void rsa::divide(const bigInt& dividend, const bigInt& divisor, bigInt& quotient, bigInt& remainder) {
        if (divisor.isZero()) throw std::runtime_error("Division by zero");
        remainder.size = 0;
        for (size_t k = 0; k < quotient.capacity; ++k) quotient.digits[k] = 0;

        for (int i = (int)dividend.size - 1; i >= 0; i--) {
            for (int j = (int)remainder.size; j > 0; j--) remainder.digits[j] = remainder.digits[j - 1];
            remainder.digits[0] = dividend.digits[i];
            if (remainder.digits[remainder.size] > 0 || remainder.size == 0) remainder.size++;

            int q = 0;
            while (compare(remainder, divisor) >= 0) {
                bigInt temp(remainder.capacity);
                subtract(remainder, divisor, temp);
                remainder = temp;
                q++;
            }
            quotient.digits[i] = q;
        }
        size_t qs = dividend.size;
        while (qs > 0 && quotient.digits[qs - 1] == 0) qs--;
        quotient.size = qs;
    }

    rsa::bigInt rsa::modPow(bigInt base, bigInt exp, const bigInt& mod) {
        bigInt res(mod.capacity); res.fromString("1");
        bigInt q(base.capacity), r(base.capacity);
        divide(base, mod, q, r); base = r;

        while (!exp.isZero()) {
            if (!exp.isEven()) {
                bigInt tempMul(mod.capacity * 2);
                multiply(res, base, tempMul);
                bigInt qm(tempMul.capacity), rm(mod.capacity);
                divide(tempMul, mod, qm, rm);
                res = rm;
            }
            bigInt tempSq(mod.capacity * 2);
            multiply(base, base, tempSq);
            bigInt qs(tempSq.capacity), rs(mod.capacity);
            divide(tempSq, mod, qs, rs);
            base = rs;

            bigInt qe(exp.capacity), re(1), two(1); two.fromString("2");
            divide(exp, two, qe, re);
            exp = qe;
        }
        return res;
    }

    // --- Key Generation & Operations ---

    netplus::rsa::bigInt netplus::rsa::modInverse(bigInt e, bigInt phi) {
        bigInt m0 = phi;
        bigInt t, q;
        bigInt x0(phi.capacity), x1(phi.capacity);

        x0.fromString("0");
        x1.fromString("1");

        if (compare(phi, x1) == 0) {
            bigInt zero(1); zero.fromString("0");
            return zero;
        }

        while (compare(e, x1) > 0) {
            // q = e / phi
            bigInt quotient(e.capacity), remainder(e.capacity);
            divide(e, phi, quotient, remainder);
            q = quotient;

            // t = phi, phi = e % phi, e = t
            t = phi;
            phi = remainder;
            e = t;

            // t = x0
            t = x0;

            // x0 = x1 - q * x0
            bigInt qx0(q.capacity + x0.capacity);
            multiply(q, x0, qx0);

            bigInt res(x1.capacity + qx0.capacity);
            // Because intermediate values can be negative in EEA,
            // we handle the subtraction based on which value is larger.
            if (compare(x1, qx0) >= 0) {
                subtract(x1, qx0, res);
                x0 = res;
            } else {
                subtract(qx0, x1, res);
                // This is the "negative" case: x0 = m0 - res
                bigInt resSub(m0.capacity);
                subtract(m0, res, resSub);
                x0 = resSub;
            }
            x1 = t;
        }

        return x1;
    }

    void netplus::rsa::generateKeys(bigInt& p, bigInt& q) {
        // 1. n = p * q
        multiply(p, q, n);

        // 2. phi = (p-1)*(q-1)
        bigInt one(1); one.fromString("1");
        bigInt pm1(p.capacity), qm1(q.capacity), phi(n.capacity);

        subtract(p, one, pm1);
        subtract(q, one, qm1);
        multiply(pm1, qm1, phi);

        // 3. Set e (Standard RSA public exponent)
        e.fromString("65537");

        // 4. d = e^-1 mod phi
        d = modInverse(e, phi);
    }

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

src/crypto/rsa.h

0 → 100644
+76 −0
Changes for src/crypto/rsa.h: 76 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 <iostream>
#include <memory>
#include <string>
#include <algorithm>

#pragma once

namespace netplus {
    class rsa {
    public:
        struct bigInt {
            std::unique_ptr<int[]> digits;
            size_t size;
            size_t capacity;

            // Constructors & Memory Management
            bigInt(size_t cap = 512);
            bigInt(const bigInt& other);            // Copy Constructor
            bigInt(bigInt&& other) noexcept;         // Move Constructor

            // Assignment Operators (Fixes unique_ptr errors)
            bigInt& operator=(const bigInt& other);
            bigInt& operator=(bigInt&& other) noexcept;

            // Helper Methods
            void fromString(const std::string& s);
            std::string toString() const;
            bool isZero() const;
            bool isEven() const;
        };

        rsa();

        // RSA Core Methods
        void generateKeys(bigInt& p, bigInt& q);
        bigInt encrypt(const bigInt& message);
        bigInt decrypt(const bigInt& cipher);

        // Static Math Engine
        static void add(const bigInt& a, const bigInt& b, bigInt& res);
        static void subtract(const bigInt& a, const bigInt& b, bigInt& res);
        static void multiply(const bigInt& a, const bigInt& b, bigInt& res);
        static void divide(const bigInt& dividend, const bigInt& divisor, bigInt& quotient, bigInt& remainder);
        static int compare(const bigInt& a, const bigInt& b);

    private:
        bigInt n, e, d;
        static bigInt modPow(bigInt base, bigInt exp, const bigInt& mod);
        static bigInt modInverse(bigInt e, bigInt phi);
    };
};
+9 −0
Changes for test/CMakeLists.txt: 9 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -16,6 +16,10 @@ add_executable(rc4 rc4.cpp)

target_link_libraries(rc4 netplus-static)

add_executable(rsa rsa.cpp)

target_link_libraries(rsa netplus-static)

add_test(
    NAME dest_test
    COMMAND des
@@ -30,3 +34,8 @@ add_test(
    NAME rc4_test
    COMMAND rc4
)

add_test(
    NAME rsa_test
    COMMAND rsa
)

test/rsa.cpp

0 → 100644
+54 −0
Changes for test/rsa.cpp: 54 added lines, 0 removed lines.
Original line number Diff line number Diff line
#include <iostream>
#include <cassert>
#include "../src/crypto/rsa.h"

using namespace netplus;

void test_bigint_addition() {
    rsa::bigInt a(10), b(10), res(11);
    a.fromString("999");
    b.fromString("1");
    rsa::add(a, b, res);
    assert(res.toString() == "1000");
    std::cout << "[PASS] BigInt Addition\n";
}

void test_bigint_multiplication() {
    rsa::bigInt a(10), b(10), res(20);
    a.fromString("12");
    b.fromString("12");
    rsa::multiply(a, b, res);
    assert(res.toString() == "144");
    std::cout << "[PASS] BigInt Multiplication\n";
}

void test_rsa_lifecycle() {
    rsa crypto;
    rsa::bigInt p(10), q(10), msg(20);

    // Use small primes for quick test validation
    p.fromString("61");
    q.fromString("53");
    msg.fromString("42");

    crypto.generateKeys(p, q);

    rsa::bigInt encrypted = crypto.encrypt(msg);
    rsa::bigInt decrypted = crypto.decrypt(encrypted);

    assert(decrypted.toString() == "42");
    std::cout << "[PASS] RSA Lifecycle (Encrypt/Decrypt)\n";
}

int main() {
    try {
        test_bigint_addition();
        test_bigint_multiplication();
        test_rsa_lifecycle();
        std::cout << "\nAll tests passed successfully!\n";
    } catch (const std::exception& e) {
        std::cerr << "\nTest failed with error: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}