Skip to main content

ic_ec/
p384.rs

1//! NIST P-384 (secp384r1).
2//!
3//! The curve a CNSA-aligned profile requires, and the one TLS reaches for when
4//! 128-bit security is not considered enough. The field, group law, and schemes
5//! come from `crate::nist`; this module supplies the constants and the public
6//! API.
7//!
8//! Paired with SHA-384 throughout, which is the matching security level and
9//! also makes RFC 6979's bit-length handling collapse to a straight reduction,
10//! since the hash and the group order are both 384 bits wide.
11
12use crate::mont_field;
13use crate::nist::arith::{sqrt_p3mod4, Field};
14use crate::nist::point::Curve;
15use crate::nist::{ecdh, ecdsa};
16use ic_core::traits::{Algorithm, KeyAgreement, SelfTest, SignatureScheme};
17use ic_core::{ensure, Result};
18
19/// The prime `p`, little-endian.
20const P: [u64; 6] = [
21    0x0000_0000_ffff_ffff,
22    0xffff_ffff_0000_0000,
23    0xffff_ffff_ffff_fffe,
24    0xffff_ffff_ffff_ffff,
25    0xffff_ffff_ffff_ffff,
26    0xffff_ffff_ffff_ffff,
27];
28
29/// The group order `n`, little-endian.
30const N: [u64; 6] = [
31    0xecec_196a_ccc5_2973,
32    0x581a_0db2_48b0_a77a,
33    0xc763_4d81_f437_2ddf,
34    0xffff_ffff_ffff_ffff,
35    0xffff_ffff_ffff_ffff,
36    0xffff_ffff_ffff_ffff,
37];
38
39// On x86-64 both rings multiply in assembly on MULX/ADX where the CPU has it,
40// and by the generic word loop otherwise: the field in assembly specialised
41// to p (`nist::p384_x86_point`), with squaring of its own; the scalar ring
42// generic in the modulus (`nist::mont_x86`). The field inverts by divsteps
43// on 64-bit targets, by an addition chain on 32-bit ones.
44#[cfg(target_arch = "x86_64")]
45mont_field!(
46    Fp,
47    6,
48    48,
49    P,
50    "The P-384 coordinate field, GF(p) with p = 2^384 - 2^128 - 2^96 + 2^32 - 1.",
51    mul = fp_mul,
52    square = fp_sqr,
53    invert = fp_invert,
54    add = Self::add_raw,
55    sub = Self::sub_raw
56);
57
58#[cfg(not(target_arch = "x86_64"))]
59mont_field!(
60    Fp,
61    6,
62    48,
63    P,
64    "The P-384 coordinate field, GF(p) with p = 2^384 - 2^128 - 2^96 + 2^32 - 1.",
65    mul = Self::mont_mul_raw,
66    square = Self::mont_square_raw,
67    invert = fp_invert,
68    add = Self::add_raw,
69    sub = Self::sub_raw
70);
71
72/// `a^-1` in the coordinate field, Montgomery form in and out: by divsteps
73/// on 64-bit targets (`nist::safegcd`), by [`fp_invert_chain`] elsewhere.
74///
75/// The divsteps invert the integer they are given, so a Montgomery `a * R`
76/// comes back as `a^-1 * R^-1`; one Montgomery multiplication by `R^3`
77/// makes that `a^-1 * R`.
78#[cfg(all(target_pointer_width = "64", not(ic_limb32)))]
79fn fp_invert(a: [u64; 6]) -> [u64; 6] {
80    const R3: [u64; 6] = Fp::mont_mul_const(Fp::R2, Fp::R2);
81    Fp(crate::nist::safegcd::invert_384::<FpModulus>(&a))
82        .mul(&Fp(R3))
83        .0
84}
85
86/// The prime, for the divsteps.
87#[cfg(all(target_pointer_width = "64", not(ic_limb32)))]
88pub(crate) struct FpModulus;
89
90#[cfg(all(target_pointer_width = "64", not(ic_limb32)))]
91impl crate::nist::safegcd::Modulus<7> for FpModulus {
92    const INFO: crate::nist::safegcd::ModInfo<7> = crate::nist::safegcd::ModInfo::new(P);
93}
94
95#[cfg(not(all(target_pointer_width = "64", not(ic_limb32))))]
96fn fp_invert(a: [u64; 6]) -> [u64; 6] {
97    fp_invert_chain(a)
98}
99
100/// `a^(p-2)`, the inverse by Fermat, by an addition chain: 385 squarings
101/// and 14 multiplications, where [`Fp::pow`]'s four-bit window takes 380
102/// squarings, 109 multiplications and 96 table scans. What 32-bit targets
103/// use, where the divsteps' 128-bit products would be library calls; on
104/// 64-bit targets the tests' reference for the divsteps.
105///
106/// `p - 2` is, from the top, 255 ones, a zero, 32 ones, 64 zeros, 30 ones,
107/// a zero and a one. `x_k` below is `a^(2^k - 1)`, a run of `k` ones.
108/// Nothing depends on `a` but the values: the chain is a constant sequence
109/// of squarings and multiplications. The tests hold it to `Fp::pow`.
110#[cfg(any(test, not(all(target_pointer_width = "64", not(ic_limb32)))))]
111fn fp_invert_chain(a: [u64; 6]) -> [u64; 6] {
112    let x1 = Fp(a);
113    let x2 = x1.square().mul(&x1);
114    let x3 = x2.square().mul(&x1);
115    let x6 = x3.square_n(3).mul(&x3);
116    let x12 = x6.square_n(6).mul(&x6);
117    let x15 = x12.square_n(3).mul(&x3);
118    let x30 = x15.square_n(15).mul(&x15);
119    let x32 = x30.square_n(2).mul(&x2);
120    let x60 = x30.square_n(30).mul(&x30);
121    let x120 = x60.square_n(60).mul(&x60);
122    let x240 = x120.square_n(120).mul(&x120);
123    let x255 = x240.square_n(15).mul(&x15);
124    // 255 ones, then a zero, then 32 ones.
125    let t = x255.square_n(33).mul(&x32);
126    // 64 zeros, then 30 ones.
127    let t = t.square_n(94).mul(&x30);
128    // A zero and a one.
129    t.square_n(2).mul(&x1).0
130}
131
132#[cfg(target_arch = "x86_64")]
133mont_field!(
134    Fn,
135    6,
136    48,
137    N,
138    "The P-384 scalar ring, Z/nZ where n is the order of the base point.",
139    mul = fn_mul,
140    square = |a| fn_mul(a, a),
141    invert = Self::invert_raw,
142    add = Self::add_raw,
143    sub = Self::sub_raw
144);
145
146#[cfg(not(target_arch = "x86_64"))]
147mont_field!(
148    Fn,
149    6,
150    48,
151    N,
152    "The P-384 scalar ring, Z/nZ where n is the order of the base point."
153);
154
155/// The last step of Montgomery multiplication: `t` below `2m`, with its top
156/// word, made canonical by one subtraction chosen behind the barrier.
157#[cfg(target_arch = "x86_64")]
158#[inline(always)]
159fn canonical(t: [u64; 6], top: u64, m: [u64; 6]) -> [u64; 6] {
160    let (reduced, borrow) = crate::nist::arith::sbb(t, m);
161    crate::nist::arith::select_ct((top | (1 - borrow)).wrapping_neg(), reduced, t)
162}
163
164/// `a * b * 2^-384 mod p`.
165#[cfg(target_arch = "x86_64")]
166#[inline(always)]
167fn fp_mul(a: [u64; 6], b: [u64; 6]) -> [u64; 6] {
168    match crate::nist::p384_x86::mul_p(&a, &b) {
169        Some(r) => r,
170        None => Fp::mont_mul_raw(a, b),
171    }
172}
173
174/// `a^2 * 2^-384 mod p`.
175#[cfg(target_arch = "x86_64")]
176#[inline(always)]
177fn fp_sqr(a: [u64; 6]) -> [u64; 6] {
178    match crate::nist::p384_x86::sqr_p(&a) {
179        Some(r) => r,
180        None => Fp::mont_mul_raw(a, a),
181    }
182}
183
184/// `a * b * 2^-384 mod n`.
185#[cfg(target_arch = "x86_64")]
186#[inline(always)]
187fn fn_mul(a: [u64; 6], b: [u64; 6]) -> [u64; 6] {
188    match crate::nist::p384_x86::mul_n(&a, &b) {
189        Some((t, top)) => canonical(t, top, N),
190        None => Fn::mont_mul_raw(a, b),
191    }
192}
193
194/// The P-384 curve.
195#[derive(Debug, Clone, Copy)]
196pub struct P384;
197
198// Its own generator table, with its own storage; see the macro, which
199// emits the table under `std` and the windowed multiplication without it.
200crate::nist::gentable::generator_table_for!(P384, 16);
201
202impl Curve for P384 {
203    type Field = Fp;
204    type Scalar = Fn;
205
206    const NAME: &'static str = "P-384";
207    const FIELD_BYTES: usize = 48;
208    const SCALAR_BYTES: usize = 48;
209    const ORDER_BITS: usize = 384;
210
211    /// `b = 0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875a`
212    ///     `c656398d8a2ed19d2a85c8edd3ec2aef`
213    const B: Fp = Fp::to_mont_const([
214        0x2a85_c8ed_d3ec_2aef,
215        0xc656_398d_8a2e_d19d,
216        0x0314_088f_5013_875a,
217        0x181d_9c6e_fe81_4112,
218        0x988e_056b_e3f8_2d19,
219        0xb331_2fa7_e23e_e7e4,
220    ]);
221
222    const GX: Fp = Fp::to_mont_const([
223        0x3a54_5e38_7276_0ab7,
224        0x5502_f25d_bf55_296c,
225        0x59f7_41e0_8254_2a38,
226        0x6e1d_3b62_8ba7_9b98,
227        0x8eb1_c71e_f320_ad74,
228        0xaa87_ca22_be8b_0537,
229    ]);
230
231    const GY: Fp = Fp::to_mont_const([
232        0x7a43_1d7c_90ea_0e5f,
233        0x0a60_b1ce_1d7e_819d,
234        0xe9da_3113_b5f0_b8c0,
235        0xf8f4_1dbd_289a_147c,
236        0x5d9e_98bf_9292_dc29,
237        0x3617_de4a_9626_2c6f,
238    ]);
239
240    /// `p = 3 mod 4`, so a square root is `x^((p+1)/4)`.
241    fn sqrt(x: &Fp) -> Fp {
242        sqrt_p3mod4(x, Fp::MODULUS, |v, e| v.pow(e))
243    }
244
245    fn field_from_slice(bytes: &[u8]) -> Option<Fp> {
246        let mut b = [0u8; 48];
247        if bytes.len() != 48 {
248            return None;
249        }
250        b.copy_from_slice(bytes);
251        Fp::from_bytes(&b)
252    }
253
254    fn scalar_from_slice(bytes: &[u8]) -> Option<Fn> {
255        let mut b = [0u8; 48];
256        if bytes.len() != 48 {
257            return None;
258        }
259        b.copy_from_slice(bytes);
260        Fn::from_bytes(&b)
261    }
262
263    #[cfg(target_arch = "x86_64")]
264    #[inline(always)]
265    fn double_fast(x: &Fp, y: &Fp, z: &Fp) -> Option<[Fp; 3]> {
266        crate::nist::p384_x86::point_double([&x.0, &y.0, &z.0])
267            .map(|[x, y, z]| [Fp(x), Fp(y), Fp(z)])
268    }
269
270    #[cfg(target_arch = "x86_64")]
271    #[inline(always)]
272    fn scan_affine(
273        entries: &[crate::nist::point::AffinePoint<P384>],
274        masks: &[u64],
275    ) -> Option<crate::nist::point::AffinePoint<P384>> {
276        Some(crate::nist::p384_x86::scan_affine(entries, masks))
277    }
278
279    #[cfg(target_arch = "x86_64")]
280    #[inline(always)]
281    fn scan_point(entries: &[crate::nist::point::Point<P384>], masks: &[u64]) -> Option<[Fp; 3]> {
282        let [x, y, z] = crate::nist::p384_x86::scan_point(entries, masks);
283        Some([Fp(x), Fp(y), Fp(z)])
284    }
285
286    #[cfg(target_arch = "x86_64")]
287    #[inline(always)]
288    fn add_fast(p: [&Fp; 3], q: [&Fp; 3]) -> Option<([Fp; 3], Fp, Fp)> {
289        crate::nist::p384_x86::point_add([&p[0].0, &p[1].0, &p[2].0], [&q[0].0, &q[1].0, &q[2].0])
290            .map(|([x, y, z], h, r)| ([Fp(x), Fp(y), Fp(z)], Fp(h), Fp(r)))
291    }
292
293    #[cfg(target_arch = "x86_64")]
294    #[inline(always)]
295    fn add_affine_fast(p: [&Fp; 3], q: [&Fp; 2]) -> Option<([Fp; 3], Fp, Fp)> {
296        crate::nist::p384_x86::point_add_affine([&p[0].0, &p[1].0, &p[2].0], [&q[0].0, &q[1].0])
297            .map(|([x, y, z], h, r)| ([Fp(x), Fp(y), Fp(z)], Fp(h), Fp(r)))
298    }
299
300    fn scalar_reduce_slice(bytes: &[u8]) -> Fn {
301        let mut b = [0u8; 48];
302        let n = core::cmp::min(48, bytes.len());
303        // Take the leftmost bytes, which is what bits2int does when the input
304        // is at least as wide as the group order.
305        b[48 - n..].copy_from_slice(&bytes[..n]);
306        Fn::from_bytes_reduced(&b)
307    }
308}
309
310impl ecdsa::EcdsaCurve for P384 {
311    type Digest = ic_hash::Sha384;
312    type Hmac = ic_mac::HmacSha384;
313}
314
315/// ECDSA over P-384 with SHA-384.
316pub struct EcdsaP384Sha384;
317
318impl Algorithm for EcdsaP384Sha384 {
319    const ID: &'static str = "ecdsa-p384-sha384";
320    const NAME: &'static str = "ECDSA P-384 with SHA-384";
321}
322
323impl SignatureScheme for EcdsaP384Sha384 {
324    const PRIVATE_KEY_LEN: usize = 48;
325    /// SEC1 uncompressed: `0x04 || X || Y`.
326    const PUBLIC_KEY_LEN: usize = 97;
327    /// Fixed-width `r || s`.
328    const SIGNATURE_LEN: usize = 96;
329
330    fn public_key(private_key: &[u8], out: &mut [u8]) -> Result<()> {
331        ecdsa::public_key::<P384>(private_key, out)
332    }
333
334    fn sign(private_key: &[u8], message: &[u8], signature: &mut [u8]) -> Result<()> {
335        ecdsa::sign::<P384>(private_key, message, signature)
336    }
337
338    fn verify(public_key: &[u8], message: &[u8], signature: &[u8]) -> Result<()> {
339        ecdsa::verify::<P384>(public_key, message, signature)
340    }
341}
342
343impl EcdsaP384Sha384 {
344    /// Verify a signature over a digest the caller computed, for signatures
345    /// made with a hash other than SHA-384.
346    ///
347    /// `digest` must be one of [`crate::PREHASH_LENS`] and at least 48
348    /// bytes, so that the hash is at least as strong as the curve; narrower is
349    /// refused with `InvalidLength`. Which hash produced it is the caller's to
350    /// establish: nothing here can tell.
351    pub fn verify_prehash(public_key: &[u8], digest: &[u8], signature: &[u8]) -> Result<()> {
352        ecdsa::verify_prehash::<P384>(public_key, digest, signature)
353    }
354
355    /// Compute the public key in SEC1 compressed form (49 bytes).
356    pub fn public_key_compressed(private_key: &[u8], out: &mut [u8]) -> Result<()> {
357        ecdsa::public_key_compressed::<P384>(private_key, out)
358    }
359
360    /// Rewrite a signature to its low-`s` form, if it is not already.
361    ///
362    /// ECDSA is malleable: `(r, s)` and `(r, n - s)` are both valid for the
363    /// same message, so a signature is not a unique identifier unless one form
364    /// is chosen. FIPS 186-5 and RFC 6979 accept both, and this library signs
365    /// and verifies per the standard, so normalization is offered rather than
366    /// imposed -- apply it when a signature doubles as a database key or a
367    /// transaction id.
368    pub fn normalize_s(signature: &mut [u8]) -> Result<()> {
369        ecdsa::normalize_s::<P384>(signature)
370    }
371
372    /// Whether a signature is already in low-`s` form.
373    pub fn has_low_s(signature: &[u8]) -> Result<bool> {
374        ecdsa::has_low_s::<P384>(signature)
375    }
376}
377
378impl SelfTest for EcdsaP384Sha384 {
379    fn self_test() -> Result<()> {
380        // Round-trip plus tamper rejection. The published RFC 6979 vector is
381        // asserted by the unit tests; this CAST is the startup integrity check.
382        let key = [0x2au8; 48];
383        let mut pk = [0u8; 97];
384        <Self as SignatureScheme>::public_key(&key, &mut pk)?;
385
386        let mut sig = [0u8; 96];
387        <Self as SignatureScheme>::sign(&key, b"self-test", &mut sig)?;
388        <Self as SignatureScheme>::verify(&pk, b"self-test", &sig)?;
389
390        // Signing is deterministic, so a repeat must agree exactly.
391        let mut again = [0u8; 96];
392        <Self as SignatureScheme>::sign(&key, b"self-test", &mut again)?;
393        ensure!(
394            ic_core::ct::verify(&sig, &again),
395            SelfTestFailed,
396            "ecdsa-p384-sha384"
397        );
398
399        sig[0] ^= 1;
400        ensure!(
401            <Self as SignatureScheme>::verify(&pk, b"self-test", &sig).is_err(),
402            SelfTestFailed,
403            "ecdsa-p384-sha384"
404        );
405        Ok(())
406    }
407}
408
409/// ECDH over P-384.
410pub struct EcdhP384;
411
412impl Algorithm for EcdhP384 {
413    const ID: &'static str = "ecdh-p384";
414    const NAME: &'static str = "ECDH P-384";
415}
416
417impl KeyAgreement for EcdhP384 {
418    const PRIVATE_KEY_LEN: usize = 48;
419    /// SEC1 uncompressed: `0x04 || X || Y`.
420    const PUBLIC_KEY_LEN: usize = 97;
421    const SHARED_SECRET_LEN: usize = 48;
422
423    fn public_key(private_key: &[u8], out: &mut [u8]) -> Result<()> {
424        ecdh::public_key::<P384>(private_key, out)
425    }
426
427    fn agree(private_key: &[u8], peer_public_key: &[u8], out: &mut [u8]) -> Result<()> {
428        ecdh::agree::<P384>(private_key, peer_public_key, out)
429    }
430}
431
432impl EcdhP384 {
433    /// Compute the public key in SEC1 compressed form (49 bytes).
434    pub fn public_key_compressed(private_key: &[u8], out: &mut [u8]) -> Result<()> {
435        ecdh::public_key_compressed::<P384>(private_key, out)
436    }
437}
438
439impl SelfTest for EcdhP384 {
440    fn self_test() -> Result<()> {
441        // Both sides of an exchange must agree, and the result must not be the
442        // trivial one.
443        let (a, b) = ([0x11u8; 48], [0x22u8; 48]);
444        let mut a_pk = [0u8; 97];
445        let mut b_pk = [0u8; 97];
446        <Self as KeyAgreement>::public_key(&a, &mut a_pk)?;
447        <Self as KeyAgreement>::public_key(&b, &mut b_pk)?;
448
449        let mut z1 = [0u8; 48];
450        let mut z2 = [0u8; 48];
451        <Self as KeyAgreement>::agree(&a, &b_pk, &mut z1)?;
452        <Self as KeyAgreement>::agree(&b, &a_pk, &mut z2)?;
453        ensure!(ic_core::ct::verify(&z1, &z2), SelfTestFailed, "ecdh-p384");
454        ensure!(z1 != [0u8; 48], SelfTestFailed, "ecdh-p384");
455        Ok(())
456    }
457}
458
459/// A P-384 point in Jacobian coordinates.
460pub type Point = crate::nist::point::Point<P384>;
461/// A P-384 point in affine coordinates.
462pub type AffinePoint = crate::nist::point::AffinePoint<P384>;
463
464#[cfg(test)]
465mod tests {
466    use super::*;
467    use ic_core::codec::{hex, unhex};
468
469    fn scalar(v: u64) -> Fn {
470        Fn::to_mont([v, 0, 0, 0, 0, 0])
471    }
472
473    fn fp(v: u64) -> Fp {
474        Fp::to_mont([v, 0, 0, 0, 0, 0])
475    }
476
477    // -- field ------------------------------------------------------------
478
479    #[test]
480    fn montgomery_constants_are_consistent() {
481        assert_eq!(Fp::MODULUS[0].wrapping_mul(Fp::NEG_INV), u64::MAX, "p");
482        assert_eq!(Fn::MODULUS[0].wrapping_mul(Fn::NEG_INV), u64::MAX, "n");
483    }
484
485    #[test]
486    fn small_arithmetic_matches_integers() {
487        assert_eq!(fp(2).add(&fp(3)), fp(5));
488        assert_eq!(fp(5).sub(&fp(3)), fp(2));
489        assert_eq!(fp(6).mul(&fp(7)), fp(42));
490        assert_eq!(fp(9).square(), fp(81));
491        assert_eq!(fp(5).triple(), fp(15));
492        assert_eq!(Fp::ONE.from_mont(), [1, 0, 0, 0, 0, 0]);
493    }
494
495    /// The field's inversion -- divsteps on 64-bit targets -- and its
496    /// addition chain, each against `a^(p-2)` by the generic windowed
497    /// exponentiation, which shares nothing with either but the
498    /// multiplication: on zero, one, `-1`, `-2`, powers of two across the
499    /// width, and two thousand pseudo-random elements; and against `a * a^-1
500    /// = 1` on all but zero.
501    #[test]
502    fn the_inversion_agrees_with_exponentiation() {
503        let mut exp = P;
504        exp[0] -= 2;
505        let mut values = std::vec![Fp::ZERO, Fp::ONE, Fp::ONE.neg(), Fp::ONE.double().neg()];
506        for k in [1usize, 31, 32, 63, 64, 95, 96, 127, 128, 200, 255, 256, 383] {
507            let mut x = [0u64; 6];
508            x[k / 64] = 1 << (k % 64);
509            values.push(Fp::to_mont(x));
510            values.push(Fp::to_mont(x).neg());
511        }
512        let mut state = 0x384u64;
513        for _ in 0..2000 {
514            let mut bytes = [0u8; 48];
515            for chunk in bytes.chunks_mut(8) {
516                state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
517                let mut z = state;
518                z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
519                z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
520                chunk.copy_from_slice(&(z ^ (z >> 31)).to_be_bytes());
521            }
522            values.push(Fp::from_bytes_reduced(&bytes));
523        }
524        for v in values {
525            let inv = v.invert();
526            assert_eq!(inv, v.pow(&exp), "{v:x?}");
527            assert_eq!(Fp(fp_invert_chain(v.0)), inv, "{v:x?}");
528            if v != Fp::ZERO {
529                assert_eq!(v.mul(&inv), Fp::ONE, "{v:x?}");
530            }
531        }
532    }
533
534    #[test]
535    fn inversion_is_correct() {
536        for v in [1u64, 2, 3, 19, 65537, u32::MAX as u64] {
537            assert_eq!(fp(v).mul(&fp(v).invert()), Fp::ONE, "1/{v} in Fp");
538            assert_eq!(scalar(v).mul(&scalar(v).invert()), Fn::ONE, "1/{v} in Fn");
539        }
540        assert_eq!(Fp::ZERO.invert(), Fp::ZERO);
541    }
542
543    #[test]
544    fn arithmetic_laws_hold_on_large_values() {
545        let a = P384::field_from_slice(&[0x3a; 48]).unwrap();
546        let b = P384::field_from_slice(&[0x91; 48]).unwrap();
547        let c = P384::field_from_slice(&[0xc7; 48]).unwrap();
548        assert_eq!(a.mul(&b).mul(&c), a.mul(&b.mul(&c)), "associativity");
549        assert_eq!(a.mul(&b), b.mul(&a), "commutativity");
550        assert_eq!(
551            a.mul(&b.add(&c)),
552            a.mul(&b).add(&a.mul(&c)),
553            "distributivity"
554        );
555        assert_eq!(a.add(&a.neg()), Fp::ZERO);
556    }
557
558    #[test]
559    fn byte_encoding_round_trips() {
560        let bytes = [0x7fu8; 48];
561        let a = P384::field_from_slice(&bytes).unwrap();
562        assert_eq!(a.to_bytes(), bytes);
563    }
564
565    // -- group law --------------------------------------------------------
566
567    /// Validates B, GX, GY and the curve equation together: if any of the four
568    /// constants were mistranscribed, the base point would not satisfy it.
569    #[test]
570    fn the_base_point_is_on_the_curve() {
571        let g = Point::generator().to_affine().unwrap();
572        assert!(bool::from(g.is_on_curve()));
573    }
574
575    /// Validates the group order n against the base point. Together with the
576    /// test above this pins down every curve constant.
577    #[test]
578    fn the_base_point_has_order_n() {
579        let n_minus_1 = Fn::ZERO.sub(&Fn::ONE);
580        let p = Point::generator().mul_scalar(&n_minus_1);
581        assert!(
582            bool::from(p.ct_eq(&Point::generator().neg())),
583            "[n-1]G == -G"
584        );
585        assert!(
586            bool::from(p.add(&Point::generator()).is_identity()),
587            "[n]G is the identity"
588        );
589    }
590
591    #[test]
592    fn identity_and_negation_behave() {
593        let g = Point::generator();
594        assert!(bool::from(g.add(&Point::identity()).ct_eq(&g)));
595        assert!(bool::from(Point::identity().double().is_identity()));
596        assert!(bool::from(g.add(&g.neg()).is_identity()));
597    }
598
599    #[test]
600    fn addition_handles_equal_inputs_as_a_doubling() {
601        let g = Point::generator();
602        assert!(bool::from(g.add(&g).ct_eq(&g.double())));
603    }
604
605    #[test]
606    fn scalar_multiplication_matches_repeated_addition() {
607        let g = Point::generator();
608        let mut acc = Point::identity();
609        for k in 1..=8u64 {
610            acc = acc.add(&g);
611            assert!(bool::from(acc.ct_eq(&g.mul_scalar(&scalar(k)))), "[{k}]G");
612        }
613    }
614
615    #[test]
616    fn scalar_multiplication_is_linear() {
617        let g = Point::generator();
618        let a = scalar(1_234_567);
619        let b = scalar(7_654_321);
620        assert!(bool::from(
621            g.mul_scalar(&a.add(&b))
622                .ct_eq(&g.mul_scalar(&a).add(&g.mul_scalar(&b)))
623        ));
624    }
625
626    /// The published `[2]G`, an independent check on the group law rather than
627    /// on self-consistency.
628    #[test]
629    fn two_g_matches_the_published_value() {
630        let two_g = Point::generator().double().to_affine().unwrap();
631        assert_eq!(
632            hex(two_g.x.to_bytes().as_ref()),
633            "08d999057ba3d2d969260045c55b97f089025959a6f434d651d207d19fb96e9e\
634             4fe0e86ebe0e64f85b96a9c75295df61"
635                .replace(char::is_whitespace, "")
636        );
637        assert_eq!(
638            hex(two_g.y.to_bytes().as_ref()),
639            "8e80f1fa5b1b3cedb7bfe8dffd6dba74b275d875bc6cc43e904e505f256ab425\
640             5ffd43e94d39e22d61501e700a940e80"
641                .replace(char::is_whitespace, "")
642        );
643    }
644
645    #[test]
646    fn every_multiple_stays_on_the_curve() {
647        let g = Point::generator();
648        for k in [1u64, 2, 3, 17, 255, 65537] {
649            let p = g.mul_scalar(&scalar(k)).to_affine().unwrap();
650            assert!(bool::from(p.is_on_curve()), "[{k}]G is off the curve");
651        }
652    }
653
654    #[test]
655    fn sec1_round_trips_in_both_forms() {
656        let g = Point::generator();
657        for k in [1u64, 2, 3, 4, 5, 6] {
658            let p = g.mul_scalar(&scalar(k)).to_affine().unwrap();
659            let mut unc = [0u8; 97];
660            let mut comp = [0u8; 49];
661            assert!(p.write_uncompressed(&mut unc));
662            assert!(p.write_compressed(&mut comp));
663
664            let a = AffinePoint::from_sec1(&unc).unwrap();
665            let b = AffinePoint::from_sec1(&comp).unwrap();
666            assert_eq!(a.x, p.x);
667            assert_eq!(a.y, p.y);
668            assert_eq!(b.x, p.x);
669            assert_eq!(b.y, p.y, "compressed y for [{k}]G");
670        }
671    }
672
673    #[test]
674    fn decoding_rejects_bad_encodings() {
675        let g = Point::generator().to_affine().unwrap();
676        let mut unc = [0u8; 97];
677        assert!(g.write_uncompressed(&mut unc));
678
679        assert!(AffinePoint::from_sec1(&[0u8; 97]).is_none(), "identity");
680        assert!(AffinePoint::from_sec1(&unc[..96]).is_none(), "truncated");
681        // A P-256-sized encoding must not be accepted here.
682        assert!(
683            AffinePoint::from_sec1(&[0x04u8; 65]).is_none(),
684            "wrong width"
685        );
686
687        let mut bad = unc;
688        bad[96] ^= 1;
689        assert!(AffinePoint::from_sec1(&bad).is_none(), "off curve");
690    }
691
692    // -- ECDSA ------------------------------------------------------------
693
694    /// RFC 6979 A.2.6: P-384 with SHA-384.
695    ///
696    /// The private key, public key and both message signatures are published
697    /// together, so matching them exercises the whole stack: the 6-limb field,
698    /// the group law, the scalar ring, the nonce derivation, and the signing
699    /// equation.
700    const KEY: &str = "6b9d3dad2e1b8c1c05b19875b6659f4de23c3b667bf297ba9aa47740787137d8\
701                       96d5724e4c70a825f872c9ea60d2edf5";
702
703    fn key_bytes() -> Vec<u8> {
704        unhex(&KEY.replace(char::is_whitespace, "")).unwrap()
705    }
706
707    #[test]
708    fn rfc6979_public_key() {
709        let mut pk = [0u8; 97];
710        EcdsaP384Sha384::public_key(&key_bytes(), &mut pk).unwrap();
711        assert_eq!(pk[0], 0x04);
712        assert_eq!(
713            hex(&pk[1..49]),
714            "ec3a4e415b4e19a4568618029f427fa5da9a8bc4ae92e02e06aae5286b300c64\
715             def8f0ea9055866064a254515480bc13"
716                .replace(char::is_whitespace, ""),
717            "Ux"
718        );
719        assert_eq!(
720            hex(&pk[49..]),
721            "8015d9b72d7d57244ea8ef9ac0c621896708a59367f9dfb9f54ca84b3f1c9db1\
722             288b231c3ae0d4fe7344fd2533264720"
723                .replace(char::is_whitespace, ""),
724            "Uy"
725        );
726    }
727
728    #[test]
729    fn rfc6979_sample_vector() {
730        let mut sig = [0u8; 96];
731        EcdsaP384Sha384::sign(&key_bytes(), b"sample", &mut sig).unwrap();
732        assert_eq!(
733            hex(&sig[..48]),
734            "94edbb92a5ecb8aad4736e56c691916b3f88140666ce9fa73d64c4ea95ad133c\
735             81a648152e44acf96e36dd1e80fabe46"
736                .replace(char::is_whitespace, ""),
737            "r"
738        );
739        assert_eq!(
740            hex(&sig[48..]),
741            "99ef4aeb15f178cea1fe40db2603138f130e740a19624526203b6351d0a3a94f\
742             a329c145786e679e7b82c71a38628ac8"
743                .replace(char::is_whitespace, ""),
744            "s"
745        );
746    }
747
748    #[test]
749    fn rfc6979_test_vector() {
750        let mut sig = [0u8; 96];
751        EcdsaP384Sha384::sign(&key_bytes(), b"test", &mut sig).unwrap();
752        assert_eq!(
753            hex(&sig[..48]),
754            "8203b63d3c853e8d77227fb377bcf7b7b772e97892a80f36ab775d509d7a5feb\
755             0542a7f0812998da8f1dd3ca3cf023db"
756                .replace(char::is_whitespace, ""),
757            "r"
758        );
759        assert_eq!(
760            hex(&sig[48..]),
761            "ddd0760448d42d8a43af45af836fce4de8be06b485e9b61b827c2f13173923e0\
762             6a739f040649a667bf3b828246baa5a5"
763                .replace(char::is_whitespace, ""),
764            "s"
765        );
766    }
767
768    #[test]
769    fn signing_is_deterministic_and_message_bound() {
770        let key = key_bytes();
771        let mut a = [0u8; 96];
772        let mut b = [0u8; 96];
773        EcdsaP384Sha384::sign(&key, b"same", &mut a).unwrap();
774        EcdsaP384Sha384::sign(&key, b"same", &mut b).unwrap();
775        assert_eq!(a, b);
776        EcdsaP384Sha384::sign(&key, b"other", &mut b).unwrap();
777        assert_ne!(&a[..48], &b[..48]);
778    }
779
780    #[test]
781    fn sign_and_verify_round_trip() {
782        let key = key_bytes();
783        let mut pk = [0u8; 97];
784        EcdsaP384Sha384::public_key(&key, &mut pk).unwrap();
785        for message in [&b""[..], b"short", &[0x5au8; 1000][..]] {
786            let mut sig = [0u8; 96];
787            EcdsaP384Sha384::sign(&key, message, &mut sig).unwrap();
788            EcdsaP384Sha384::verify(&pk, message, &sig).unwrap();
789        }
790    }
791
792    #[test]
793    fn verification_rejects_tampering() {
794        let key = key_bytes();
795        let mut pk = [0u8; 97];
796        EcdsaP384Sha384::public_key(&key, &mut pk).unwrap();
797        let mut sig = [0u8; 96];
798        EcdsaP384Sha384::sign(&key, b"authentic", &mut sig).unwrap();
799
800        assert!(EcdsaP384Sha384::verify(&pk, b"forged", &sig).is_err());
801        let mut bad = sig;
802        bad[0] ^= 1;
803        assert!(EcdsaP384Sha384::verify(&pk, b"authentic", &bad).is_err());
804        let mut bad = sig;
805        bad[95] ^= 1;
806        assert!(EcdsaP384Sha384::verify(&pk, b"authentic", &bad).is_err());
807
808        let mut other = [0u8; 97];
809        EcdsaP384Sha384::public_key(&[0x11u8; 48], &mut other).unwrap();
810        assert!(EcdsaP384Sha384::verify(&other, b"authentic", &sig).is_err());
811    }
812
813    #[test]
814    fn signing_rejects_invalid_private_keys() {
815        let mut sig = [0u8; 96];
816        assert!(
817            EcdsaP384Sha384::sign(&[0u8; 48], b"m", &mut sig).is_err(),
818            "zero"
819        );
820        assert!(
821            EcdsaP384Sha384::sign(&[0xffu8; 48], b"m", &mut sig).is_err(),
822            ">= n"
823        );
824        assert!(
825            EcdsaP384Sha384::sign(&[1u8; 32], b"m", &mut sig).is_err(),
826            "P-256 sized"
827        );
828    }
829
830    #[test]
831    fn malleability_and_normalization() {
832        let key = key_bytes();
833        let mut pk = [0u8; 97];
834        EcdsaP384Sha384::public_key(&key, &mut pk).unwrap();
835        let mut sig = [0u8; 96];
836        EcdsaP384Sha384::sign(&key, b"sample", &mut sig).unwrap();
837
838        let mut normalized = sig;
839        EcdsaP384Sha384::normalize_s(&mut normalized).unwrap();
840        assert!(EcdsaP384Sha384::has_low_s(&normalized).unwrap());
841        // Both forms verify: that is the malleability.
842        EcdsaP384Sha384::verify(&pk, b"sample", &normalized).unwrap();
843        EcdsaP384Sha384::verify(&pk, b"sample", &sig).unwrap();
844
845        let mut twice = normalized;
846        EcdsaP384Sha384::normalize_s(&mut twice).unwrap();
847        assert_eq!(twice, normalized, "normalization must be idempotent");
848    }
849
850    #[test]
851    fn ecdsa_self_test_passes() {
852        EcdsaP384Sha384::self_test().unwrap();
853    }
854
855    // -- ECDH -------------------------------------------------------------
856
857    #[test]
858    fn both_parties_derive_the_same_secret() {
859        let (alice, bob) = ([0x11u8; 48], [0x22u8; 48]);
860        let mut alice_pk = [0u8; 97];
861        let mut bob_pk = [0u8; 97];
862        EcdhP384::public_key(&alice, &mut alice_pk).unwrap();
863        EcdhP384::public_key(&bob, &mut bob_pk).unwrap();
864
865        let mut z1 = [0u8; 48];
866        let mut z2 = [0u8; 48];
867        EcdhP384::agree(&alice, &bob_pk, &mut z1).unwrap();
868        EcdhP384::agree(&bob, &alice_pk, &mut z2).unwrap();
869        assert_eq!(z1, z2);
870        assert_ne!(z1, [0u8; 48]);
871    }
872
873    #[test]
874    fn compressed_and_uncompressed_peers_agree() {
875        let (alice, bob) = ([0x33u8; 48], [0x44u8; 48]);
876        let mut unc = [0u8; 97];
877        let mut comp = [0u8; 49];
878        EcdhP384::public_key(&bob, &mut unc).unwrap();
879        EcdhP384::public_key_compressed(&bob, &mut comp).unwrap();
880
881        let mut z1 = [0u8; 48];
882        let mut z2 = [0u8; 48];
883        EcdhP384::agree(&alice, &unc, &mut z1).unwrap();
884        EcdhP384::agree(&alice, &comp, &mut z2).unwrap();
885        assert_eq!(z1, z2);
886    }
887
888    #[test]
889    fn ecdh_rejects_invalid_inputs() {
890        let alice = [0x11u8; 48];
891        let mut z = [0u8; 48];
892        assert!(EcdhP384::agree(&alice, &[0u8; 97], &mut z).is_err());
893        assert!(EcdhP384::agree(&alice, &[], &mut z).is_err());
894
895        let mut bob_pk = [0u8; 97];
896        EcdhP384::public_key(&[0x22u8; 48], &mut bob_pk).unwrap();
897        bob_pk[96] ^= 1;
898        assert!(
899            EcdhP384::agree(&alice, &bob_pk, &mut z).is_err(),
900            "off curve"
901        );
902    }
903
904    #[test]
905    fn ecdh_self_test_passes() {
906        EcdhP384::self_test().unwrap();
907    }
908}