Skip to main content

pkix_path/
ed521.rs

1//! Ed521 (EdDSA over curve E-521), as specified by ICP-Brasil.
2//!
3//! # ⚠ DO NOT USE THIS FOR ANYTHING ELSE
4//!
5//! **This module exists to verify one certificate and should not be
6//! used for any other purpose.** It is the least-validated code in this
7//! workspace by a wide margin, and that is not a solvable problem with
8//! the material available.
9//!
10//! Every other primitive added to this crate was checked against either
11//! an independent implementation or a published test vector with
12//! intermediate values. This one has neither:
13//!
14//! - **No published test vectors exist.** DOC-ICP-01.01 specifies the
15//!   parameters completely and publishes no examples. RFC 8032 covers
16//!   Ed25519 and Ed448 only, so its vectors do not apply.
17//! - **No second Rust implementation exists** to differential-test
18//!   against, and no OpenSSL support.
19//! - **Exactly one real signature exercises it**: the `AC Raiz
20//!   Brasileira v7` certificate in
21//!   `third_party/trust-stores/br-icpbrasil/`. One signature proves the
22//!   happy path and nothing else.
23//!
24//! So the **edge cases are untested**: the identity point, small-order
25//! points, non-canonical `y >= p` encodings, cofactor behaviour, points
26//! off the curve, and malleability of `S` are covered by argument and by
27//! reading RFC 8032, not by a vector that would catch getting them
28//! wrong. A general-purpose EdDSA implementation needs all of that
29//! covered before anyone relies on it, and this is not one.
30//!
31//! It is behind the `ed521` feature, off by default and outside the
32//! `rustcrypto` umbrella, for exactly that reason. It is here for
33//! completeness of the vendored corpus -- so that no certificate in
34//! `third_party/trust-stores/` is refused for an algorithm nobody
35//! looked at -- and the one certificate it verifies is the only place it
36//! will ever appear.
37//!
38//! # What Ed521 is
39//!
40//! EdDSA (RFC 8032's construction) over **E-521**, an untwisted Edwards
41//! curve. ICP-Brasil's `AC Raiz Brasileira v7` root is signed with it:
42//! the first official Brazilian root CA on E-521, per Kryptus, whose
43//! kNET HSMs the ITI operates.
44//!
45//! # Where the parameters come from
46//!
47//! DOC-ICP-01.01 ("Padrões e Algoritmos Criptográficos da ICP-Brasil"),
48//! section **"Parâmetros para a curva E521"**, which gives the full
49//! RFC 8032 parameter table and states the construction is
50//! "PureEdDSA e HashEdDSA, conforme RFC 8032":
51//!
52//! | parameter | value |
53//! |---|---|
54//! | `p` | `2^521 - 1` |
55//! | `a` | 1 (so the curve is `x² + y² = 1 + d·x²·y²`, untwisted) |
56//! | `d` | `-376014` |
57//! | `b` | 528, so a key is 66 octets and a signature 132 |
58//! | GF(p) encoding | 527-bit **little-endian** |
59//! | `H(x)` | `SHAKE256(dom5(phflag, context) ‖ x, 132)` |
60//! | `phflag` | 0, i.e. PureEdDSA; `PH` is the identity |
61//! | cofactor | 4 (the document gives `c = 2`, its base-2 logarithm) |
62//! | `B` | `(X, 12)` |
63//! | `L` | the order of E-521, 519 bits |
64//! | `dom5(x,y)` | `"SigEd521" ‖ octet(x) ‖ octet(OLEN(y)) ‖ y` |
65//!
66//! The parameters here are checked rather than trusted: this module's
67//! tests recompute that `B` satisfies the curve equation and that
68//! `[L]B` is the identity.
69//!
70//! # The OID, and why it is cited from the certificate
71//!
72//! The signature algorithm is `1.3.6.1.4.1.44588.2.1`. **DOC-ICP-01.01
73//! never gives that number** -- it names the algorithm only
74//! symbolically, as `id-Ed521`. The binding to that arc appears in
75//! third-party code (the `edgetk` tool and the `kya-icp` monitor), which
76//! is weak evidence for a normative claim.
77//!
78//! What makes it solid is the certificate: `AC Raiz Brasileira v7`
79//! declares `1.3.6.1.4.1.44588.2.1` and its signature verifies as
80//! Ed521 under these parameters. A wrong algorithm would not verify, so
81//! the binding is established by the artifact rather than by the
82//! documentation.
83//!
84//! # Verification
85//!
86//! RFC 8032 §5.2.7, with E-521's parameters substituted. Given a public
87//! key `A`, a signature split into `R ‖ S`, and a message `M`:
88//!
89//! 1. decode `A` and `R` as compressed Edwards points, reject `S >= L`;
90//! 2. `k = SHAKE256(dom5(0, "") ‖ R ‖ A ‖ M, 132)` read little-endian,
91//!    reduced mod `L`;
92//! 3. accept iff `[S]B = R + [k]A`.
93
94use crypto_bigint::modular::ConstMontyForm;
95use crypto_bigint::{NonZero, U576, const_monty_params};
96
97// `p = 2^521 - 1`, carried in a 576-bit integer because 521 is not a
98// machine-word multiple. DOC-ICP-01.01, `p`. The macro takes its own
99// doc string, so this is a plain comment.
100const_monty_params!(FieldP, U576, PARAM_P, "E-521's field modulus, 2^521 - 1");
101
102const PARAM_P: &str = PP;
103const PP: &str = "00000000000001ffffffffffffffffffffffffffffffffffffffffffffffffff\
104        ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\
105        ffffffffffffffff";
106
107/// The order of E-521. DOC-ICP-01.01, `L`.
108const PARAM_L: U576 = U576::from_be_hex(
109    "000000000000007fffffffffffffffffffffffffffffffffffffffffffffffff\
110        fffffffffffffffd15b6c64746fc85f736b8af5e7ec53f04fbd8c4569a8f1f45\
111        40ea2435f5180d6b",
112);
113
114/// `d = -376014`, reduced. DOC-ICP-01.01, `d`.
115const PARAM_D_NEG: U576 = U576::from_u64(376_014);
116
117/// `B`'s affine coordinates. DOC-ICP-01.01, `B`.
118const PARAM_BX: U576 = U576::from_be_hex(
119    "00000000000000752cb45c48648b189df90cb2296b2878a3bfd9f42fc6c818ec\
120        8bf3c9c0c6203913f6ecc5ccc72434b1ae949d568fc99c6059d0fb13364838aa\
121        302a940a2f19ba6c",
122);
123const PARAM_BY: U576 = U576::from_u64(12);
124
125/// A field element modulo `p`.
126type Fe = ConstMontyForm<FieldP, { U576::LIMBS }>;
127
128fn fe(v: &U576) -> Fe {
129    Fe::new(v)
130}
131
132/// `x^e mod p`, used for both inversion (`e = p-2`) and the square root
133/// (`e = (p+1)/4`, valid because `p ≡ 3 mod 4`).
134fn fe_pow(x: Fe, e: &U576) -> Fe {
135    x.pow_amm(e)
136}
137
138fn fe_inv(x: Fe) -> Fe {
139    // Fermat rather than a gcd: `p` is prime, and this module values
140    // being obviously correct over being fast.
141    let e = p_minus(2);
142    fe_pow(x, &e)
143}
144
145fn p_minus(k: u64) -> U576 {
146    U576::from_be_hex(PP).wrapping_sub(&U576::from_u64(k))
147}
148
149/// An affine point on `x² + y² = 1 + d·x²·y²`.
150#[derive(Clone, Copy)]
151struct Point {
152    x: Fe,
153    y: Fe,
154}
155
156impl Point {
157    /// The neutral element, `(0, 1)`.
158    fn identity() -> Self {
159        Self {
160            x: fe(&U576::ZERO),
161            y: fe(&U576::ONE),
162        }
163    }
164
165    fn eq(&self, other: &Self) -> bool {
166        self.x == other.x && self.y == other.y
167    }
168
169    /// Untwisted Edwards addition, the `a = 1` formulas:
170    ///
171    /// ```text
172    /// x3 = (x1·y2 + x2·y1) / (1 + d·x1·x2·y1·y2)
173    /// y3 = (y1·y2 - x1·x2) / (1 - d·x1·x2·y1·y2)
174    /// ```
175    ///
176    /// Affine with an inversion per addition. That is slow and it is the
177    /// right trade here: this runs once per certificate, and a
178    /// projective implementation would add the completeness questions
179    /// this module has no vectors to check.
180    fn add(&self, other: &Self) -> Self {
181        let d = fe(&U576::ZERO) - fe(&PARAM_D_NEG);
182        let one = fe(&U576::ONE);
183        let t = d * self.x * other.x * self.y * other.y;
184        let x3 = (self.x * other.y + other.x * self.y) * fe_inv(one + t);
185        let y3 = (self.y * other.y - self.x * other.x) * fe_inv(one - t);
186        Self { x: x3, y: y3 }
187    }
188
189    /// `[k]self`, double-and-add over the bits of `k`.
190    ///
191    /// Not constant-time. Verification handles only public values -- the
192    /// key, the signature and the message -- so there is no secret for a
193    /// timing channel to leak. Signing would need otherwise, which is
194    /// one more reason this module does not sign.
195    fn mul(&self, k: &U576) -> Self {
196        let mut acc = Self::identity();
197        let mut base = *self;
198        for i in 0..U576::BITS {
199            if bool::from(k.bit(i)) {
200                acc = acc.add(&base);
201            }
202            base = base.add(&base);
203        }
204        acc
205    }
206}
207
208/// Decode a 66-octet compressed point, RFC 8032 §5.2.3's shape with
209/// `a = 1`.
210///
211/// The encoding is little-endian per DOC-ICP-01.01's "527-bit
212/// codificação little-endian", with `x`'s sign in the top bit of the
213/// last octet -- bit `b-1 = 527`.
214///
215/// Returns `None` for a non-canonical `y >= p`, for a `y` with no
216/// corresponding `x` on the curve, and for the `x = 0` case with the
217/// sign bit set, which RFC 8032 rejects because it encodes a point twice.
218fn decompress(enc: &[u8; 66]) -> Option<Point> {
219    let sign = (enc[65] >> 7) & 1;
220
221    let mut le = *enc;
222    le[65] &= 0x7f; // clear bit 527, the sign
223    let mut be = le;
224    be.reverse();
225    let mut wide = [0u8; 72];
226    wide[6..].copy_from_slice(&be);
227    let y_int = U576::from_be_slice(&wide);
228    if y_int >= U576::from_be_hex(PP) {
229        return None; // non-canonical
230    }
231
232    let y = fe(&y_int);
233    let one = fe(&U576::ONE);
234    let d = fe(&U576::ZERO) - fe(&PARAM_D_NEG);
235    // x² = (1 - y²) / (1 - d·y²)
236    let num = one - y * y;
237    let den = one - d * y * y;
238    if den == fe(&U576::ZERO) {
239        return None;
240    }
241    let x2 = num * fe_inv(den);
242
243    // p ≡ 3 (mod 4), so a square root is x2^((p+1)/4).
244    let exp = U576::from_be_hex(PP)
245        .wrapping_add(&U576::ONE)
246        .shr_vartime(2);
247    let mut x = fe_pow(x2, &exp);
248    if x * x != x2 {
249        return None; // y does not correspond to a curve point
250    }
251
252    let x_canon = x.retrieve();
253    let x_is_odd = bool::from(x_canon.is_odd());
254    if x_canon == U576::ZERO && sign == 1 {
255        return None;
256    }
257    if x_is_odd != (sign == 1) {
258        x = fe(&U576::ZERO) - x;
259    }
260    Some(Point { x, y })
261}
262
263/// Verify an Ed521 signature, RFC 8032 §5.2.7 over E-521.
264///
265/// `signature` is `R ‖ S`, 66 octets each. `public_key` is the
266/// compressed `A`.
267///
268/// # ⚠
269///
270/// See the module docs: this is validated by one real signature and no
271/// test vectors, and its edge cases are untested. Do not use it outside
272/// verifying the ICP-Brasil `AC Raiz v7` certificate.
273#[must_use]
274pub fn verify(public_key: &[u8; 66], signature: &[u8; 132], message: &[u8]) -> bool {
275    use shake::digest::{ExtendableOutput, Update, XofReader};
276
277    let mut r_enc = [0u8; 66];
278    let mut s_enc = [0u8; 66];
279    r_enc.copy_from_slice(&signature[..66]);
280    s_enc.copy_from_slice(&signature[66..]);
281
282    // Step 1: decode A and R, and reject S outside [0, L).
283    let Some(a_point) = decompress(public_key) else {
284        return false;
285    };
286    let Some(r_point) = decompress(&r_enc) else {
287        return false;
288    };
289    let s_int = {
290        let mut be = s_enc;
291        be.reverse();
292        let mut wide = [0u8; 72];
293        wide[6..].copy_from_slice(&be);
294        U576::from_be_slice(&wide)
295    };
296    if s_int >= PARAM_L {
297        // RFC 8032 §5.2.7: S must be reduced. Accepting an unreduced S
298        // would make signatures malleable.
299        return false;
300    }
301
302    // Step 2: k = H(dom5(0, "") ‖ R ‖ A ‖ M) mod L, read little-endian.
303    //
304    // dom5 per DOC-ICP-01.01: "SigEd521" ‖ octet(phflag) ‖
305    // octet(OLEN(context)) ‖ context. phflag is 0 for PureEdDSA and the
306    // context is empty for X.509, so the prefix is the ten octets
307    // "SigEd521".
308    let mut xof = shake::Shake256::default();
309    xof.update(b"SigEd521");
310    xof.update(&[0u8]); // phflag = 0, PureEdDSA
311    xof.update(&[0u8]); // OLEN(context) = 0
312    xof.update(&r_enc);
313    xof.update(public_key);
314    xof.update(message);
315    let mut h = [0u8; 132];
316    xof.finalize_xof().read(&mut h);
317
318    // 132 octets is wider than U576, so the reduction is done on the
319    // value's own width before narrowing: fold the high octets in by
320    // Horner's method modulo L.
321    let k = reduce_mod_l(&h);
322
323    // Step 3: [S]B = R + [k]A.
324    let b_point = Point {
325        x: fe(&PARAM_BX),
326        y: fe(&PARAM_BY),
327    };
328    let lhs = b_point.mul(&s_int);
329    let rhs = r_point.add(&a_point.mul(&k));
330    lhs.eq(&rhs)
331}
332
333/// Reduce a 132-octet little-endian integer modulo `L`.
334///
335/// `H` is wider than `U576`, so it cannot simply be loaded. The octets
336/// are folded in from the most significant end, `acc = acc·256 + byte`
337/// with a reduction each step, which is Horner's method on base 256 and
338/// avoids needing a 1056-bit integer type.
339fn reduce_mod_l(h_le: &[u8; 132]) -> U576 {
340    let mut acc = U576::ZERO;
341    let two56 = U576::from_u64(256);
342    for byte in h_le.iter().rev() {
343        // acc = acc * 256 + byte, mod L
344        let l = NonZero::new(PARAM_L).expect("L is non-zero");
345        acc = acc.mul_mod(&two56, &l);
346        let add = U576::from_u64(u64::from(*byte));
347        acc = acc.add_mod(&add, &l);
348    }
349    acc
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355
356    /// The parameters are recomputed rather than trusted.
357    ///
358    /// `B` must satisfy `x² + y² = 1 + d·x²·y²`, and `[L]B` must be the
359    /// identity. Both would fail on a mistranscribed constant, which is
360    /// the failure mode this module is most exposed to given it has no
361    /// vectors.
362    #[test]
363    fn the_base_point_is_on_the_curve_and_has_order_l() {
364        let b = Point {
365            x: fe(&PARAM_BX),
366            y: fe(&PARAM_BY),
367        };
368        let one = fe(&U576::ONE);
369        let d = fe(&U576::ZERO) - fe(&PARAM_D_NEG);
370        let lhs = b.x * b.x + b.y * b.y;
371        let rhs = one + d * b.x * b.x * b.y * b.y;
372        assert_eq!(lhs, rhs, "B must satisfy the E-521 curve equation");
373
374        let lb = b.mul(&PARAM_L);
375        assert!(
376            lb.eq(&Point::identity()),
377            "[L]B must be the identity, i.e. B generates the order-L subgroup"
378        );
379    }
380}