pkix-path 0.6.1

RFC 5280 X.509 certificate path validation — pure Rust, no_std
Documentation
//! brainpoolP512r1 (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
//! brainpoolP512r1.
//!
//! 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
//!
//! brainpoolP512r1 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 brainpoolP512r1 *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), brainpoolP512r1 ×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 brainpoolP512r1 -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::U64},
    bigint::{Odd, U512},
};

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

/// Field modulus `p`, RFC 5639 §3.7.
const MODULUS_HEX: &str = "aadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca7033087\
17d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3";
/// Group order `q`, RFC 5639 §3.7.
const ORDER_HEX: &str = "aadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca7033087\
0553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069";

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

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

/// 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, U512};
    use elliptic_curve::{
        ff::PrimeField,
        ops::BatchInvert,
        subtle::{Choice, ConstantTimeEq, CtOption},
    };

    primefield::monty_field_params! {
        name: FieldParams,
        modulus: MODULUS_HEX,
        uint: U512,
        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: 2,
        doc: "Montgomery parameters for brainpoolP512r1's field modulus"
    }

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

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

    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, U512};
        primefield::test_primefield!(FieldElement, U512);
    }
}

/// 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::{BrainpoolP512r1, ORDER, ORDER_HEX, U512};
    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: U512,
        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: 7,
        doc: "Montgomery parameters for brainpoolP512r1's scalar modulus"
    }

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

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

    primefield::monty_field_reduce! {
        name: Scalar,
        params: ScalarParams,
        uint: U512,
    }

    elliptic_curve::scalar_impls!(BrainpoolP512r1, 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 = U512;

        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: U512 = 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, U512};
        primefield::test_primefield!(Scalar, U512);
    }
}

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

impl elliptic_curve::Curve for BrainpoolP512r1 {
    type FieldBytesSize = U64;
    type Uint = U512;

    const ORDER: Odd<U512> = ORDER;
}

impl elliptic_curve::PrimeCurve for BrainpoolP512r1 {}

impl elliptic_curve::point::PointCompression for BrainpoolP512r1 {
    /// 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 brainpoolP512r1.
pub type AffinePoint = primeorder::AffinePoint<BrainpoolP512r1>;
/// Projective point on brainpoolP512r1.
pub type ProjectivePoint = primeorder::ProjectivePoint<BrainpoolP512r1>;

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

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

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

impl primeorder::PrimeCurveParams for BrainpoolP512r1 {
    /// `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(
        "7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc\
2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca",
    );
    const EQUATION_B: FieldElement = FieldElement::from_hex_vartime(
        "3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a7\
2bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723",
    );
    const GENERATOR: (FieldElement, FieldElement) = (
        FieldElement::from_hex_vartime(
            "81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098e\
ff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822",
        ),
        FieldElement::from_hex_vartime(
            "7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111\
b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892",
        ),
    );
}

impl ecdsa::EcdsaCurve for BrainpoolP512r1 {
    /// `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 BrainpoolP512r1 {
    type Digest = sha2::Sha512;
}