Loading src/crypto/rsa.cpp +354 −92 Changes for src/crypto/rsa.cpp: 354 added lines, 92 removed lines. Original line number Diff line number Diff line Loading @@ -23,8 +23,17 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include <stdexcept> #include <iostream> #include <algorithm> #include <stdexcept> #ifdef _WIN32 #include <windows.h> #include <bcrypt.h> #pragma comment(lib, "bcrypt.lib") #else #include <fstream> #endif #include "rsa.h" Loading @@ -50,22 +59,33 @@ namespace netplus { rsa::bigInt& rsa::bigInt::operator=(const bigInt& other) { if (this != &other) { if (capacity < other.size) { // Only reallocate if we absolutely must 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; } size = other.size; for (size_t i = 0; i < capacity; ++i) this->size = other.size; // Reset the entire buffer to 0 first to prevent garbage data 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 { netplus::rsa::bigInt& netplus::rsa::bigInt::operator=(bigInt&& other) noexcept { if (this != &other) { // This transfers the pointer ownership and automatically // cleans up the old 'this->digits' memory. digits = std::move(other.digits); size = other.size; capacity = other.capacity; // Ensure 'other' is left in a safe, empty state other.size = 0; other.capacity = 0; } Loading @@ -74,14 +94,13 @@ namespace netplus { void rsa::bigInt::fromString(const std::string& s) { size = s.length(); if (size > capacity) { digits = std::make_unique<int[]>(size); capacity = size; } // ... allocation logic ... for (size_t i = 0; i < size; ++i) { digits[i] = s[size - 1 - i] - '0'; } // 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 @@ -91,7 +110,12 @@ namespace netplus { return s; } bool rsa::bigInt::isZero() const { return size == 0; } bool rsa::bigInt::isZero() const { if (size == 0) return true; if (size == 1 && digits[0] == 0) return true; return false; } bool rsa::bigInt::isEven() const { return size == 0 || digits[0] % 2 == 0; } // --- RSA Math Engine --- Loading @@ -99,9 +123,12 @@ namespace netplus { 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; 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; if (a.digits[i] != b.digits[i]) return (a.digits[i] < b.digits[i]) ? -1 : 1; } return 0; } Loading @@ -118,151 +145,386 @@ 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; } 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; 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--; // 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; } // Shrink size int newSize = (int)a.size; while (newSize > 0 && res.digits[newSize - 1] == 0) { newSize--; } 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; } // 2. Clear the buffer for (size_t k = 0; k < res.capacity; ++k) res.digits[k] = 0; // 3. Multiplication logic... for (size_t i = 0; i < a.size; ++i) { int 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; res.digits[i + j] = cur % 10; res.digits[i + j] = (int)(cur % 10); carry = (int)(cur / 10); } } // ... update size and strip zeros 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; // 1. Reset Quotient for (size_t k = 0; k < quotient.capacity; ++k) quotient.digits[k] = 0; quotient.size = 0; // 2. Reset Remainder for (size_t k = 0; k < remainder.capacity; ++k) remainder.digits[k] = 0; remainder.size = 0; // Long division algorithm 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]; // SHIFT: remainder = remainder * 10 if (remainder.size > 0 || dividend.digits[i] > 0) { // Ensure room for shift + new digit 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 { 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]; if (remainder.digits[remainder.size] > 0 || remainder.size == 0) remainder.size++; remainder.size++; while (remainder.size > 0 && remainder.digits[remainder.size - 1] == 0) remainder.size--; } int q = 0; // SUBTRACT LOOP: Find how many times divisor fits in remainder 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 = temp; q++; remainder = std::move(temp); 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; } quotient.digits[i] = q; } size_t qs = dividend.size; while (qs > 0 && quotient.digits[qs - 1] == 0) qs--; quotient.size = qs; // Final trim of leading zeros for quotient while (quotient.size > 0 && quotient.digits[quotient.size - 1] == 0) quotient.size--; } 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; // Result starts at 1 bigInt res(mod.capacity); 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 two(1); two.fromString("2"); // 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; } // current_base = (current_base * current_base) % mod bigInt tempSquare(workCap); multiply(current_base, current_base, tempSquare); bigInt q_sq(tempSquare.capacity), r_sq(mod.capacity); divide(tempSquare, mod, q_sq, r_sq); current_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; } return res; } // --- Key Generation & Operations --- netplus::rsa::bigInt netplus::rsa::modInverse(bigInt e, bigInt phi) { bigInt m0 = phi; bigInt t, q; // Greatest Common Divisor rsa::bigInt rsa::gcd(bigInt a, bigInt b) { bigInt temp_a = a; bigInt temp_b = b; 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); } 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 = e, b = phi; bool x0_pos = true, x1_pos = true; // EEA Loop while (!b.isZero()) { bigInt q(a.capacity), r(a.capacity); divide(a, b, q, r); // Update a and b a = b; b = r; x0.fromString("0"); x1.fromString("1"); // next_x = x0 - q * x1 bigInt qx1(q.capacity + x1.capacity); multiply(q, x1, qx1); if (compare(phi, x1) == 0) { bigInt zero(1); zero.fromString("0"); return zero; bigInt next_x(phi.capacity + 2); bool next_x_pos; if (x0_pos == x1_pos) { if (compare(x0, qx1) >= 0) { subtract(x0, qx1, next_x); next_x_pos = x0_pos; } else { subtract(qx1, x0, next_x); next_x_pos = !x0_pos; } } else { add(x0, qx1, next_x); next_x_pos = x0_pos; } while (compare(e, x1) > 0) { // q = e / phi bigInt quotient(e.capacity), remainder(e.capacity); divide(e, phi, quotient, remainder); q = quotient; // Shift coefficients x0 = x1; x0_pos = x1_pos; x1 = next_x; x1_pos = next_x_pos; } // t = phi, phi = e % phi, e = t t = phi; phi = remainder; e = t; // 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. // t = x0 t = x0; if (!x0_pos && !x0.isZero()) { bigInt res(phi.capacity); subtract(phi, x0, res); return res; } return x0; } // x0 = x1 - q * x0 bigInt qx0(q.capacity + x0.capacity); multiply(q, x0, qx0); void rsa::generateSecureRandom(bigInt& n, size_t requested_digits) { if (requested_digits > n.capacity) requested_digits = n.capacity; 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; #ifdef _WIN32 // Windows implementation using BCrypt if (!BCRYPT_SUCCESS(BCryptGenRandom(NULL, reinterpret_cast<PUCHAR>(n.digits.get()), requested_digits * sizeof(int), BCRYPT_USE_SYSTEM_PREFERRED_RNG))) { throw std::runtime_error("BCryptGenRandom failed"); } x1 = t; // Since BCrypt fills the buffer with raw bytes, we must map them to 0-9 for (size_t i = 0; i < requested_digits; ++i) { n.digits[i] = static_cast<unsigned int>(n.digits[i]) % 10; } #else // Linux/Unix implementation std::ifstream urandom("/dev/urandom", std::ios::in | std::ios::binary); if (!urandom) throw std::runtime_error("Could not open /dev/urandom"); for (size_t i = 0; i < requested_digits; ++i) { unsigned char byte; urandom.read(reinterpret_cast<char*>(&byte), 1); n.digits[i] = byte % 10; } #endif n.size = requested_digits; return x1; // Standard RSA adjustments (No leading zeros, force odd) while (n.size > 1 && n.digits[n.size - 1] == 0) n.size--; if (n.size > 0 && n.digits[0] % 2 == 0) { n.digits[0] = (n.digits[0] + 1) % 10; } } 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 void netplus::rsa::generateKeys(bigInt& p, bigInt& q) { // 1. n = p * q multiply(p, q, n); // 2. Write n-1 as 2^s * d bigInt two(n.capacity); two.fromString("2"); bigInt nm1(n.capacity); subtract(n, one, nm1); 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); 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 x = modPow(a, d, n); // If x == 1 or x == n-1 if (x.toString() == "1" || x.toString() == nm1.toString()) 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()) { 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); add(p, two, next_p); p = std::move(next_p); } } 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 // 2. phi = (p-1)*(q-1) bigInt one(1); one.fromString("1"); bigInt pm1(p.capacity), qm1(q.capacity), phi(n.capacity); bigInt two(1); two.fromString("2"); 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"); e.fromString("17"); // Default candidate // Increment e until it is coprime with phi while (gcd(e, phi).toString() != "1") { bigInt next_e(e.capacity); add(e, two, next_e); e = std::move(next_e); } // 4. d = e^-1 mod phi d = modInverse(e, phi); std::cerr << "d: " << d.toString() << "e: " << e.toString() << "phi: " << phi.toString() << std::endl; } 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 +5 −1 Changes for src/crypto/rsa.h: 5 added lines, 1 removed line. Original line number Diff line number Diff line Loading @@ -57,7 +57,7 @@ namespace netplus { rsa(); // RSA Core Methods void generateKeys(bigInt& p, bigInt& q); void generateKeys(size_t digit_count); bigInt encrypt(const bigInt& message); bigInt decrypt(const bigInt& cipher); Loading @@ -70,7 +70,11 @@ namespace netplus { private: bigInt n, e, d; bool isProbablyPrime(const bigInt& n, int k); void findPrime(bigInt& p, size_t digits); void generateSecureRandom(bigInt& n, size_t requested_digits); static bigInt modPow(bigInt base, bigInt exp, const bigInt& mod); static bigInt modInverse(bigInt e, bigInt phi); static bigInt gcd(bigInt a, bigInt b); }; }; test/rsa.cpp +4 −4 Changes for test/rsa.cpp: 4 added lines, 4 removed lines. Original line number Diff line number Diff line Loading @@ -24,18 +24,18 @@ void test_bigint_multiplication() { void test_rsa_lifecycle() { rsa crypto; rsa::bigInt p(10), q(10), msg(20); rsa::bigInt msg(20); // Use small primes for quick test validation p.fromString("61"); q.fromString("53"); msg.fromString("42"); crypto.generateKeys(p, q); crypto.generateKeys(10); rsa::bigInt encrypted = crypto.encrypt(msg); rsa::bigInt decrypted = crypto.decrypt(encrypted); std::cout << "DEBUG: Cipher=" << encrypted.toString() << std::endl; assert(decrypted.toString() == "42"); std::cout << "[PASS] RSA Lifecycle (Encrypt/Decrypt)\n"; } Loading Loading
src/crypto/rsa.cpp +354 −92 Changes for src/crypto/rsa.cpp: 354 added lines, 92 removed lines. Original line number Diff line number Diff line Loading @@ -23,8 +23,17 @@ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ #include <stdexcept> #include <iostream> #include <algorithm> #include <stdexcept> #ifdef _WIN32 #include <windows.h> #include <bcrypt.h> #pragma comment(lib, "bcrypt.lib") #else #include <fstream> #endif #include "rsa.h" Loading @@ -50,22 +59,33 @@ namespace netplus { rsa::bigInt& rsa::bigInt::operator=(const bigInt& other) { if (this != &other) { if (capacity < other.size) { // Only reallocate if we absolutely must 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; } size = other.size; for (size_t i = 0; i < capacity; ++i) this->size = other.size; // Reset the entire buffer to 0 first to prevent garbage data 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 { netplus::rsa::bigInt& netplus::rsa::bigInt::operator=(bigInt&& other) noexcept { if (this != &other) { // This transfers the pointer ownership and automatically // cleans up the old 'this->digits' memory. digits = std::move(other.digits); size = other.size; capacity = other.capacity; // Ensure 'other' is left in a safe, empty state other.size = 0; other.capacity = 0; } Loading @@ -74,14 +94,13 @@ namespace netplus { void rsa::bigInt::fromString(const std::string& s) { size = s.length(); if (size > capacity) { digits = std::make_unique<int[]>(size); capacity = size; } // ... allocation logic ... for (size_t i = 0; i < size; ++i) { digits[i] = s[size - 1 - i] - '0'; } // 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 @@ -91,7 +110,12 @@ namespace netplus { return s; } bool rsa::bigInt::isZero() const { return size == 0; } bool rsa::bigInt::isZero() const { if (size == 0) return true; if (size == 1 && digits[0] == 0) return true; return false; } bool rsa::bigInt::isEven() const { return size == 0 || digits[0] % 2 == 0; } // --- RSA Math Engine --- Loading @@ -99,9 +123,12 @@ namespace netplus { 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; 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; if (a.digits[i] != b.digits[i]) return (a.digits[i] < b.digits[i]) ? -1 : 1; } return 0; } Loading @@ -118,151 +145,386 @@ 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; } 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; 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--; // 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; } // Shrink size int newSize = (int)a.size; while (newSize > 0 && res.digits[newSize - 1] == 0) { newSize--; } 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; } // 2. Clear the buffer for (size_t k = 0; k < res.capacity; ++k) res.digits[k] = 0; // 3. Multiplication logic... for (size_t i = 0; i < a.size; ++i) { int 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; res.digits[i + j] = cur % 10; res.digits[i + j] = (int)(cur % 10); carry = (int)(cur / 10); } } // ... update size and strip zeros 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; // 1. Reset Quotient for (size_t k = 0; k < quotient.capacity; ++k) quotient.digits[k] = 0; quotient.size = 0; // 2. Reset Remainder for (size_t k = 0; k < remainder.capacity; ++k) remainder.digits[k] = 0; remainder.size = 0; // Long division algorithm 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]; // SHIFT: remainder = remainder * 10 if (remainder.size > 0 || dividend.digits[i] > 0) { // Ensure room for shift + new digit 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 { 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]; if (remainder.digits[remainder.size] > 0 || remainder.size == 0) remainder.size++; remainder.size++; while (remainder.size > 0 && remainder.digits[remainder.size - 1] == 0) remainder.size--; } int q = 0; // SUBTRACT LOOP: Find how many times divisor fits in remainder 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 = temp; q++; remainder = std::move(temp); 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; } quotient.digits[i] = q; } size_t qs = dividend.size; while (qs > 0 && quotient.digits[qs - 1] == 0) qs--; quotient.size = qs; // Final trim of leading zeros for quotient while (quotient.size > 0 && quotient.digits[quotient.size - 1] == 0) quotient.size--; } 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; // Result starts at 1 bigInt res(mod.capacity); 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 two(1); two.fromString("2"); // 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; } // current_base = (current_base * current_base) % mod bigInt tempSquare(workCap); multiply(current_base, current_base, tempSquare); bigInt q_sq(tempSquare.capacity), r_sq(mod.capacity); divide(tempSquare, mod, q_sq, r_sq); current_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; } return res; } // --- Key Generation & Operations --- netplus::rsa::bigInt netplus::rsa::modInverse(bigInt e, bigInt phi) { bigInt m0 = phi; bigInt t, q; // Greatest Common Divisor rsa::bigInt rsa::gcd(bigInt a, bigInt b) { bigInt temp_a = a; bigInt temp_b = b; 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); } 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 = e, b = phi; bool x0_pos = true, x1_pos = true; // EEA Loop while (!b.isZero()) { bigInt q(a.capacity), r(a.capacity); divide(a, b, q, r); // Update a and b a = b; b = r; x0.fromString("0"); x1.fromString("1"); // next_x = x0 - q * x1 bigInt qx1(q.capacity + x1.capacity); multiply(q, x1, qx1); if (compare(phi, x1) == 0) { bigInt zero(1); zero.fromString("0"); return zero; bigInt next_x(phi.capacity + 2); bool next_x_pos; if (x0_pos == x1_pos) { if (compare(x0, qx1) >= 0) { subtract(x0, qx1, next_x); next_x_pos = x0_pos; } else { subtract(qx1, x0, next_x); next_x_pos = !x0_pos; } } else { add(x0, qx1, next_x); next_x_pos = x0_pos; } while (compare(e, x1) > 0) { // q = e / phi bigInt quotient(e.capacity), remainder(e.capacity); divide(e, phi, quotient, remainder); q = quotient; // Shift coefficients x0 = x1; x0_pos = x1_pos; x1 = next_x; x1_pos = next_x_pos; } // t = phi, phi = e % phi, e = t t = phi; phi = remainder; e = t; // 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. // t = x0 t = x0; if (!x0_pos && !x0.isZero()) { bigInt res(phi.capacity); subtract(phi, x0, res); return res; } return x0; } // x0 = x1 - q * x0 bigInt qx0(q.capacity + x0.capacity); multiply(q, x0, qx0); void rsa::generateSecureRandom(bigInt& n, size_t requested_digits) { if (requested_digits > n.capacity) requested_digits = n.capacity; 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; #ifdef _WIN32 // Windows implementation using BCrypt if (!BCRYPT_SUCCESS(BCryptGenRandom(NULL, reinterpret_cast<PUCHAR>(n.digits.get()), requested_digits * sizeof(int), BCRYPT_USE_SYSTEM_PREFERRED_RNG))) { throw std::runtime_error("BCryptGenRandom failed"); } x1 = t; // Since BCrypt fills the buffer with raw bytes, we must map them to 0-9 for (size_t i = 0; i < requested_digits; ++i) { n.digits[i] = static_cast<unsigned int>(n.digits[i]) % 10; } #else // Linux/Unix implementation std::ifstream urandom("/dev/urandom", std::ios::in | std::ios::binary); if (!urandom) throw std::runtime_error("Could not open /dev/urandom"); for (size_t i = 0; i < requested_digits; ++i) { unsigned char byte; urandom.read(reinterpret_cast<char*>(&byte), 1); n.digits[i] = byte % 10; } #endif n.size = requested_digits; return x1; // Standard RSA adjustments (No leading zeros, force odd) while (n.size > 1 && n.digits[n.size - 1] == 0) n.size--; if (n.size > 0 && n.digits[0] % 2 == 0) { n.digits[0] = (n.digits[0] + 1) % 10; } } 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 void netplus::rsa::generateKeys(bigInt& p, bigInt& q) { // 1. n = p * q multiply(p, q, n); // 2. Write n-1 as 2^s * d bigInt two(n.capacity); two.fromString("2"); bigInt nm1(n.capacity); subtract(n, one, nm1); 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); 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 x = modPow(a, d, n); // If x == 1 or x == n-1 if (x.toString() == "1" || x.toString() == nm1.toString()) 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()) { 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); add(p, two, next_p); p = std::move(next_p); } } 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 // 2. phi = (p-1)*(q-1) bigInt one(1); one.fromString("1"); bigInt pm1(p.capacity), qm1(q.capacity), phi(n.capacity); bigInt two(1); two.fromString("2"); 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"); e.fromString("17"); // Default candidate // Increment e until it is coprime with phi while (gcd(e, phi).toString() != "1") { bigInt next_e(e.capacity); add(e, two, next_e); e = std::move(next_e); } // 4. d = e^-1 mod phi d = modInverse(e, phi); std::cerr << "d: " << d.toString() << "e: " << e.toString() << "phi: " << phi.toString() << std::endl; } 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 +5 −1 Changes for src/crypto/rsa.h: 5 added lines, 1 removed line. Original line number Diff line number Diff line Loading @@ -57,7 +57,7 @@ namespace netplus { rsa(); // RSA Core Methods void generateKeys(bigInt& p, bigInt& q); void generateKeys(size_t digit_count); bigInt encrypt(const bigInt& message); bigInt decrypt(const bigInt& cipher); Loading @@ -70,7 +70,11 @@ namespace netplus { private: bigInt n, e, d; bool isProbablyPrime(const bigInt& n, int k); void findPrime(bigInt& p, size_t digits); void generateSecureRandom(bigInt& n, size_t requested_digits); static bigInt modPow(bigInt base, bigInt exp, const bigInt& mod); static bigInt modInverse(bigInt e, bigInt phi); static bigInt gcd(bigInt a, bigInt b); }; };
test/rsa.cpp +4 −4 Changes for test/rsa.cpp: 4 added lines, 4 removed lines. Original line number Diff line number Diff line Loading @@ -24,18 +24,18 @@ void test_bigint_multiplication() { void test_rsa_lifecycle() { rsa crypto; rsa::bigInt p(10), q(10), msg(20); rsa::bigInt msg(20); // Use small primes for quick test validation p.fromString("61"); q.fromString("53"); msg.fromString("42"); crypto.generateKeys(p, q); crypto.generateKeys(10); rsa::bigInt encrypted = crypto.encrypt(msg); rsa::bigInt decrypted = crypto.decrypt(encrypted); std::cout << "DEBUG: Cipher=" << encrypted.toString() << std::endl; assert(decrypted.toString() == "42"); std::cout << "[PASS] RSA Lifecycle (Encrypt/Decrypt)\n"; } Loading