Loading src/crypto/rsa.cpp +212 −204 Changes for src/crypto/rsa.cpp: 212 added lines, 204 removed lines. Original line number Diff line number Diff line Loading @@ -58,22 +58,24 @@ namespace netplus { } rsa::bigInt& rsa::bigInt::operator=(const bigInt& other) { if (this != &other) { // Only reallocate if we absolutely must if (this == &other) return *this; // 1. Ensure enough capacity if (this->capacity < other.size) { // make_unique creates a NEW buffer; unique_ptr::operator= // will then safely delete the OLD buffer. digits = std::make_unique<int[]>(other.capacity); capacity = other.capacity; auto new_digits = std::make_unique<int[]>(other.size + 2); digits = std::move(new_digits); capacity = other.size + 2; } // 2. Copy the size this->size = other.size; // Reset the entire buffer to 0 first to prevent garbage data // 3. Copy the digits and ZERO out the rest of the capacity // This prevents "ghost digits" from previous values for (size_t i = 0; i < capacity; ++i) { digits[i] = (i < other.size) ? other.digits[i] : 0; } } return *this; } Loading @@ -93,14 +95,41 @@ namespace netplus { } void rsa::bigInt::fromString(const std::string& s) { // 1. Handle empty string as zero if (s.empty()) { size = 1; digits[0] = 0; return; } // 2. Adjust capacity if the string is longer than current allocation if (s.length() > capacity) { digits = std::make_unique<int[]>(s.length() + 2); capacity = s.length() + 2; } // 3. Convert characters to digits in REVERSE order // String "123" -> digits[0]=3, digits[1]=2, digits[2]=1 size = s.length(); // ... allocation logic ... for (size_t i = 0; i < size; ++i) { digits[i] = s[size - 1 - i] - '0'; char c = s[size - 1 - i]; if (c >= '0' && c <= '9') { digits[i] = c - '0'; } else { digits[i] = 0; // Or throw an error for invalid characters } } // 4. Wipe any old data in the remaining capacity (Ghost Digits) for (size_t i = size; i < capacity; ++i) { digits[i] = 0; } // 5. Strip leading zeros, but keep at least one digit // Example: "000123" should have size 3. "000" should have size 1. while (size > 1 && digits[size - 1] == 0) { size--; } // STRIP LEADING ZEROS while (size > 0 && digits[size - 1] == 0) size--; // If the input was "0", size should be 0, not 1. } std::string rsa::bigInt::toString() const { Loading @@ -111,28 +140,50 @@ namespace netplus { } bool rsa::bigInt::isZero() const { // A number is zero if size is 0, or if all digits up to size are 0 if (size == 0) return true; if (size == 1 && digits[0] == 0) return true; return false; for (size_t i = 0; i < size; ++i) { if (digits[i] != 0) return false; } return true; } bool rsa::bigInt::isEven() const { return size == 0 || digits[0] % 2 == 0; } // --- RSA Math Engine --- int rsa::compare(const bigInt& a, const bigInt& b) { // 1. Get actual sizes ignoring leading zeros size_t a_real = a.size; while (a_real > 0 && a.digits[a_real - 1] == 0) a_real--; rsa::rsa() : n(1024), e(1024), d(1024) {} size_t b_real = b.size; while (b_real > 0 && b.digits[b_real - 1] == 0) b_real--; int rsa::compare(const bigInt& a, const bigInt& b) { if (a.size != b.size) return (a.size < b.size) ? -1 : 1; if (a_real > b_real) return 1; if (a_real < b_real) return -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; // 2. Same size, compare digit by digit from most significant for (int i = (int)a_real - 1; i >= 0; i--) { if (a.digits[i] > b.digits[i]) return 1; if (a.digits[i] < b.digits[i]) return -1; } return 0; } bool rsa::bigInt::isEven() const { return size == 0 || digits[0] % 2 == 0; } void rsa::bigInt::divideByTwo() { int carry = 0; for (int i = (int)size - 1; i >= 0; i--) { int cur = digits[i] + carry * 10; digits[i] = cur / 2; carry = cur % 2; } while (size > 0 && digits[size - 1] == 0) size--; if (size == 0) { size = 1; digits[0] = 0; } } // --- RSA Math Engine --- rsa::rsa() : n(1024), e(1024), d(1024) {} void rsa::add(const bigInt& a, const bigInt& b, bigInt& res) { int carry = 0; size_t nSize = std::max(a.size, b.size); Loading @@ -145,14 +196,15 @@ namespace netplus { } void rsa::subtract(const bigInt& a, const bigInt& b, bigInt& res) { // Ensure res has enough capacity if (res.capacity < a.size) { res.digits = std::make_unique<int[]>(a.size); res.capacity = a.size; // Assumption: a >= b. EEA logic handles signs by comparing before calling this. size_t nSize = a.size; if (res.capacity < nSize) { res.digits = std::make_unique<int[]>(nSize + 2); res.capacity = nSize + 2; } int borrow = 0; for (size_t i = 0; i < a.size; ++i) { for (size_t i = 0; i < nSize; ++i) { int sub = a.digits[i] - borrow - (i < b.size ? b.digits[i] : 0); if (sub < 0) { sub += 10; Loading @@ -163,44 +215,62 @@ namespace netplus { res.digits[i] = sub; } // Zero out the remaining digits in res buffer to prevent "ghost" numbers for (size_t i = a.size; i < res.capacity; ++i) { res.digits[i] = 0; } res.size = nSize; // Wipe remaining capacity for (size_t k = res.size; k < res.capacity; ++k) res.digits[k] = 0; // Shrink size int newSize = (int)a.size; while (newSize > 0 && res.digits[newSize - 1] == 0) { newSize--; // Stripping leading zeros but keeping at least one digit while (res.size > 1 && res.digits[res.size - 1] == 0) { res.size--; } res.size = (size_t)newSize; } void rsa::multiply(const bigInt& a, const bigInt& b, bigInt& res) { // 1. Check if res has enough room. a.size + b.size is the max possible result size. if (res.capacity < a.size + b.size) { res.digits = std::make_unique<int[]>(a.size + b.size + 2); res.capacity = a.size + b.size + 2; // 1. If either is 0, the result is 0 if (a.isZero() || b.isZero()) { res.fromString("0"); return; } // 2. Clear the buffer // 2. Clear res buffer completely for (size_t k = 0; k < res.capacity; ++k) res.digits[k] = 0; // 3. Multiplication logic... // 3. Multiplication loop for (size_t i = 0; i < a.size; ++i) { int carry = 0; long long carry = 0; for (size_t j = 0; j < b.size || carry; ++j) { // Safety check to prevent the invalid pointer error if (i + j >= res.capacity) break; long long cur = res.digits[i + j] + a.digits[i] * 1LL * (j < b.size ? b.digits[j] : 0) + carry; 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); carry = (int)(cur / 10); carry = cur / 10; } } // 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--; } 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; } // Print in reverse (MSB to LSB) for (int i = (int)size - 1; i >= 0; i--) { std::cout << digits[i]; } // ... update size and strip zeros res.size = a.size + b.size; while (res.size > 0 && res.digits[res.size - 1] == 0) res.size--; // 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; } void rsa::divide(const bigInt& dividend, const bigInt& divisor, bigInt& quotient, bigInt& remainder) { Loading @@ -208,113 +278,79 @@ namespace netplus { // 1. Reset Quotient for (size_t k = 0; k < quotient.capacity; ++k) quotient.digits[k] = 0; quotient.size = 0; quotient.size = 1; // 2. Reset Remainder for (size_t k = 0; k < remainder.capacity; ++k) remainder.digits[k] = 0; remainder.size = 0; // 2. Reset Remainder to 0 remainder.size = 1; remainder.digits[0] = 0; // Long division algorithm // 3. Process dividend from Most Significant Digit to Least for (int i = (int)dividend.size - 1; i >= 0; i--) { // SHIFT: remainder = remainder * 10 if (remainder.size > 0 || dividend.digits[i] > 0) { // Ensure room for shift + new digit // Shift remainder left by 1 (multiply by 10) if (!(remainder.size == 1 && remainder.digits[0] == 0)) { // Check capacity before shifting if (remainder.size + 1 >= remainder.capacity) { size_t newCap = remainder.capacity + 16; auto newDigits = std::make_unique<int[]>(newCap); for (size_t k = 0; k < remainder.size; ++k) newDigits[k + 1] = remainder.digits[k]; for (size_t k = remainder.size + 1; k < newCap; ++k) newDigits[k] = 0; remainder.digits = std::move(newDigits); remainder.capacity = newCap; } else { // Manual resize or throw error if capacity is too low throw std::runtime_error("Remainder capacity exceeded in divide"); } for (int j = (int)remainder.size; j > 0; j--) { remainder.digits[j] = remainder.digits[j - 1]; } } // Pull down next digit remainder.digits[0] = dividend.digits[i]; remainder.size++; while (remainder.size > 0 && remainder.digits[remainder.size - 1] == 0) remainder.size--; } // SUBTRACT LOOP: Find how many times divisor fits in remainder // Add current digit from dividend remainder.digits[0] = dividend.digits[i]; // 4. Inner loop: How many times does divisor fit? // This runs at most 9 times per dividend digit. int count = 0; while (compare(remainder, divisor) >= 0) { // Use a temporary with enough capacity for subtraction bigInt temp(remainder.capacity); subtract(remainder, divisor, temp); remainder = std::move(temp); // We use a temporary here only to satisfy your subtract(a, b, res) signature // but we subtract directly into remainder subtract(remainder, divisor, remainder); count++; } // UPDATE QUOTIENT if (count > 0) { // Ensure quotient has capacity for the current index if ((size_t)i >= quotient.capacity) { size_t newCap = (size_t)i + 16; auto newQDigits = std::make_unique<int[]>(newCap); for (size_t k = 0; k < quotient.capacity; ++k) newQDigits[k] = quotient.digits[k]; for (size_t k = quotient.capacity; k < newCap; ++k) newQDigits[k] = 0; quotient.digits = std::move(newQDigits); quotient.capacity = newCap; } quotient.digits[i] = count; if ((size_t)i + 1 > quotient.size) quotient.size = (size_t)i + 1; } } // Final trim of leading zeros for quotient while (quotient.size > 0 && quotient.digits[quotient.size - 1] == 0) quotient.size--; // 5. Final Size Adjustments quotient.size = dividend.size; while (quotient.size > 1 && quotient.digits[quotient.size - 1] == 0) quotient.size--; if (remainder.size == 0) remainder.size = 1; while (remainder.size > 1 && remainder.digits[remainder.size - 1] == 0) remainder.size--; } rsa::bigInt rsa::modPow(bigInt base, bigInt exp, const bigInt& mod) { // Result starts at 1 bigInt res(mod.capacity); bigInt res(mod.capacity + 2); res.fromString("1"); // Copy base to a local variable with enough capacity for squaring // Capacity should be at least 2x the modulus digits size_t workCap = mod.capacity * 2 + 2; bigInt current_base(workCap); // Initial reduction: current_base = base % mod { bigInt q_init(base.capacity), r_init(mod.capacity); divide(base, mod, q_init, r_init); current_base = r_init; // Use assignment to keep workCap } bigInt curr_base = base; bigInt curr_exp = exp; bigInt two(1); two.fromString("2"); while (!curr_exp.isZero()) { if (!curr_exp.isEven()) { bigInt temp_mul(curr_base.capacity + res.capacity + 1); multiply(res, curr_base, temp_mul); // Copy exponent so we can modify it bigInt current_exp = exp; while (!current_exp.isZero()) { if (!current_exp.isEven()) { // res = (res * current_base) % mod bigInt tempMul(workCap); multiply(res, current_base, tempMul); bigInt q(tempMul.capacity), r(mod.capacity); divide(tempMul, mod, q, r); res = r; bigInt r(mod.capacity + 2); bigInt q(temp_mul.capacity + 2); divide(temp_mul, mod, q, r); res = r; // This calls operator= } // current_base = (current_base * current_base) % mod bigInt tempSquare(workCap); multiply(current_base, current_base, tempSquare); // Squaring step bigInt sq(curr_base.capacity * 2 + 2); multiply(curr_base, curr_base, sq); bigInt q_sq(tempSquare.capacity), r_sq(mod.capacity); divide(tempSquare, mod, q_sq, r_sq); current_base = r_sq; bigInt r_sq(mod.capacity + 2); bigInt q_sq(sq.capacity + 2); divide(sq, mod, q_sq, r_sq); curr_base = r_sq; // exp = exp / 2 bigInt q_exp(current_exp.capacity), r_exp(2); divide(current_exp, two, q_exp, r_exp); current_exp = q_exp; curr_exp.divideByTwo(); } return res; } Loading @@ -328,36 +364,31 @@ namespace netplus { while (!temp_b.isZero()) { bigInt q(temp_a.capacity), r(temp_a.capacity); divide(temp_a, temp_b, q, r); temp_a = std::move(temp_b); temp_b = std::move(r); temp_a = temp_b; // Assignment copies the digits safely temp_b = r; } return temp_a; } // Modular Multiplicative Inverse rsa::bigInt rsa::modInverse(bigInt e, bigInt phi) { bigInt x0(phi.capacity), x1(phi.capacity); x0.fromString("0"); x1.fromString("1"); bigInt a = phi; // <-- swap bigInt b = e; // <-- swap bigInt a = e, b = phi; bigInt x0(phi.capacity + 2); x0.fromString("0"); bigInt x1(phi.capacity + 2); x1.fromString("1"); bool x0_pos = true, x1_pos = true; // EEA Loop while (!b.isZero()) { bigInt q(a.capacity), r(a.capacity); bigInt q(a.capacity + 2), r(a.capacity + 2); divide(a, b, q, r); // Update a and b a = b; b = r; // next_x = x0 - q * x1 bigInt qx1(q.capacity + x1.capacity); bigInt qx1(q.capacity + x1.capacity + 2); multiply(q, x1, qx1); bigInt next_x(phi.capacity + 2); bigInt next_x(phi.capacity + 4); bool next_x_pos; // next_x = x0 - q*x1 (with sign handling) if (x0_pos == x1_pos) { if (compare(x0, qx1) >= 0) { subtract(x0, qx1, next_x); Loading @@ -371,19 +402,19 @@ namespace netplus { next_x_pos = x0_pos; } // Shift coefficients a = b; b = r; x0 = x1; x0_pos = x1_pos; x1 = next_x; x1_pos = next_x_pos; } // After b becomes 0, a contains GCD(e, phi). // The inverse is the coefficient that was in x1 BEFORE the last update, // which is now stored in x0. // x0 is the inverse; normalize to [0, phi) if (!x0_pos && !x0.isZero()) { bigInt res(phi.capacity); subtract(phi, x0, res); return res; bigInt tmp(phi.capacity + 2); // tmp = x0 % phi (optional if x0 can exceed phi) // simplest normalization if |x0| < phi: subtract(phi, x0, tmp); return tmp; } return x0; } Loading Loading @@ -424,85 +455,57 @@ namespace netplus { } bool rsa::isProbablyPrime(const bigInt& n, int k) { // Create temporary bigInts for comparison bigInt one(n.capacity), three(n.capacity); one.fromString("1"); three.fromString("3"); // 1. Basic checks if (compare(n, one) <= 0) return false; // n <= 1 if (compare(n, three) <= 0) return true; // n is 2 or 3 if (n.isEven()) return false; // Even numbers > 2 are not prime // 2. Write n-1 as 2^s * d bigInt two(n.capacity); two.fromString("2"); bigInt nm1(n.capacity); bigInt one(1), two(1), nm1(n.capacity); one.fromString("1"); two.fromString("2"); subtract(n, one, nm1); if (compare(n, one) <= 0) return false; if (n.isEven()) return compare(n, two) == 0; bigInt d = nm1; size_t s = 0; // While d is even, divide by 2 while (d.isEven() && !d.isZero()) { bigInt next_d(d.capacity); bigInt r_exp(d.capacity); divide(d, two, next_d, r_exp); d = std::move(next_d); while (d.isEven()) { d.divideByTwo(); s++; } // 3. Witness loop (Miller-Rabin rounds) for (int i = 0; i < k; i++) { // Pick a witness. For simplicity, we use 2. // In a full implementation, pick a random 'a' in [2, n-2] bigInt a(n.capacity); a.fromString("2"); bigInt a(1); a.fromString("2"); // Simplified witness bigInt x = modPow(a, d, n); // If x == 1 or x == n-1 if (x.toString() == "1" || x.toString() == nm1.toString()) continue; if (x.toString() == "1" || compare(x, nm1) == 0) continue; bool composite = true; for (size_t r = 1; r < s; r++) { x = modPow(x, two, n); // Square: x = x^2 % n if (x.toString() == nm1.toString()) { x = modPow(x, two, n); if (compare(x, nm1) == 0) { composite = false; break; } } if (composite) return false; } return true; } void rsa::findPrime(bigInt& p, size_t digits) { bigInt two(1); two.fromString("2"); // 1. Start with a random candidate generateSecureRandom(p, digits); // 2. Keep incrementing by 2 until we hit a prime // 40 rounds of Miller-Rabin is standard for 1024-bit primes while (!isProbablyPrime(p, 40)) { bigInt next_p(p.capacity + 1); while (!isProbablyPrime(p, 10)) { // 10 rounds is enough for testing bigInt next_p(p.capacity + 2); add(p, two, next_p); p = std::move(next_p); p = next_p; // Assignment, NOT move } } void rsa::generateKeys(size_t digit_count) { bigInt p(digit_count), q(digit_count); // Generate two distinct primes findPrime(p, digit_count); findPrime(q, digit_count); multiply(p, q, n); // n = p * q multiply(p, q, n); bigInt one(1); one.fromString("1"); bigInt two(1); two.fromString("2"); Loading @@ -512,17 +515,22 @@ namespace netplus { subtract(q, one, qm1); multiply(pm1, qm1, phi); e.fromString("17"); // Default candidate // Increment e until it is coprime with phi e.fromString("17"); while (gcd(e, phi).toString() != "1") { bigInt next_e(e.capacity); add(e, two, next_e); e = std::move(next_e); } d = modInverse(e, phi); std::cerr << "d: " << d.toString() << "e: " << e.toString() << "phi: " << phi.toString() << std::endl; // ✅ Store in the member, not a local shadow this->d = modInverse(e, phi); // verify bigInt check(n.capacity * 2); multiply(e, this->d, check); bigInt q_c(check.capacity), r_c(phi.capacity); divide(check, phi, q_c, r_c); std::cout << "EEA VERIFY: (e*d % phi) = " << r_c.toString() << std::endl; } rsa::bigInt rsa::encrypt(const bigInt& m) { return modPow(m, e, n); } Loading src/crypto/rsa.h +2 −0 Changes for src/crypto/rsa.h: 2 added lines, 0 removed lines. Original line number Diff line number Diff line Loading @@ -52,6 +52,8 @@ namespace netplus { std::string toString() const; bool isZero() const; bool isEven() const; void divideByTwo(); void printDebug(const std::string& label) const ; }; rsa(); Loading Loading
src/crypto/rsa.cpp +212 −204 Changes for src/crypto/rsa.cpp: 212 added lines, 204 removed lines. Original line number Diff line number Diff line Loading @@ -58,22 +58,24 @@ namespace netplus { } rsa::bigInt& rsa::bigInt::operator=(const bigInt& other) { if (this != &other) { // Only reallocate if we absolutely must if (this == &other) return *this; // 1. Ensure enough capacity if (this->capacity < other.size) { // make_unique creates a NEW buffer; unique_ptr::operator= // will then safely delete the OLD buffer. digits = std::make_unique<int[]>(other.capacity); capacity = other.capacity; auto new_digits = std::make_unique<int[]>(other.size + 2); digits = std::move(new_digits); capacity = other.size + 2; } // 2. Copy the size this->size = other.size; // Reset the entire buffer to 0 first to prevent garbage data // 3. Copy the digits and ZERO out the rest of the capacity // This prevents "ghost digits" from previous values for (size_t i = 0; i < capacity; ++i) { digits[i] = (i < other.size) ? other.digits[i] : 0; } } return *this; } Loading @@ -93,14 +95,41 @@ namespace netplus { } void rsa::bigInt::fromString(const std::string& s) { // 1. Handle empty string as zero if (s.empty()) { size = 1; digits[0] = 0; return; } // 2. Adjust capacity if the string is longer than current allocation if (s.length() > capacity) { digits = std::make_unique<int[]>(s.length() + 2); capacity = s.length() + 2; } // 3. Convert characters to digits in REVERSE order // String "123" -> digits[0]=3, digits[1]=2, digits[2]=1 size = s.length(); // ... allocation logic ... for (size_t i = 0; i < size; ++i) { digits[i] = s[size - 1 - i] - '0'; char c = s[size - 1 - i]; if (c >= '0' && c <= '9') { digits[i] = c - '0'; } else { digits[i] = 0; // Or throw an error for invalid characters } } // 4. Wipe any old data in the remaining capacity (Ghost Digits) for (size_t i = size; i < capacity; ++i) { digits[i] = 0; } // 5. Strip leading zeros, but keep at least one digit // Example: "000123" should have size 3. "000" should have size 1. while (size > 1 && digits[size - 1] == 0) { size--; } // STRIP LEADING ZEROS while (size > 0 && digits[size - 1] == 0) size--; // If the input was "0", size should be 0, not 1. } std::string rsa::bigInt::toString() const { Loading @@ -111,28 +140,50 @@ namespace netplus { } bool rsa::bigInt::isZero() const { // A number is zero if size is 0, or if all digits up to size are 0 if (size == 0) return true; if (size == 1 && digits[0] == 0) return true; return false; for (size_t i = 0; i < size; ++i) { if (digits[i] != 0) return false; } return true; } bool rsa::bigInt::isEven() const { return size == 0 || digits[0] % 2 == 0; } // --- RSA Math Engine --- int rsa::compare(const bigInt& a, const bigInt& b) { // 1. Get actual sizes ignoring leading zeros size_t a_real = a.size; while (a_real > 0 && a.digits[a_real - 1] == 0) a_real--; rsa::rsa() : n(1024), e(1024), d(1024) {} size_t b_real = b.size; while (b_real > 0 && b.digits[b_real - 1] == 0) b_real--; int rsa::compare(const bigInt& a, const bigInt& b) { if (a.size != b.size) return (a.size < b.size) ? -1 : 1; if (a_real > b_real) return 1; if (a_real < b_real) return -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; // 2. Same size, compare digit by digit from most significant for (int i = (int)a_real - 1; i >= 0; i--) { if (a.digits[i] > b.digits[i]) return 1; if (a.digits[i] < b.digits[i]) return -1; } return 0; } bool rsa::bigInt::isEven() const { return size == 0 || digits[0] % 2 == 0; } void rsa::bigInt::divideByTwo() { int carry = 0; for (int i = (int)size - 1; i >= 0; i--) { int cur = digits[i] + carry * 10; digits[i] = cur / 2; carry = cur % 2; } while (size > 0 && digits[size - 1] == 0) size--; if (size == 0) { size = 1; digits[0] = 0; } } // --- RSA Math Engine --- rsa::rsa() : n(1024), e(1024), d(1024) {} void rsa::add(const bigInt& a, const bigInt& b, bigInt& res) { int carry = 0; size_t nSize = std::max(a.size, b.size); Loading @@ -145,14 +196,15 @@ namespace netplus { } void rsa::subtract(const bigInt& a, const bigInt& b, bigInt& res) { // Ensure res has enough capacity if (res.capacity < a.size) { res.digits = std::make_unique<int[]>(a.size); res.capacity = a.size; // Assumption: a >= b. EEA logic handles signs by comparing before calling this. size_t nSize = a.size; if (res.capacity < nSize) { res.digits = std::make_unique<int[]>(nSize + 2); res.capacity = nSize + 2; } int borrow = 0; for (size_t i = 0; i < a.size; ++i) { for (size_t i = 0; i < nSize; ++i) { int sub = a.digits[i] - borrow - (i < b.size ? b.digits[i] : 0); if (sub < 0) { sub += 10; Loading @@ -163,44 +215,62 @@ namespace netplus { res.digits[i] = sub; } // Zero out the remaining digits in res buffer to prevent "ghost" numbers for (size_t i = a.size; i < res.capacity; ++i) { res.digits[i] = 0; } res.size = nSize; // Wipe remaining capacity for (size_t k = res.size; k < res.capacity; ++k) res.digits[k] = 0; // Shrink size int newSize = (int)a.size; while (newSize > 0 && res.digits[newSize - 1] == 0) { newSize--; // Stripping leading zeros but keeping at least one digit while (res.size > 1 && res.digits[res.size - 1] == 0) { res.size--; } res.size = (size_t)newSize; } void rsa::multiply(const bigInt& a, const bigInt& b, bigInt& res) { // 1. Check if res has enough room. a.size + b.size is the max possible result size. if (res.capacity < a.size + b.size) { res.digits = std::make_unique<int[]>(a.size + b.size + 2); res.capacity = a.size + b.size + 2; // 1. If either is 0, the result is 0 if (a.isZero() || b.isZero()) { res.fromString("0"); return; } // 2. Clear the buffer // 2. Clear res buffer completely for (size_t k = 0; k < res.capacity; ++k) res.digits[k] = 0; // 3. Multiplication logic... // 3. Multiplication loop for (size_t i = 0; i < a.size; ++i) { int carry = 0; long long carry = 0; for (size_t j = 0; j < b.size || carry; ++j) { // Safety check to prevent the invalid pointer error if (i + j >= res.capacity) break; long long cur = res.digits[i + j] + a.digits[i] * 1LL * (j < b.size ? b.digits[j] : 0) + carry; 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); carry = (int)(cur / 10); carry = cur / 10; } } // 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--; } 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; } // Print in reverse (MSB to LSB) for (int i = (int)size - 1; i >= 0; i--) { std::cout << digits[i]; } // ... update size and strip zeros res.size = a.size + b.size; while (res.size > 0 && res.digits[res.size - 1] == 0) res.size--; // 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; } void rsa::divide(const bigInt& dividend, const bigInt& divisor, bigInt& quotient, bigInt& remainder) { Loading @@ -208,113 +278,79 @@ namespace netplus { // 1. Reset Quotient for (size_t k = 0; k < quotient.capacity; ++k) quotient.digits[k] = 0; quotient.size = 0; quotient.size = 1; // 2. Reset Remainder for (size_t k = 0; k < remainder.capacity; ++k) remainder.digits[k] = 0; remainder.size = 0; // 2. Reset Remainder to 0 remainder.size = 1; remainder.digits[0] = 0; // Long division algorithm // 3. Process dividend from Most Significant Digit to Least for (int i = (int)dividend.size - 1; i >= 0; i--) { // SHIFT: remainder = remainder * 10 if (remainder.size > 0 || dividend.digits[i] > 0) { // Ensure room for shift + new digit // Shift remainder left by 1 (multiply by 10) if (!(remainder.size == 1 && remainder.digits[0] == 0)) { // Check capacity before shifting if (remainder.size + 1 >= remainder.capacity) { size_t newCap = remainder.capacity + 16; auto newDigits = std::make_unique<int[]>(newCap); for (size_t k = 0; k < remainder.size; ++k) newDigits[k + 1] = remainder.digits[k]; for (size_t k = remainder.size + 1; k < newCap; ++k) newDigits[k] = 0; remainder.digits = std::move(newDigits); remainder.capacity = newCap; } else { // Manual resize or throw error if capacity is too low throw std::runtime_error("Remainder capacity exceeded in divide"); } for (int j = (int)remainder.size; j > 0; j--) { remainder.digits[j] = remainder.digits[j - 1]; } } // Pull down next digit remainder.digits[0] = dividend.digits[i]; remainder.size++; while (remainder.size > 0 && remainder.digits[remainder.size - 1] == 0) remainder.size--; } // SUBTRACT LOOP: Find how many times divisor fits in remainder // Add current digit from dividend remainder.digits[0] = dividend.digits[i]; // 4. Inner loop: How many times does divisor fit? // This runs at most 9 times per dividend digit. int count = 0; while (compare(remainder, divisor) >= 0) { // Use a temporary with enough capacity for subtraction bigInt temp(remainder.capacity); subtract(remainder, divisor, temp); remainder = std::move(temp); // We use a temporary here only to satisfy your subtract(a, b, res) signature // but we subtract directly into remainder subtract(remainder, divisor, remainder); count++; } // UPDATE QUOTIENT if (count > 0) { // Ensure quotient has capacity for the current index if ((size_t)i >= quotient.capacity) { size_t newCap = (size_t)i + 16; auto newQDigits = std::make_unique<int[]>(newCap); for (size_t k = 0; k < quotient.capacity; ++k) newQDigits[k] = quotient.digits[k]; for (size_t k = quotient.capacity; k < newCap; ++k) newQDigits[k] = 0; quotient.digits = std::move(newQDigits); quotient.capacity = newCap; } quotient.digits[i] = count; if ((size_t)i + 1 > quotient.size) quotient.size = (size_t)i + 1; } } // Final trim of leading zeros for quotient while (quotient.size > 0 && quotient.digits[quotient.size - 1] == 0) quotient.size--; // 5. Final Size Adjustments quotient.size = dividend.size; while (quotient.size > 1 && quotient.digits[quotient.size - 1] == 0) quotient.size--; if (remainder.size == 0) remainder.size = 1; while (remainder.size > 1 && remainder.digits[remainder.size - 1] == 0) remainder.size--; } rsa::bigInt rsa::modPow(bigInt base, bigInt exp, const bigInt& mod) { // Result starts at 1 bigInt res(mod.capacity); bigInt res(mod.capacity + 2); res.fromString("1"); // Copy base to a local variable with enough capacity for squaring // Capacity should be at least 2x the modulus digits size_t workCap = mod.capacity * 2 + 2; bigInt current_base(workCap); // Initial reduction: current_base = base % mod { bigInt q_init(base.capacity), r_init(mod.capacity); divide(base, mod, q_init, r_init); current_base = r_init; // Use assignment to keep workCap } bigInt curr_base = base; bigInt curr_exp = exp; bigInt two(1); two.fromString("2"); while (!curr_exp.isZero()) { if (!curr_exp.isEven()) { bigInt temp_mul(curr_base.capacity + res.capacity + 1); multiply(res, curr_base, temp_mul); // Copy exponent so we can modify it bigInt current_exp = exp; while (!current_exp.isZero()) { if (!current_exp.isEven()) { // res = (res * current_base) % mod bigInt tempMul(workCap); multiply(res, current_base, tempMul); bigInt q(tempMul.capacity), r(mod.capacity); divide(tempMul, mod, q, r); res = r; bigInt r(mod.capacity + 2); bigInt q(temp_mul.capacity + 2); divide(temp_mul, mod, q, r); res = r; // This calls operator= } // current_base = (current_base * current_base) % mod bigInt tempSquare(workCap); multiply(current_base, current_base, tempSquare); // Squaring step bigInt sq(curr_base.capacity * 2 + 2); multiply(curr_base, curr_base, sq); bigInt q_sq(tempSquare.capacity), r_sq(mod.capacity); divide(tempSquare, mod, q_sq, r_sq); current_base = r_sq; bigInt r_sq(mod.capacity + 2); bigInt q_sq(sq.capacity + 2); divide(sq, mod, q_sq, r_sq); curr_base = r_sq; // exp = exp / 2 bigInt q_exp(current_exp.capacity), r_exp(2); divide(current_exp, two, q_exp, r_exp); current_exp = q_exp; curr_exp.divideByTwo(); } return res; } Loading @@ -328,36 +364,31 @@ namespace netplus { while (!temp_b.isZero()) { bigInt q(temp_a.capacity), r(temp_a.capacity); divide(temp_a, temp_b, q, r); temp_a = std::move(temp_b); temp_b = std::move(r); temp_a = temp_b; // Assignment copies the digits safely temp_b = r; } return temp_a; } // Modular Multiplicative Inverse rsa::bigInt rsa::modInverse(bigInt e, bigInt phi) { bigInt x0(phi.capacity), x1(phi.capacity); x0.fromString("0"); x1.fromString("1"); bigInt a = phi; // <-- swap bigInt b = e; // <-- swap bigInt a = e, b = phi; bigInt x0(phi.capacity + 2); x0.fromString("0"); bigInt x1(phi.capacity + 2); x1.fromString("1"); bool x0_pos = true, x1_pos = true; // EEA Loop while (!b.isZero()) { bigInt q(a.capacity), r(a.capacity); bigInt q(a.capacity + 2), r(a.capacity + 2); divide(a, b, q, r); // Update a and b a = b; b = r; // next_x = x0 - q * x1 bigInt qx1(q.capacity + x1.capacity); bigInt qx1(q.capacity + x1.capacity + 2); multiply(q, x1, qx1); bigInt next_x(phi.capacity + 2); bigInt next_x(phi.capacity + 4); bool next_x_pos; // next_x = x0 - q*x1 (with sign handling) if (x0_pos == x1_pos) { if (compare(x0, qx1) >= 0) { subtract(x0, qx1, next_x); Loading @@ -371,19 +402,19 @@ namespace netplus { next_x_pos = x0_pos; } // Shift coefficients a = b; b = r; x0 = x1; x0_pos = x1_pos; x1 = next_x; x1_pos = next_x_pos; } // After b becomes 0, a contains GCD(e, phi). // The inverse is the coefficient that was in x1 BEFORE the last update, // which is now stored in x0. // x0 is the inverse; normalize to [0, phi) if (!x0_pos && !x0.isZero()) { bigInt res(phi.capacity); subtract(phi, x0, res); return res; bigInt tmp(phi.capacity + 2); // tmp = x0 % phi (optional if x0 can exceed phi) // simplest normalization if |x0| < phi: subtract(phi, x0, tmp); return tmp; } return x0; } Loading Loading @@ -424,85 +455,57 @@ namespace netplus { } bool rsa::isProbablyPrime(const bigInt& n, int k) { // Create temporary bigInts for comparison bigInt one(n.capacity), three(n.capacity); one.fromString("1"); three.fromString("3"); // 1. Basic checks if (compare(n, one) <= 0) return false; // n <= 1 if (compare(n, three) <= 0) return true; // n is 2 or 3 if (n.isEven()) return false; // Even numbers > 2 are not prime // 2. Write n-1 as 2^s * d bigInt two(n.capacity); two.fromString("2"); bigInt nm1(n.capacity); bigInt one(1), two(1), nm1(n.capacity); one.fromString("1"); two.fromString("2"); subtract(n, one, nm1); if (compare(n, one) <= 0) return false; if (n.isEven()) return compare(n, two) == 0; bigInt d = nm1; size_t s = 0; // While d is even, divide by 2 while (d.isEven() && !d.isZero()) { bigInt next_d(d.capacity); bigInt r_exp(d.capacity); divide(d, two, next_d, r_exp); d = std::move(next_d); while (d.isEven()) { d.divideByTwo(); s++; } // 3. Witness loop (Miller-Rabin rounds) for (int i = 0; i < k; i++) { // Pick a witness. For simplicity, we use 2. // In a full implementation, pick a random 'a' in [2, n-2] bigInt a(n.capacity); a.fromString("2"); bigInt a(1); a.fromString("2"); // Simplified witness bigInt x = modPow(a, d, n); // If x == 1 or x == n-1 if (x.toString() == "1" || x.toString() == nm1.toString()) continue; if (x.toString() == "1" || compare(x, nm1) == 0) continue; bool composite = true; for (size_t r = 1; r < s; r++) { x = modPow(x, two, n); // Square: x = x^2 % n if (x.toString() == nm1.toString()) { x = modPow(x, two, n); if (compare(x, nm1) == 0) { composite = false; break; } } if (composite) return false; } return true; } void rsa::findPrime(bigInt& p, size_t digits) { bigInt two(1); two.fromString("2"); // 1. Start with a random candidate generateSecureRandom(p, digits); // 2. Keep incrementing by 2 until we hit a prime // 40 rounds of Miller-Rabin is standard for 1024-bit primes while (!isProbablyPrime(p, 40)) { bigInt next_p(p.capacity + 1); while (!isProbablyPrime(p, 10)) { // 10 rounds is enough for testing bigInt next_p(p.capacity + 2); add(p, two, next_p); p = std::move(next_p); p = next_p; // Assignment, NOT move } } void rsa::generateKeys(size_t digit_count) { bigInt p(digit_count), q(digit_count); // Generate two distinct primes findPrime(p, digit_count); findPrime(q, digit_count); multiply(p, q, n); // n = p * q multiply(p, q, n); bigInt one(1); one.fromString("1"); bigInt two(1); two.fromString("2"); Loading @@ -512,17 +515,22 @@ namespace netplus { subtract(q, one, qm1); multiply(pm1, qm1, phi); e.fromString("17"); // Default candidate // Increment e until it is coprime with phi e.fromString("17"); while (gcd(e, phi).toString() != "1") { bigInt next_e(e.capacity); add(e, two, next_e); e = std::move(next_e); } d = modInverse(e, phi); std::cerr << "d: " << d.toString() << "e: " << e.toString() << "phi: " << phi.toString() << std::endl; // ✅ Store in the member, not a local shadow this->d = modInverse(e, phi); // verify bigInt check(n.capacity * 2); multiply(e, this->d, check); bigInt q_c(check.capacity), r_c(phi.capacity); divide(check, phi, q_c, r_c); std::cout << "EEA VERIFY: (e*d % phi) = " << r_c.toString() << std::endl; } rsa::bigInt rsa::encrypt(const bigInt& m) { return modPow(m, e, n); } Loading
src/crypto/rsa.h +2 −0 Changes for src/crypto/rsa.h: 2 added lines, 0 removed lines. Original line number Diff line number Diff line Loading @@ -52,6 +52,8 @@ namespace netplus { std::string toString() const; bool isZero() const; bool isEven() const; void divideByTwo(); void printDebug(const std::string& label) const ; }; rsa(); Loading