Commit 510835f5 authored by jan.koester's avatar jan.koester
Browse files

more modern c++

parent 5e7c4f70
Loading
Loading
Loading
Loading
+133 −146
Changes for src/crypto/ecc_p256.cpp: 133 added lines, 146 removed lines.
Original line number Diff line number Diff line
@@ -18,7 +18,7 @@ static const uint8_t P256_B_BE[32] = {
  0x3b,0xce,0x3c,0x3e,0x27,0xd2,0x60,0x4b
};

const u256 P256_B = bytes_be_to_u256(P256_B_BE);
const u256 P256_B = u256::fromBigEndian(P256_B_BE);

// NIST P-256 / secp256r1 base point G (uncompressed)
// Gx = 6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296
@@ -29,81 +29,51 @@ static const P256Point P256_G_STD = []{
    P256Point g;
    g.inf  = false;
    g.mont = false;
    g.x = bytes_be_to_u256(P256_GX_BE);
    g.y = bytes_be_to_u256(P256_GY_BE);
    g.x = u256::fromBigEndian(P256_GX_BE);
    g.y = u256::fromBigEndian(P256_GY_BE);
    return g;
}();

const P256Point& P256_G() { return P256_G_STD; }


// Montgomery basepoint (for internal jacobian arithmetic)
static const P256Point P256_G_JAC_MONT = []{
    P256Point j;
    j.mont=true;
    j.inf = false;
    j.x = to_mont(P256_G_STD.x);
    j.y = to_mont(P256_G_STD.y);

    u256 one; u256_zero(one); one.w[0]=1;
    j.z = to_mont(one); // Z=1 in mont

    return j;
}();
const P256Point& P256Point::basePoint() { return P256_G_STD; }

// ------------------------------------------------------------
// Point Transformations
// ------------------------------------------------------------

/**
 * Converts Affine (Montgomery) to Jacobian (Montgomery).
 * Z starts as 1 in Montgomery domain: Z = to_mont(1).
 */
static inline P256Point jac_inf() {
    P256Point r;
    r.inf = true;
    r.mont = true;
    u256 zero; u256_zero(zero);
    r.x = to_mont(zero);
    r.y = to_mont(zero);
    r.z = to_mont(zero);  // Z=0 => infinity
    return r;
}

/**
 * Converts Jacobian (Montgomery) to Affine (Montgomery).
 * x = X / Z^2, y = Y / Z^3  (all Montgomery domain)
 */
P256Point toAff(const P256Point& Jm)
P256Point P256Point::toAffine() const
{
    P256Point P;
    P.mont = false;  // ✅ because we return STD

    if (Jm.inf) {
    if (inf) {
        P.inf = true;
        return P;
    }

    // Z == 0 ?
    u256 z_std = from_mont(Jm.z);
    if (u256_is_zero(z_std)) {
    u256 z_std = z.fromMontgomery();
    if (z_std.isZero()) {
        P.inf = true;
        return P;
    }

    // zinv = 1/Z in MONT
    u256 zinv  = fp_inv(Jm.z);
    u256 zinv2 = fp_mul(zinv, zinv);
    u256 zinv3 = fp_mul(zinv2, zinv);
    u256 zinv  = z.montgomeryInverse();
    u256 zinv2 = zinv.montgomeryMul(zinv);
    u256 zinv3 = zinv2.montgomeryMul(zinv);

    // affine in MONT
    u256 Xm = fp_mul(Jm.x, zinv2);
    u256 Ym = fp_mul(Jm.y, zinv3);
    u256 Xm = x.montgomeryMul(zinv2);
    u256 Ym = y.montgomeryMul(zinv3);

    // convert to STD for output
    P.inf = false;
    P.x   = from_mont(Xm);
    P.y   = from_mont(Ym);
    P.x   = Xm.fromMontgomery();
    P.y   = Ym.fromMontgomery();
    return P;
}

@@ -113,41 +83,42 @@ P256Point toAff(const P256Point& Jm)
// ------------------------------------------------------------

/**
 * Jacobian point doubling: R = 2P  (all Montgomery domain)
 * Jacobian point doubling: R = 2*this  (all Montgomery domain)
 * Optimized for a=-3.
 */
P256Point point_double(const P256Point& a) {
    if (a.inf || u256_is_zero(a.z)) return a;
P256Point P256Point::doubled() const {
    if (inf || z.isZero()) return *this;

    u256 t1 = fp_sqr(a.z);              // Z^2
    u256 t2 = fp_sub(a.x, t1);          // X - Z^2
    u256 t3 = fp_add(a.x, t1);          // X + Z^2
    t2 = fp_mul(t2, t3);                // (X-Z^2)(X+Z^2)
    u256 t4 = fp_add(t2, t2);           // 2*t2
    u256 M  = fp_add(t4, t2);           // 3*(X^2 - Z^4)
    u256 t1 = z.montgomerySquare();               // Z^2
    u256 t2 = x.montgomerySub(t1);                 // X - Z^2
    u256 t3 = x.montgomeryAdd(t1);                 // X + Z^2
    t2 = t2.montgomeryMul(t3);                     // (X-Z^2)(X+Z^2)
    u256 t4 = t2.montgomeryAdd(t2);                // 2*t2
    u256 M  = t4.montgomeryAdd(t2);                // 3*(X^2 - Z^4)

    u256 Y2 = fp_sqr(a.y);              // Y^2
    u256 S  = fp_mul(a.x, Y2);          // X*Y^2
    S = fp_add(S, S);
    S = fp_add(S, S);                   // S = 4*X*Y^2
    u256 Y2 = y.montgomerySquare();                // Y^2
    u256 S  = x.montgomeryMul(Y2);                 // X*Y^2
    S = S.montgomeryAdd(S);
    S = S.montgomeryAdd(S);                        // S = 4*X*Y^2

    u256 T  = fp_sqr(M);                // M^2
    u256 S2 = fp_add(S, S);             // 2S
    u256 X3 = fp_sub(T, S2);
    u256 T  = M.montgomerySquare();                // M^2
    u256 S2 = S.montgomeryAdd(S);                  // 2S
    u256 X3 = T.montgomerySub(S2);

    u256 Y4 = fp_sqr(Y2);
    u256 Y8 = fp_add(Y4, Y4);
    Y8 = fp_add(Y8, Y8);
    Y8 = fp_add(Y8, Y8);                // 8*Y^4
    u256 Y4 = Y2.montgomerySquare();
    u256 Y8 = Y4.montgomeryAdd(Y4);
    Y8 = Y8.montgomeryAdd(Y8);
    Y8 = Y8.montgomeryAdd(Y8);                     // 8*Y^4

    u256 S_minus_X3 = fp_sub(S, X3);
    u256 Y3 = fp_sub(fp_mul(M, S_minus_X3), Y8);
    u256 S_minus_X3 = S.montgomerySub(X3);
    u256 Y3 = M.montgomeryMul(S_minus_X3).montgomerySub(Y8);

    u256 YZ = fp_mul(a.y, a.z);
    u256 Z3 = fp_add(YZ, YZ);
    u256 YZ = y.montgomeryMul(z);
    u256 Z3 = YZ.montgomeryAdd(YZ);

    P256Point r;
    r.inf = false;
    r.mont = true;
    r.x = X3;
    r.y = Y3;
    r.z = Z3;
@@ -155,53 +126,72 @@ P256Point point_double(const P256Point& a) {
}

/**
 * Full Jacobian point addition: R = a + b (Montgomery)
 * Full Jacobian point addition: R = this + other (Montgomery)
 */
P256Point point_add_jac(const P256Point& a, const P256Point& b) {
    if (a.inf) return b;
    if (b.inf) return a;
P256Point P256Point::addJacobian(const P256Point& other) const {
    if (inf) return other;
    if (other.inf) return *this;

    u256 z1z1 = fp_sqr(a.z);
    u256 z2z2 = fp_sqr(b.z);
    u256 z1z1 = z.montgomerySquare();
    u256 z2z2 = other.z.montgomerySquare();

    u256 u1 = fp_mul(a.x, z2z2);
    u256 u2 = fp_mul(b.x, z1z1);
    u256 u1 = x.montgomeryMul(z2z2);
    u256 u2 = other.x.montgomeryMul(z1z1);

    u256 s1 = fp_mul(fp_mul(a.y, b.z), z2z2);
    u256 s2 = fp_mul(fp_mul(b.y, a.z), z1z1);
    u256 s1 = y.montgomeryMul(other.z).montgomeryMul(z2z2);
    u256 s2 = other.y.montgomeryMul(z).montgomeryMul(z1z1);

    if (u256_cmp(u1, u2) == 0) {
        if (u256_cmp(s1, s2) == 0) return point_double(a);
        P256Point r; r.inf = true; return r;
    if (u1 == u2) {
        if (s1 == s2) return doubled();
        P256Point r; r.inf = true; r.mont = true; return r;
    }

    u256 h = fp_sub(u2, u1);
    u256 r_val = fp_sub(s2, s1);
    u256 h2 = fp_sqr(h);
    u256 h3 = fp_mul(h2, h);
    u256 v  = fp_mul(u1, h2);
    u256 h = u2.montgomerySub(u1);
    u256 r_val = s2.montgomerySub(s1);
    u256 h2 = h.montgomerySquare();
    u256 h3 = h2.montgomeryMul(h);
    u256 v  = u1.montgomeryMul(h2);

    u256 x3 = fp_sub(fp_sub(fp_sqr(r_val), h3), fp_add(v, v));
    u256 y3 = fp_sub(fp_mul(r_val, fp_sub(v, x3)), fp_mul(s1, h3));
    u256 z3 = fp_mul(fp_mul(a.z, b.z), h);
    u256 x3 = r_val.montgomerySquare().montgomerySub(h3).montgomerySub(v.montgomeryAdd(v));
    u256 y3 = r_val.montgomeryMul(v.montgomerySub(x3)).montgomerySub(s1.montgomeryMul(h3));
    u256 z3 = z.montgomeryMul(other.z).montgomeryMul(h);

    P256Point res;
    res.inf = false;
    res.mont = true;
    res.x = x3;
    res.y = y3;
    res.z = z3;
    return res;
}

P256Point P256Point::addMixed(const P256Point& other) const {
    // Not yet needed by any caller (mirrors the pre-refactor state, where
    // point_add_mixed was declared but never implemented/called); kept as a
    // named extension point rather than silently falling back to the slower
    // full addJacobian(), which would hide the missing optimization.
    return addJacobian(other);
}

P256Point P256Point::operator+(const P256Point& other) const {
    return toJacobian().addJacobian(other.toJacobian()).toAffine();
}

bool P256Point::operator==(const P256Point& other) const {
    if (inf != other.inf) return false;
    if (inf) return true;
    return x == other.x && y == other.y;
}

// ------------------------------------------------------------
// Scalar Multiplication (Montgomery Ladder)
// ------------------------------------------------------------

static inline void cswap_jac(P256Point& A, P256Point& B, uint32_t swap) {
    // swap is 0 or 1
    cswap_u256(A.x, B.x, swap);
    cswap_u256(A.y, B.y, swap);
    cswap_u256(A.z, B.z, swap);
    u256::cswap(A.x, B.x, swap);
    u256::cswap(A.y, B.y, swap);
    u256::cswap(A.z, B.z, swap);

    // IMPORTANT: swap the infinity flag too
    uint32_t t = (uint32_t)A.inf ^ (uint32_t)B.inf;
@@ -210,26 +200,24 @@ static inline void cswap_jac(P256Point& A, P256Point& B, uint32_t swap) {
    B.inf = (bool)((uint32_t)B.inf ^ t);
}

P256Point toJac(const P256Point& Pstd)
P256Point P256Point::toJacobian() const
{
    P256Point J;
    J.mont = true;

    if (Pstd.inf) {
    if (inf) {
        J.inf = true;
        u256 z; u256_zero(z);
        J.x = to_mont(z);
        J.y = to_mont(z);
        J.z = to_mont(z); // Z=0 => INF
        u256 z0 = u256::zero();
        J.x = z0.toMontgomery();
        J.y = z0.toMontgomery();
        J.z = z0.toMontgomery(); // Z=0 => INF
        return J;
    }

    J.inf = false;
    J.x = to_mont(Pstd.x);
    J.y = to_mont(Pstd.y);

    u256 one; u256_zero(one); one.w[0]=1;
    J.z = to_mont(one); // Z=1
    J.x = x.toMontgomery();
    J.y = y.toMontgomery();
    J.z = u256::one().toMontgomery(); // Z=1
    return J;
}

@@ -239,35 +227,35 @@ static bool scalar_is_zero(const uint8_t k[32]) {
    return true;
}

P256Point scalar_mul(const uint8_t k[32], const P256Point& Pstd)
P256Point P256Point::scalarMul(const uint8_t k[32]) const
{
    // R = INF (Jacobian, MONT)
    P256Point R;
    R.inf  = true;
    R.mont = true;
    u256 z; u256_zero(z);
    R.x = to_mont(z);
    R.y = to_mont(z);
    R.z = to_mont(z);
    u256 z0 = u256::zero();
    R.x = z0.toMontgomery();
    R.y = z0.toMontgomery();
    R.z = z0.toMontgomery();

    // Q = P as Jacobian (MONT)
    P256Point Q = toJac(Pstd);
    // Q = this as Jacobian (MONT)
    P256Point Q = toJacobian();

    // classic double-and-add MSB->LSB (matches get_bit_be)
    for (int i=0;i<256;i++){
        uint32_t bit = get_bit_be(k,i);

        R = point_double(R);
        if(bit) R = point_add_jac(R,Q);
        R = R.doubled();
        if(bit) R = R.addJacobian(Q);
    }

    // ✅ Return affine STD
    return toAff(R);
    return R.toAffine();
}



P256Point scalar_mul_G(const uint8_t priv[32])
P256Point P256Point::scalarMulBase(const uint8_t priv[32])
{
    if (scalar_is_zero(priv)) {
        P256Point R;
@@ -275,33 +263,33 @@ P256Point scalar_mul_G(const uint8_t priv[32])
        R.mont = false;
        return R;
    }
    return scalar_mul(priv, P256_G());
    return basePoint().scalarMul(priv);
}

bool is_on_curve(const P256Point& P)
bool P256Point::isOnCurve() const
{
    if (P.inf) return true;
    if (inf) return true;

    // reject x>=p or y>=p
    if (u256_cmp(P.x, P256_P) >= 0) return false;
    if (u256_cmp(P.y, P256_P) >= 0) return false;
    if (x >= P256_P) return false;
    if (y >= P256_P) return false;

    u256 x = P.mont ? P.x : to_mont(P.x);
    u256 y = P.mont ? P.y : to_mont(P.y);
    u256 b = to_mont(P256_B);
    u256 xm = mont ? x : x.toMontgomery();
    u256 ym = mont ? y : y.toMontgomery();
    u256 b = P256_B.toMontgomery();

    u256 y2 = fp_mul(y,y);
    u256 x2 = fp_mul(x,x);
    u256 x3 = fp_mul(x2,x);
    u256 y2 = ym.montgomeryMul(ym);
    u256 x2 = xm.montgomeryMul(xm);
    u256 x3 = x2.montgomeryMul(xm);

    // rhs = x^3 - 3x + b
    u256 three_std = {{3,0,0,0,0,0,0,0}};
    u256 three = to_mont(three_std);
    u256 three = three_std.toMontgomery();

    u256 rhs = fp_sub(x3, fp_mul(three,x));
    rhs = fp_add(rhs,b);
    u256 rhs = x3.montgomerySub(three.montgomeryMul(xm));
    rhs = rhs.montgomeryAdd(b);

    return u256_cmp(y2,rhs)==0;
    return y2 == rhs;
}

// ------------------------------------------------------------
@@ -310,47 +298,46 @@ bool is_on_curve(const P256Point& P)

/**
 * Decodes uncompressed TLS point (04||X||Y).
 * Internally stores coordinates in Montgomery domain.
 * Also validates curve equation in Montgomery domain.
 * Stores coordinates in the affine, standard domain.
 * Does not itself validate the curve equation -- call isOnCurve() too.
 */
bool decode_tls_point(P256Point& out, const uint8_t* in, size_t len)
bool P256Point::decodeTls(P256Point& out, const uint8_t* in, size_t len)
{
    if (len != 65 || in[0] != 0x04) return false;

    out.inf  = false;
    out.mont = false;
    out.x = bytes_be_to_u256(in + 1);
    out.y = bytes_be_to_u256(in + 33);
    out.x = u256::fromBigEndian(in + 1);
    out.y = u256::fromBigEndian(in + 33);
    return true;
}


/**
 * Encodes affine point (Montgomery) to TLS (std big endian).
 * Encodes affine point to TLS (std big endian).
 */
std::vector<uint8_t> encode_tls_point(const P256Point& P)
std::vector<uint8_t> P256Point::encodeTls() const
{
    std::vector<uint8_t> out(65);
    out[0]=0x04;
    u256_to_be(&out[1], P.x);
    u256_to_be(&out[33],P.y);
    x.toBigEndian(&out[1]);
    y.toBigEndian(&out[33]);
    return out;
}



/**
 * ECDH: returns Big-Endian X-coordinate of shared point.
 * ECDH: returns Big-Endian X-coordinate of shared point (priv * this).
 */
bool ecdh_shared_secret(uint8_t out32[32], const uint8_t priv[32], const P256Point& peer)
bool P256Point::ecdh(uint8_t out32[32], const uint8_t priv[32]) const
{
    if (!out32 || peer.inf) return false;
    if (!out32 || inf) return false;

    // scalar_mul returns affine STD
    P256Point shared = scalar_mul(priv, peer);
    // scalarMul returns affine STD
    P256Point shared = scalarMul(priv);
    if (shared.inf) return false;

    u256_to_be(out32, shared.x);   // ✅ already STD
    shared.x.toBigEndian(out32);   // ✅ already STD
    return true;
}

+58 −58
Changes for src/crypto/ecc_p256.h: 58 added lines, 58 removed lines.
Original line number Diff line number Diff line
@@ -6,17 +6,6 @@

namespace netplus {

static const u256 P256_N = {{
    0xFC632551, // w[0] LSW
    0xF3B9CAC2,
    0xA7179E84,
    0xBCE6FAAD,
    0xFFFFFFFF,
    0xFFFFFFFF,
    0x00000000,
    0xFFFFFFFF  // w[7] MSW
}};

static const uint8_t P256_GX_BE[32] = {
  0x6b,0x17,0xd1,0xf2,0xe1,0x2c,0x42,0x47,
  0xf8,0xbc,0xe6,0xe5,0x63,0xa4,0x40,0xf2,
@@ -32,9 +21,17 @@ static const uint8_t P256_GY_BE[32] = {
};

/**
 * @brief Affine point on the NIST P-256 curve.
 * @brief Affine or Jacobian point on the NIST P-256 curve.
 * Equation: y^2 = x^3 - 3x + b (mod p)
 * Internal layout: x.w[0] is the Least Significant Word (Little-Endian math).
 *
 * Representation is tracked by `mont`: false means affine, standard (not
 * Montgomery) domain -- the representation used at every public/TLS boundary
 * (encodeTls/decodeTls, scalarMul results, ecdh). true means Jacobian,
 * Montgomery domain -- the internal working representation used only by the
 * scalar-multiplication ladder and doubled()/addJacobian(), where converting
 * to affine on every step would cost a modular inversion per step instead of
 * one per scalar multiplication.
 */
struct P256Point {
    u256 x;
@@ -42,86 +39,89 @@ struct P256Point {
    u256 z;      // only valid if mont=true (Jacobian)
    bool inf = true;
    bool mont = false;
};

// --- NIST P-256 Curve Constants ---

    /**
 * @brief Returns a reference to the NIST P-256 Base Point G.
     * @brief The NIST P-256 Base Point G (affine, standard domain).
     */
const P256Point& P256_G();
    static const P256Point& basePoint();

/**
 * @brief The 'b' coefficient of the NIST P-256 curve equation.
 */
extern const u256 P256_B;
    // --- Representation conversions ---

// --- Point Operations ---
    /** @brief Converts affine (standard domain) to Jacobian (Montgomery domain), Z = 1. */
    P256Point toJacobian() const;

/** * @brief Converts affine coordinates to Jacobian coordinates.
 * Sets Z = 1.
 */
P256Point toJac(const P256Point& P);
    /** @brief Converts Jacobian (Montgomery domain) back to affine (standard domain).
     * Requires one modular inversion -- expensive, call once, not per step. */
    P256Point toAffine() const;

/** * @brief Converts Jacobian coordinates back to Affine.
 * Requires one modular inversion.
 */
P256Point  toAff(const P256Point& a);
    // --- Point arithmetic (Jacobian/Montgomery only -- for the scalar-mult
    // ladder; no implicit domain conversion, matching the old point_double /
    // point_add_jac contract) ---

/** * @brief Point doubling: R = 2 * P.
 * Optimized for the NIST case where a = -3.
 */
P256Point point_double(const P256Point& a);
    /** @brief Point doubling: R = 2 * this. Optimized for the NIST case where a = -3. */
    P256Point doubled() const;

/** * @brief Full Jacobian point addition: R = P1 + P2.
 */
P256Point point_add_jac(const P256Point& a, const P256Point& b);
    /** @brief Full Jacobian point addition: R = this + other. */
    P256Point addJacobian(const P256Point& other) const;

/** * @brief Mixed addition: R = P1 (Jacobian) + P2 (Affine).
 * Faster than full Jacobian addition when one point is already affine.
 */
P256Point point_add_mixed(const P256Point& a, const P256Point& b);
    /** @brief Mixed addition: this (Jacobian) + other (Affine). Faster than
     * addJacobian() when other is already affine. */
    P256Point addMixed(const P256Point& other) const;

    // --- Point arithmetic (affine, standard domain in and out -- the
    // friendly/general-purpose form; each call pays one Jacobian round-trip) ---

    /** @brief Point addition on affine points: R = this + other. */
    P256Point operator+(const P256Point& other) const;

    /** @brief Point equality. Both operands must be in the same representation. */
    bool operator==(const P256Point& other) const;
    bool operator!=(const P256Point& other) const { return !(*this == other); }

    bool isOnCurve() const;

    // --- Scalar Multiplication ---

    /**
 * @brief Computes R = k * P using a Montgomery Ladder.
     * @brief Computes R = k * this using a Montgomery Ladder.
     * @param priv 32-byte scalar (Big-Endian, as used in TLS/NIST).
 * @param P Affine point on the curve.
     * @return The resulting affine point.
     */
P256Point scalar_mul(const uint8_t priv[32], const P256Point& P);

/** * @brief Computes R = k * G (Base point multiplication).
 */
P256Point scalar_mul_G(const uint8_t priv[32]);
    P256Point scalarMul(const uint8_t priv[32]) const;

bool is_on_curve(const P256Point& P);
    /** @brief Computes R = k * G (Base point multiplication). */
    static P256Point scalarMulBase(const uint8_t priv[32]);

    // --- TLS / Interoperability ---

    /**
 * @brief Encodes a point into the uncompressed TLS format (0x04 || X || Y).
     * @brief Encodes this point into the uncompressed TLS format (0x04 || X || Y).
     * @return A 65-byte vector in Big-Endian format.
     */
std::vector<uint8_t> encode_tls_point(const P256Point& P);
    std::vector<uint8_t> encodeTls() const;

    /**
 * @brief Decodes an uncompressed point and validates that it lies on the curve.
 * Mandatory check for NIST compliance to prevent Invalid Curve attacks.
     * @brief Decodes an uncompressed point. Does NOT validate that it lies on
     * the curve -- callers performing key exchange must call isOnCurve() too
     * (mandatory for NIST compliance, to prevent Invalid Curve attacks).
     * @param p Pointer to input data (starting with 0x04).
     * @param n Length of input (must be 65).
     */
bool decode_tls_point(P256Point& out, const uint8_t* p, size_t n);
    static bool decodeTls(P256Point& out, const uint8_t* p, size_t n);

    /**
 * @brief ECDH Shared Secret calculation.
 * Extracts the X-coordinate of the resulting point (k * Peer_Public).
     * @brief ECDH Shared Secret calculation: extracts the X-coordinate of
     * (priv * this), where `this` is the remote peer's public key.
     * @param out32 Target buffer for the secret (32 bytes, Big-Endian).
     * @param priv Local private key.
 * @param peer Remote peer's public key.
     * @return true on success, false if the resulting point is at infinity.
     */
bool ecdh_shared_secret(uint8_t out32[32], const uint8_t priv[32], const P256Point& peer);
    bool ecdh(uint8_t out32[32], const uint8_t priv[32]) const;
};

/**
 * @brief The 'b' coefficient of the NIST P-256 curve equation.
 */
extern const u256 P256_B;

} // namespace netplus
+112 −158

File changed.

Preview size limit exceeded, changes collapsed.

+76 −62
Changes for src/crypto/ecc_u256.h: 76 added lines, 62 removed lines.
Original line number Diff line number Diff line
@@ -4,72 +4,86 @@

namespace netplus {

struct u256 { uint32_t w[8]; };
struct u512 { uint32_t w[16]; };
struct u512;

/**
 * @brief 256-bit little-endian integer (w[0] = least significant word).
 *
 * u256 is reused for three distinct algebraic structures depending on
 * context: a plain 256-bit unsigned integer, a GF(P256_P) field element
 * (Montgomery domain), and a Z/P256_N scalar (ECDSA r/s/k, a *different*
 * modulus). To keep that unambiguous, the arithmetic operators below only
 * ever mean raw, modulus-free integer arithmetic (mod 2^256 wraparound,
 * widening multiply, magnitude comparison) -- exactly what u256_add_raw /
 * u256_mul_raw / u256_cmp meant before this was a class. Field arithmetic
 * (Montgomery domain, mod P256_P) and scalar arithmetic (mod P256_N) are
 * intentionally named methods, never operators: silently mixing up the two
 * moduli would compute wrong ECDSA signatures without any compiler error.
 */
struct u256 {
    uint32_t w[8];

    // -------- construction / conversion --------
    static u256 zero();
    static u256 one();
    static u256 fromBigEndian(const uint8_t be32[32]);
    void toBigEndian(uint8_t out32[32]) const;

    bool isZero() const;

    // -------- comparison (raw magnitude) --------
    int compare(const u256& other) const;
    bool operator==(const u256& other) const { return compare(other) == 0; }
    bool operator!=(const u256& other) const { return compare(other) != 0; }
    bool operator<(const u256& other)  const { return compare(other) < 0; }
    bool operator<=(const u256& other) const { return compare(other) <= 0; }
    bool operator>(const u256& other)  const { return compare(other) > 0; }
    bool operator>=(const u256& other) const { return compare(other) >= 0; }

    // -------- raw arithmetic (mod 2^256, no field/scalar reduction) --------
    u256 addRaw(const u256& other, uint32_t& carry) const;
    u256 subRaw(const u256& other, uint32_t& borrow) const;
    u256 operator+(const u256& other) const { uint32_t c; return addRaw(other, c); }
    u256 operator-(const u256& other) const { uint32_t b; return subRaw(other, b); }
    u512 operator*(const u256& other) const; // widening multiply -> 512-bit product

    /// Constant-time conditional swap (swap must be 0 or 1).
    static void cswap(u256& a, u256& b, uint32_t swap);

    // -------- GF(P256_P) field arithmetic (Montgomery domain) --------
    u256 toMontgomery() const;
    u256 fromMontgomery() const;
    u256 montgomeryAdd(const u256& other) const;
    u256 montgomerySub(const u256& other) const;
    u256 montgomeryMul(const u256& other) const;
    u256 montgomerySquare() const;
    u256 montgomeryInverse() const;

    // -------- Z/P256_N scalar arithmetic (ECDSA r, s, k) --------
    u256 scalarAddModN(const u256& other) const;
    u256 scalarMulModN(const u256& other) const;
    u256 scalarInverseModN() const;

private:
    static u256 redc(const u256& a, const u256& b);
};

struct u512 {
    uint32_t w[16];

    static u512 fromBigEndian(const uint8_t be64[64]);

    /// Reduce mod the P-256 field prime (was mod_p256).
    u256 reduceModP() const;
    /// Reduce mod the P-256 group order (was mod_n256), for ECDSA scalars.
    u256 reduceModN() const;
};

extern const u256 P256_P;
extern const u256 P256_R2;
extern const u256 P256_N; // curve order n, used for ECDSA scalar arithmetic

// -------- low-level helpers --------
void u256_zero(u256& a);
bool u256_is_zero(const u256& a);

static inline void u256_one(u256& a) {
    u256_zero(a);
    a.w[0] = 1;
}

static inline void cswap_u256(u256& A, u256& B, uint32_t swap)
{
    // swap is 0 or 1
    uint32_t mask = 0u - swap;  // 0x00000000 or 0xFFFFFFFF

    for (int i = 0; i < 8; i++) {
        uint32_t t = (A.w[i] ^ B.w[i]) & mask;
        A.w[i] ^= t;
        B.w[i] ^= t;
    }
}


int  u256_cmp(const u256& a, const u256& b);

// raw ops (no mod reduction)
u256 u256_add_raw(const u256& a, const u256& b, uint32_t& carry);
u256 u256_sub_raw(const u256& a, const u256& b, uint32_t& borrow);

// conversion (network BE <-> internal LE)
u256 u256_from_be(const uint8_t be32[32]);
void u256_to_be(uint8_t out32[32], const u256& a);
u512 u512_from_be(const uint8_t in[64]);
u256 bytes_be_to_u256(const uint8_t in[32]);
// multiply
u512 u256_mul_raw(const u256& a, const u256& b);

// Montgomery core
u256 mont_mul(const u256& a, const u256& b);
u256 to_mont(const u256& a);
u256 from_mont(const u256& a);

// field ops (Montgomery domain)
u256 fp_add(const u256& a, const u256& b);
u256 fp_sub(const u256& a, const u256& b);
u256 fp_mul(const u256& a, const u256& b);
u256 fp_sqr(const u256& a);

// inversion (works with Montgomery domain inputs)
u256 fp_inv(const u256& a);

// scalar bit access
// Scalar bit access (MSB-first), used by Montgomery-ladder scalar multiplication.
uint32_t get_bit_be(const uint8_t priv[32], int bit_index);

// reduction (512 -> 256 mod P)
u256 mod_p256(const u512& in);

// scalar field arithmetic (mod n, group order) for ECDSA
u256 mod_n256(const u512& in);
u256 scalar_mul_mod_n(const u256& a, const u256& b);
u256 scalar_add_mod_n(const u256& a, const u256& b);
u256 scalar_inv_mod_n(const u256& a);

} // namespace netplus
+42 −43

File changed.

Preview size limit exceeded, changes collapsed.

Loading