pkix-path 0.7.1

RFC 5280 X.509 certificate path validation — pure Rust, no_std
Documentation
//! brainpoolP224r1 (RFC 5639 §3.7), implemented here because no crate
//! provides it.
//!
//! # Why this file exists
//!
//! RustCrypto publishes `bp256` and `bp384`. It does not publish a
//! `bp512`, and the reason is not difficulty: each of those crates
//! carries about 31,000 lines of field and scalar arithmetic generated
//! by **fiat-crypto**, once per word size, whose own header reads
//!
//! ```text
//! Autogenerated: fiat-crypto word-by-word-montgomery --lang Rust \
//!   --inline bp384 32 0x8cb91e82a3386d28...
//! ```
//!
//! against roughly 130 lines written by hand. Producing and reviewing
//! that output is a per-curve job, and nobody has done it for
//! brainpoolP224r1.
//!
//! The generated code is an **optimization**, not a requirement. Those
//! crates also carry a second backend, selected with
//! `--cfg bp384_backend="bigint"`, which builds the same field from a
//! hex modulus through three `primefield` macros. This module takes that
//! path: generic Montgomery arithmetic from `crypto-bigint`, no
//! generated code, no new dependencies -- `primefield`, `primeorder` and
//! `elliptic-curve` were already in the tree as dependencies of
//! `bp256`.
//!
//! The cost is speed. Generic Montgomery multiplication is slower than
//! fiat-crypto's specialized reduction. For **signature verification**
//! that is the right trade: there is no secret in a verification, so the
//! constant-time argument that motivates the specialized code does not
//! apply, and nobody is verifying passports in a tight loop.
//!
//! # Why it is worth the trouble
//!
//! brainpoolP224r1 is the curve under **three of the eight roots** in
//! Germany's CSCA archive (`third_party/trust-stores/de-csca/`) and 17
//! certificates of the ICAO corpus.
//!
//! Measured, because an earlier version of this comment claimed the
//! German archive was brainpoolP224r1 *throughout* and it is not. BSI
//! moved curve across generations, and the 23 certificates divide as
//! brainpoolP256r1 ×9 (2 roots, 1 link, 6 signers), brainpoolP384r1 ×6
//! (3 roots, 3 links), brainpoolP224r1 ×6 (3 roots, 3 links) and
//! brainpoolP224r1 ×2 (2 signers). So this module unblocks the newest
//! three roots rather than the whole archive; `bp384` unblocks three
//! more, and `bp256` the last two once a separate question about RFC
//! 5758 §3.2 is settled.
//!
//! What was true either way: before any brainpool support, **no German
//! root could be verified at all**. BSI's choice of curve is BSI's to
//! make, and once their root is an anchor our having no arithmetic for
//! it is our gap, not a defect in their certificate.
//!
//! # This is a stopgap
//!
//! When RustCrypto publishes a `bp512`, delete this file, add the
//! dependency, and move the table entry in [`crate::specified_curve`] to
//! point at it. The curve parameters here are the ones that crate will
//! also use, so the change is mechanical. Better still, the contents of
//! this file are most of an upstream contribution.
//!
//! # Parameters
//!
//! Taken from RFC 5639 §3.7 and cross-checked against OpenSSL's
//! `ecparam -name brainpoolP224r1 -param_enc explicit`. The generator is
//! verified to lie on the curve and the curve to be non-singular by
//! this module's own tests, which recompute both rather than trusting
//! the constants.

use elliptic_curve::{
    array::{Array, typenum::U28},
    bigint::{Odd, U256},
};

/// brainpoolP224r1.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, PartialOrd, Ord)]
pub struct BrainpoolP224r1;

/// Field modulus `p`, RFC 5639 §3.7.
/// Left-padded to the 256-bit uint width. `U224` exists only on 32-bit
/// targets, because 224 is not a multiple of 64, so the field is carried
/// in a `U256` -- the same shape as `p521` carrying a 521-bit field in
/// `U576`. The padding is encoding, not a different modulus.
const MODULUS_HEX: &str = "00000000d7c134aa264366862a18302575d1d787b09f075797da89f57ec8c0ff";
/// Group order `q`, RFC 5639 §3.7.
const ORDER_HEX: &str = "00000000d7c134aa264366862a18302575d0fb98d116bc4b6ddebca3a5a7939f";

const ORDER: Odd<U256> = Odd::<U256>::from_be_hex(ORDER_HEX);

/// Byte representation of a base or scalar field element.
pub type FieldBytes = Array<u8, U28>;

/// The base field, modulo `p`.
///
/// Its own module because `primefield::monty_field_params!` emits a
/// `use` of `ConstMontyParams`, so the field and the scalar field cannot
/// be declared side by side.
// `primefield 0.14.0`'s `monty_field_params!` calls
// `crypto_bigint::Uint::bits`, which `crypto-bigint 0.7.11` deprecated
// in favour of `bit_width`. The call is in upstream's macro, not in
// anything written here, and this workspace builds with
// `RUSTFLAGS=-D warnings`, so the expansion is an error without this.
//
// Reported as part of the upstreaming work; nothing to fix locally
// beyond waiting for a `primefield` release that uses `bit_width`. At
// that point delete this attribute -- it is scoped to the module rather
// than crate-wide so that it stops applying the moment it is obsolete.
#[expect(deprecated)]
mod field {
    use super::{MODULUS_HEX, U256};
    use elliptic_curve::{
        ff::PrimeField,
        ops::BatchInvert,
        subtle::{Choice, ConstantTimeEq, CtOption},
    };

    primefield::monty_field_params! {
        name: FieldParams,
        modulus: MODULUS_HEX,
        uint: U256,
        byte_order: primefield::ByteOrder::BigEndian,
        // 2, not the 3 that `bp384` uses: 3 is a quadratic residue
        // modulo this prime and 2 is not, checked in `super::tests`.
        // 2, not the 3 that `bp384` uses: 3 is a quadratic residue
        // modulo this prime and 2 is not. Checked in `super::tests`.
        multiplicative_generator: 3,
        doc: "Montgomery parameters for brainpoolP224r1's field modulus"
    }

    primefield::monty_field_element! {
        name: FieldElement,
        params: FieldParams,
        uint: U256,
        doc: "Element of the brainpoolP224r1 base field, modulo p"
    }

    primefield::monty_field_arithmetic! {
        name: FieldElement,
        params: FieldParams,
        uint: U256
    }

    impl BatchInvert for FieldElement {}

    /// `primefield`'s own conformance suite for the base field.
    ///
    /// Upstream runs this against every curve it ships. Running it here
    /// means the arithmetic underneath this curve is checked by the
    /// crate that defines what correct means for it, rather than only by
    /// this workspace's certificate tests.
    #[cfg(test)]
    mod tests {
        use super::{FieldElement, U256};
        primefield::test_primefield!(FieldElement, U256);
    }
}

/// The scalar field, modulo `q`.
// `primefield 0.14.0`'s `monty_field_params!` calls
// `crypto_bigint::Uint::bits`, which `crypto-bigint 0.7.11` deprecated
// in favour of `bit_width`. The call is in upstream's macro, not in
// anything written here, and this workspace builds with
// `RUSTFLAGS=-D warnings`, so the expansion is an error without this.
//
// Reported as part of the upstreaming work; nothing to fix locally
// beyond waiting for a `primefield` release that uses `bit_width`. At
// that point delete this attribute -- it is scoped to the module rather
// than crate-wide so that it stops applying the moment it is obsolete.
#[expect(deprecated)]
mod scalar {
    use super::{BrainpoolP224r1, ORDER, ORDER_HEX, U256};
    use elliptic_curve::{
        ff::PrimeField,
        ops::BatchInvert,
        scalar::{FromUintUnchecked, IsHigh},
        subtle::{Choice, ConstantTimeEq, ConstantTimeGreater as _, CtOption},
    };

    primefield::monty_field_params! {
        name: ScalarParams,
        modulus: ORDER_HEX,
        uint: U256,
        byte_order: primefield::ByteOrder::BigEndian,
        // 7, the smallest quadratic non-residue modulo q. Not 2, which
        // is a residue here and makes the macro refuse at compile time
        // with "invalid generator" -- the validation that caught the
        // first guess. `super::tests` recomputes both.
        multiplicative_generator: 3,
        doc: "Montgomery parameters for brainpoolP224r1's scalar modulus"
    }

    primefield::monty_field_element! {
        name: Scalar,
        params: ScalarParams,
        uint: U256,
        doc: "Element of the brainpoolP224r1 scalar field, modulo q"
    }

    primefield::monty_field_arithmetic! {
        name: Scalar,
        params: ScalarParams,
        uint: U256
    }

    // `primefield::monty_field_reduce!` cannot be used for this curve.
    // Its bytes impl is bounded on
    // `Uint<LIMBS>: ArrayEncoding<ByteSize = MOD::ByteSize>` -- the
    // uint's byte width must EQUAL the field's byte size -- and
    // brainpoolP224r1 is a 28-byte field carried in a 32-byte `U256`,
    // because `U224` exists only on 32-bit targets. So the two impls are
    // written out here, the second widening before it reduces.
    //
    // `{ U256::LIMBS }` rather than a literal. A limb is one pointer
    // word, so `U256` is 4 limbs on a 64-bit target and 8 on a 32-bit
    // one. This said `4`, which is right on the host and wrong on
    // thumbv7em-none-eabi and riscv32 -- `ScalarParams` is generated by
    // `monty_field_params!` for the target's limb width, so on 32-bit it
    // implements `MontyFieldParams<8>` and the bound on `<_, 4>` cannot
    // be met. The bare-metal CI job was the only thing that compiled it
    // for a 32-bit target, and it had been failing on this.
    impl primefield::bigint::Reduce<U256> for Scalar {
        fn reduce(w: &U256) -> Self {
            Self(primefield::MontyFieldElement::<ScalarParams, { U256::LIMBS }>::reduce(w))
        }
    }

    impl primefield::bigint::Reduce<primefield::array::Array<u8, elliptic_curve::consts::U28>>
        for Scalar
    {
        fn reduce(bytes: &primefield::array::Array<u8, elliptic_curve::consts::U28>) -> Self {
            // Big-endian, matching `ByteOrder::BigEndian` above: the 28
            // octets are the low end of a 32-octet value.
            let mut wide = [0u8; 32];
            wide[4..].copy_from_slice(bytes.as_slice());
            <Self as primefield::bigint::Reduce<U256>>::reduce(&U256::from_be_slice(&wide))
        }
    }

    elliptic_curve::scalar_impls!(BrainpoolP224r1, Scalar);
    primeorder::wnaf::impl_wnaf_size_for_scalar!(Scalar);

    impl AsRef<Scalar> for Scalar {
        fn as_ref(&self) -> &Scalar {
            self
        }
    }

    impl FromUintUnchecked for Scalar {
        type Uint = U256;

        fn from_uint_unchecked(uint: Self::Uint) -> Self {
            Self::from_uint_unchecked(uint)
        }
    }

    impl IsHigh for Scalar {
        fn is_high(&self) -> Choice {
            const MODULUS_SHR1: U256 = ORDER.as_ref().shr_vartime(1);
            self.to_canonical().ct_gt(&MODULUS_SHR1)
        }
    }

    impl BatchInvert for Scalar {}

    /// `primefield`'s own conformance suite for the scalar field.
    #[cfg(test)]
    mod tests {
        use super::{Scalar, U256};
        primefield::test_primefield!(Scalar, U256);
    }
}

pub use self::{field::FieldElement, scalar::Scalar};

impl elliptic_curve::Curve for BrainpoolP224r1 {
    type FieldBytesSize = U28;
    type Uint = U256;

    const ORDER: Odd<U256> = ORDER;
}

impl elliptic_curve::PrimeCurve for BrainpoolP224r1 {}

impl elliptic_curve::point::PointCompression for BrainpoolP224r1 {
    /// Uncompressed, matching `bp256` and `bp384`. Every
    /// explicit-parameter certificate in the ICAO corpus encodes its
    /// generator and its public point uncompressed.
    const COMPRESS_POINTS: bool = false;
}

/// Affine point on brainpoolP224r1.
pub type AffinePoint = primeorder::AffinePoint<BrainpoolP224r1>;
/// Projective point on brainpoolP224r1.
pub type ProjectivePoint = primeorder::ProjectivePoint<BrainpoolP224r1>;

impl elliptic_curve::CurveArithmetic for BrainpoolP224r1 {
    type AffinePoint = AffinePoint;
    type ProjectivePoint = ProjectivePoint;
    type Scalar = Scalar;
}

impl elliptic_curve::hazmat::FieldArithmetic for BrainpoolP224r1 {
    type FieldElement = FieldElement;
}

impl elliptic_curve::PrimeCurveArithmetic for BrainpoolP224r1 {
    type CurveGroup = ProjectivePoint;
}

// NOTE ON TWO DIFFERENT HEX WIDTHS, which is a real trap here.
//
// `MODULUS_HEX` and `ORDER_HEX` above are padded to the 64-character
// `U256` width, because `const_prime_monty_params!` parses them as that
// uint. The curve constants below are the bare 56 characters, because
// `FieldElement::from_hex_vartime` parses at the field's `ByteSize`,
// which is 28 octets. Padding these produces "hex is the wrong length"
// at compile time, and leaving the modulus unpadded produces "hex string
// is not the expected size" -- both caught during construction rather
// than silently taken as a different value.
impl primeorder::PrimeCurveParams for BrainpoolP224r1 {
    /// `EquationAIsGeneric`, as `bp256` and `bp384` use: brainpool's `a`
    /// is an arbitrary field element, unlike the NIST curves where
    /// `a = -3` admits a faster formula.
    type PointArithmetic = primeorder::point_arithmetic::EquationAIsGeneric;
    type Backend = primeorder::mul_backend::VariableOnly;

    const EQUATION_A: FieldElement =
        FieldElement::from_hex_vartime("68a5e62ca9ce6c1c299803a6c1530b514e182ad8b0042a59cad29f43");
    const EQUATION_B: FieldElement =
        FieldElement::from_hex_vartime("2580f63ccfe44138870713b1a92369e33e2135d266dbb372386c400b");
    const GENERATOR: (FieldElement, FieldElement) = (
        FieldElement::from_hex_vartime("0d9029ad2c7e5cf4340823b2a87dc68c9e4ce3174c1e6efdee12c07d"),
        FieldElement::from_hex_vartime("58aa56f772c0726f24c6b89e4ecdac24354b9e99caa3f6d3761402cd"),
    );
}

impl ecdsa::EcdsaCurve for BrainpoolP224r1 {
    /// `false`, as `bp256` and `bp384` set it: RFC 5639 defines no
    /// low-`s` normalization, and a verifier that demanded one would
    /// reject valid signatures.
    const NORMALIZE_S: bool = false;
}

// No `cfg` on sha2: it is an optional dependency rather than a feature,
// and the `bp512` feature that gates this whole module already enables
// it.
impl ecdsa::DigestAlgorithm for BrainpoolP224r1 {
    type Digest = sha2::Sha256;
}