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

unit test completed

parent 34678f91
Loading
Loading
Loading
Loading
+33 −34
Changes for src/crypto/rsa.cpp: 33 added lines, 34 removed lines.
Original line number Diff line number Diff line
@@ -225,52 +225,51 @@ namespace netplus {
        }
    }

    void rsa::multiply(const bigInt& a, const bigInt& b, bigInt& res) {
        // 1. If either is 0, the result is 0
        if (a.isZero() || b.isZero()) {
            res.fromString("0");
            return;
        }
    void netplus::rsa::multiply(const bigInt& a, const bigInt& b, bigInt& res) {
        size_t required = a.size + b.size;
        res.reserve(required); // Ensure we don't write past 2048 bytes

        // 2. Clear res buffer completely
        for (size_t k = 0; k < res.capacity; ++k) res.digits[k] = 0;
        // Initialize res size and clear existing digits
        res.size = required;
        for(size_t i = 0; i < res.capacity; ++i) res.digits[i] = 0;

        // 3. Multiplication loop
        // Your multiplication logic (likely nested loops)
        for (size_t i = 0; i < a.size; ++i) {
            long long 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] = (int)(cur % 10);
            int carry = 0;
            for (size_t j = 0; j < b.size; ++j) {
                // This is likely where line 245 is:
                long long cur = res.digits[i + j] + (long long)a.digits[i] * b.digits[j] + carry;
                res.digits[i + j] = cur % 10; // Assuming base 10
                carry = cur / 10;
            }
            res.digits[i + b.size] = carry;
        }

        // 4. Correct size calculation
        res.size = a.size + b.size + 1;
        if (res.size > res.capacity) res.size = res.capacity; // Safety
        while (res.size > 1 && res.digits[res.size - 1] == 0) res.size--;
        // Trim leading zeros to update res.size correctly
        while (res.size > 1 && res.digits[res.size - 1] == 0) {
            res.size--;
        }
    }

    void rsa::bigInt::printDebug(const std::string& label) const {
        std::cout << "[" << label << "] "
                << "Size: " << size
                << ", Cap: " << capacity
                << ", Value: ";
        if (isZero()) {
            std::cout << "0" << std::endl;
            return;
    void netplus::rsa::bigInt::reserve(size_t new_cap) {
        if (new_cap <= capacity) return; // Already large enough

        // Allocate new memory
        auto new_digits = std::make_unique<int[]>(new_cap);

        // Copy existing digits
        for (size_t i = 0; i < size; ++i) {
            new_digits[i] = digits[i];
        }
        // Print in reverse (MSB to LSB)
        for (int i = (int)size - 1; i >= 0; i--) {
            std::cout << digits[i];

        // Zero-initialize the remaining new space to avoid reading junk data
        for (size_t i = size; i < new_cap; ++i) {
            new_digits[i] = 0;
        }
        // Optional: Print raw buffer to see if there is "hidden" data
        // std::cout << " | Raw: ";
        // for(size_t i=0; i < capacity; ++i) std::cout << digits[i];

        std::cout << std::endl;
        // Replace old digits with the new array
        digits = std::move(new_digits);
        capacity = new_cap;
    }

    void rsa::divide(const bigInt& dividend, const bigInt& divisor, bigInt& quotient, bigInt& remainder) {
+1 −1
Changes for src/crypto/rsa.h: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -53,7 +53,7 @@ namespace netplus {
            bool isZero() const;
            bool isEven() const;
            void divideByTwo();
            void printDebug(const std::string& label) const ;
            void reserve(size_t new_cap);
        };

        rsa();
+87 −47
Changes for src/crypto/x509.cpp: 87 added lines, 47 removed lines.
Original line number Diff line number Diff line
@@ -31,6 +31,71 @@

netplus::x509cert::x509cert() {}

#include <ctime>
#include <iomanip>
#include <sstream>

time_t netplus::x509cert::parseASN1Time(const std::vector<uint8_t>& data, uint8_t tag) {
    std::string timeStr(data.begin(), data.end());
    struct tm t = {0};
    const char* format;

    if (tag == 0x17) { // UTCTime: YYMMDDHHMMSSZ
        format = "%y%m%d%H%M%S";
    } else if (tag == 0x18) { // GeneralizedTime: YYYYMMDDHHMMSSZ
        format = "%Y%m%d%H%M%S";
    } else {
        return 0;
    }

    if (strptime(timeStr.c_str(), format, &t)) {
        return timegm(&t); // Convert to UTC timestamp
    }
    return 0;
}

bool netplus::x509cert::checkValidity() {
    if (root.children.empty() || root.children[0].children.size() < 5)
        return false;

    // 1. Locate the Validity Sequence
    // Searching by tag 0x30 to be index-independent
    ASN1Node* validity = nullptr;
    auto& tbs = root.children[0];

    // In X.509, Validity is the 4th or 5th element depending on Version presence
    for (size_t i = 0; i < tbs.children.size(); ++i) {
        // Validity is a Sequence of two times (0x17 or 0x18)
        if (tbs.children[i].tag == 0x30 && !tbs.children[i].children.empty()) {
            uint8_t firstTag = tbs.children[i].children[0].tag;
            if (firstTag == 0x17 || firstTag == 0x18) {
                validity = &tbs.children[i];
                break;
            }
        }
    }

    if (!validity || validity->children.size() < 2) return false;

    // 2. Parse the dates
    time_t notBefore = parseASN1Time(validity->children[0].data, validity->children[0].tag);
    time_t notAfter = parseASN1Time(validity->children[1].data, validity->children[1].tag);
    time_t now = time(nullptr);

    // 3. Compare
    if (now < notBefore) {
        std::cout << "Certificate is not yet valid (Future date)." << std::endl;
        return false;
    }
    if (now > notAfter) {
        std::cout << "Certificate has EXPIRED." << std::endl;
        return false;
    }

    std::cout << "Certificate validity: OK." << std::endl;
    return true;
}

bool netplus::x509cert::loadFromBuffer(const std::vector<uint8_t>& buffer) {
    if (buffer.empty()) return false;

@@ -103,30 +168,41 @@ size_t netplus::x509cert::parseInternal(const uint8_t* data, size_t size, ASN1No
    outNode.tag = data[cursor++];

    // 1. Parse Length
    if (cursor >= size) return 0; // Safety check
    size_t length = data[cursor++];

    if (length & 0x80) { // Long form
        int octets = length & 0x7F;

        // Defensive Check: If octets is unreasonably high or exceeds remaining buffer
        if (octets > sizeof(size_t) || cursor + octets > size) return 0;

        length = 0;
        for (int i = 0; i < octets; ++i) {
            length = (length << 8) | data[cursor++];
        }
    }

    // Safety check: ensure we don't read past the buffer
    // Safety check: ensure the indicated length doesn't exceed the provided buffer
    if (cursor + length > size) return 0;

    // 2. Extract Data
    outNode.data.assign(data + cursor, data + cursor + length);

    // 3. Recursive Step: If it's a "Constructed" type (Sequence, Set, etc.)
    // Bit 6 of the tag indicates if it's constructed (0x20)
    // 3. Recursive Step: Only for Constructed types (Bit 6 = 0x20)
    if (outNode.tag & 0x20) {
        size_t subCursor = 0;
        // Ensure we don't clear children if we are re-parsing
        outNode.children.clear();

        while (subCursor < length) {
            ASN1Node child;
            // Recursively parse using the internal data buffer and its specific length
            size_t bytesRead = parseInternal(outNode.data.data() + subCursor, length - subCursor, child);

            if (bytesRead == 0) break;
            outNode.children.push_back(child);

            outNode.children.push_back(std::move(child)); // Use move for efficiency
            subCursor += bytesRead;
        }
    }
@@ -134,57 +210,21 @@ size_t netplus::x509cert::parseInternal(const uint8_t* data, size_t size, ASN1No
    return cursor + length;
}

std::tm netplus::x509cert::parseUTCTime(const std::vector<uint8_t>& data) {
    std::string timeStr(data.begin(), data.end());
    std::tm t = {};

    // Format: YYMMDDHHMMSSZ (13 bytes)
    if (timeStr.length() >= 12) {
        int year = std::stoi(timeStr.substr(0, 2));
        // Adjust year based on RFC 5280 rules
        year += (year < 50) ? 100 : 0; // 100 is offset from 1900 (so 2024 is 124)

        t.tm_year = year;
        t.tm_mon  = std::stoi(timeStr.substr(2, 2)) - 1; // 0-indexed
        t.tm_mday = std::stoi(timeStr.substr(4, 2));
        t.tm_hour = std::stoi(timeStr.substr(6, 2));
        t.tm_min  = std::stoi(timeStr.substr(8, 2));
        t.tm_sec  = std::stoi(timeStr.substr(10, 2));
    }
    return t;
}

bool netplus::x509cert::isExpired(const std::tm& notAfter) {
    std::time_t now = std::time(nullptr);
    std::time_t expiry = std::mktime(const_cast<std::tm*>(&notAfter));

    return std::difftime(now, expiry) > 0;
}

std::string netplus::x509cert::bytesToHex(const std::vector<uint8_t>& bytes) {
    std::stringstream ss;
    for (uint8_t b : bytes) {
        ss << std::hex << std::setw(2) << std::setfill('0') << (int)b;
    }
    return ss.str();
}

void netplus::x509cert::bytesToBigInt(const std::vector<uint8_t>& bytes, netplus::rsa::bigInt& out) {
    // Initialize out to 0
    out.fromString("0");
    out.fromString("0"); // Ensure it starts clean

    netplus::rsa::bigInt base256;
    base256.fromString("256");

    netplus::rsa::bigInt tempAdd;
    netplus::rsa::bigInt tempMul;

    for (uint8_t b : bytes) {
        // out = (out * 256) + byte
        netplus::rsa::bigInt tempMul, tempAdd, byteVal;

        // If 'out' or 'tempMul' reaches 'capacity' without resizing,
        // you get the 'free(): invalid next size' error.
        netplus::rsa::multiply(out, base256, tempMul);

        tempAdd.fromString(std::to_string((int)b));
        netplus::rsa::add(tempMul, tempAdd, out);
        byteVal.fromString(std::to_string((int)b));
        netplus::rsa::add(tempMul, byteVal, out);
    }
}

+3 −2
Changes for src/crypto/x509.h: 3 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -48,8 +48,9 @@ namespace netplus {
        bool loadFromBuffer(const std::vector<uint8_t>& buffer);
        bool loadFromFile(const std::string& filePath);

        bool checkValidity();

        std::string getSubjectCN();
        bool isExpired(const std::tm& notAfter);
        bool extractPublicKey(netplus::rsa& outRsa);
        std::vector<std::string> getSubjectAltNames();

@@ -68,7 +69,7 @@ namespace netplus {
        // Internal ASN.1 parsing helpers
        ASN1Node root;
        size_t parseInternal(const uint8_t* data, size_t size, ASN1Node& outNode);
        std::tm parseUTCTime(const std::vector<uint8_t>& data);
        time_t parseASN1Time(const std::vector<uint8_t>& data, uint8_t tag) ;
        std::string decodeOID(const std::vector<uint8_t>& data);
        std::string bytesToHex(const std::vector<uint8_t>& bytes);
        void bytesToBigInt(const std::vector<uint8_t>& bytes, netplus::rsa::bigInt& out);
+9 −4
Changes for test/x509.cpp: 9 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -33,17 +33,22 @@ int main(int argc,char *argv[]) {
    // 1. Initialize the Certificate Parser
    netplus::x509cert cert;

    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " <cert.der>" << std::endl;
        return 1;
    }

    // Most certificates from web servers are in .der (binary) format
    if (!cert.loadFromFile(argv[1])) {
        std::cerr << "Error: Could not load or parse the DER file." << std::endl;
        return 1;
    }

    // 2. Prepare your RSA Engine
    netplus::rsa rsaEngine;
    // New Step: Check Validity
    std::cout << "--- Certificate Status ---" << std::endl;
    cert.checkValidity();

    // 3. Extract the Public Key (N and E) into the RSA Engine
    // This uses the bytesToBigInt logic we built to fill rsaEngine.n and rsaEngine.e
    netplus::rsa rsaEngine;
    if (cert.extractPublicKey(rsaEngine)) {
        std::cout << "Successfully extracted RSA Public Key." << std::endl;
    } else {