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
19mont_field!(
20    Fp,
21    6,
22    48,
23    [
24        0x0000_0000_ffff_ffff,
25        0xffff_ffff_0000_0000,
26        0xffff_ffff_ffff_fffe,
27        0xffff_ffff_ffff_ffff,
28        0xffff_ffff_ffff_ffff,
29        0xffff_ffff_ffff_ffff,
30    ],
31    "The P-384 coordinate field, GF(p) with p = 2^384 - 2^128 - 2^96 + 2^32 - 1."
32);
33
34mont_field!(
35    Fn,
36    6,
37    48,
38    [
39        0xecec_196a_ccc5_2973,
40        0x581a_0db2_48b0_a77a,
41        0xc763_4d81_f437_2ddf,
42        0xffff_ffff_ffff_ffff,
43        0xffff_ffff_ffff_ffff,
44        0xffff_ffff_ffff_ffff,
45    ],
46    "The P-384 scalar ring, Z/nZ where n is the order of the base point."
47);
48
49/// The P-384 curve.
50#[derive(Debug, Clone, Copy)]
51pub struct P384;
52
53// Its own generator table, with its own storage; see the macro, which
54// emits the table under `std` and the ladder without it.
55crate::generator_table_for!(P384);
56
57impl Curve for P384 {
58    type Field = Fp;
59    type Scalar = Fn;
60
61    const NAME: &'static str = "P-384";
62    const FIELD_BYTES: usize = 48;
63    const SCALAR_BYTES: usize = 48;
64    const ORDER_BITS: usize = 384;
65
66    /// `b = 0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875a`
67    ///     `c656398d8a2ed19d2a85c8edd3ec2aef`
68    const B: Fp = Fp::to_mont([
69        0x2a85_c8ed_d3ec_2aef,
70        0xc656_398d_8a2e_d19d,
71        0x0314_088f_5013_875a,
72        0x181d_9c6e_fe81_4112,
73        0x988e_056b_e3f8_2d19,
74        0xb331_2fa7_e23e_e7e4,
75    ]);
76
77    const GX: Fp = Fp::to_mont([
78        0x3a54_5e38_7276_0ab7,
79        0x5502_f25d_bf55_296c,
80        0x59f7_41e0_8254_2a38,
81        0x6e1d_3b62_8ba7_9b98,
82        0x8eb1_c71e_f320_ad74,
83        0xaa87_ca22_be8b_0537,
84    ]);
85
86    const GY: Fp = Fp::to_mont([
87        0x7a43_1d7c_90ea_0e5f,
88        0x0a60_b1ce_1d7e_819d,
89        0xe9da_3113_b5f0_b8c0,
90        0xf8f4_1dbd_289a_147c,
91        0x5d9e_98bf_9292_dc29,
92        0x3617_de4a_9626_2c6f,
93    ]);
94
95    /// `p = 3 mod 4`, so a square root is `x^((p+1)/4)`.
96    fn sqrt(x: &Fp) -> Fp {
97        sqrt_p3mod4(x, Fp::MODULUS, |v, e| v.pow(e))
98    }
99
100    fn field_from_slice(bytes: &[u8]) -> Option<Fp> {
101        let mut b = [0u8; 48];
102        if bytes.len() != 48 {
103            return None;
104        }
105        b.copy_from_slice(bytes);
106        Fp::from_bytes(&b)
107    }
108
109    fn scalar_from_slice(bytes: &[u8]) -> Option<Fn> {
110        let mut b = [0u8; 48];
111        if bytes.len() != 48 {
112            return None;
113        }
114        b.copy_from_slice(bytes);
115        Fn::from_bytes(&b)
116    }
117
118    fn scalar_reduce_slice(bytes: &[u8]) -> Fn {
119        let mut b = [0u8; 48];
120        let n = core::cmp::min(48, bytes.len());
121        // Take the leftmost bytes, which is what bits2int does when the input
122        // is at least as wide as the group order.
123        b[48 - n..].copy_from_slice(&bytes[..n]);
124        Fn::from_bytes_reduced(&b)
125    }
126}
127
128impl ecdsa::EcdsaCurve for P384 {
129    type Digest = ic_hash::Sha384;
130    type Hmac = ic_mac::HmacSha384;
131    const SIGNATURE_ID: &'static str = "ecdsa-p384-sha384";
132}
133
134/// ECDSA over P-384 with SHA-384.
135pub struct EcdsaP384Sha384;
136
137impl Algorithm for EcdsaP384Sha384 {
138    const ID: &'static str = "ecdsa-p384-sha384";
139    const NAME: &'static str = "ECDSA P-384 with SHA-384";
140}
141
142impl SignatureScheme for EcdsaP384Sha384 {
143    const PRIVATE_KEY_LEN: usize = 48;
144    /// SEC1 uncompressed: `0x04 || X || Y`.
145    const PUBLIC_KEY_LEN: usize = 97;
146    /// Fixed-width `r || s`.
147    const SIGNATURE_LEN: usize = 96;
148
149    fn public_key(private_key: &[u8], out: &mut [u8]) -> Result<()> {
150        ecdsa::public_key::<P384>(private_key, out)
151    }
152
153    fn sign(private_key: &[u8], message: &[u8], signature: &mut [u8]) -> Result<()> {
154        ecdsa::sign::<P384>(private_key, message, signature)
155    }
156
157    fn verify(public_key: &[u8], message: &[u8], signature: &[u8]) -> Result<()> {
158        ecdsa::verify::<P384>(public_key, message, signature)
159    }
160}
161
162impl EcdsaP384Sha384 {
163    /// Compute the public key in SEC1 compressed form (49 bytes).
164    pub fn public_key_compressed(private_key: &[u8], out: &mut [u8]) -> Result<()> {
165        ecdsa::public_key_compressed::<P384>(private_key, out)
166    }
167
168    /// Rewrite a signature to its low-`s` form. See [`ecdsa::normalize_s`].
169    pub fn normalize_s(signature: &mut [u8]) -> Result<()> {
170        ecdsa::normalize_s::<P384>(signature)
171    }
172
173    /// Whether a signature is already in low-`s` form.
174    pub fn has_low_s(signature: &[u8]) -> Result<bool> {
175        ecdsa::has_low_s::<P384>(signature)
176    }
177}
178
179impl SelfTest for EcdsaP384Sha384 {
180    fn self_test() -> Result<()> {
181        // Round-trip plus tamper rejection. The published RFC 6979 vector is
182        // asserted by the unit tests; this CAST is the startup integrity check.
183        let key = [0x2au8; 48];
184        let mut pk = [0u8; 97];
185        <Self as SignatureScheme>::public_key(&key, &mut pk)?;
186
187        let mut sig = [0u8; 96];
188        <Self as SignatureScheme>::sign(&key, b"self-test", &mut sig)?;
189        <Self as SignatureScheme>::verify(&pk, b"self-test", &sig)?;
190
191        // Signing is deterministic, so a repeat must agree exactly.
192        let mut again = [0u8; 96];
193        <Self as SignatureScheme>::sign(&key, b"self-test", &mut again)?;
194        ensure!(
195            ic_core::ct::verify(&sig, &again),
196            SelfTestFailed,
197            "ecdsa-p384-sha384"
198        );
199
200        sig[0] ^= 1;
201        ensure!(
202            <Self as SignatureScheme>::verify(&pk, b"self-test", &sig).is_err(),
203            SelfTestFailed,
204            "ecdsa-p384-sha384"
205        );
206        Ok(())
207    }
208}
209
210/// ECDH over P-384.
211pub struct EcdhP384;
212
213impl Algorithm for EcdhP384 {
214    const ID: &'static str = "ecdh-p384";
215    const NAME: &'static str = "ECDH P-384";
216}
217
218impl KeyAgreement for EcdhP384 {
219    const PRIVATE_KEY_LEN: usize = 48;
220    /// SEC1 uncompressed: `0x04 || X || Y`.
221    const PUBLIC_KEY_LEN: usize = 97;
222    const SHARED_SECRET_LEN: usize = 48;
223
224    fn public_key(private_key: &[u8], out: &mut [u8]) -> Result<()> {
225        ecdh::public_key::<P384>(private_key, out)
226    }
227
228    fn agree(private_key: &[u8], peer_public_key: &[u8], out: &mut [u8]) -> Result<()> {
229        ecdh::agree::<P384>(private_key, peer_public_key, out)
230    }
231}
232
233impl EcdhP384 {
234    /// Compute the public key in SEC1 compressed form (49 bytes).
235    pub fn public_key_compressed(private_key: &[u8], out: &mut [u8]) -> Result<()> {
236        ecdh::public_key_compressed::<P384>(private_key, out)
237    }
238}
239
240impl SelfTest for EcdhP384 {
241    fn self_test() -> Result<()> {
242        // Both sides of an exchange must agree, and the result must not be the
243        // trivial one.
244        let (a, b) = ([0x11u8; 48], [0x22u8; 48]);
245        let mut a_pk = [0u8; 97];
246        let mut b_pk = [0u8; 97];
247        <Self as KeyAgreement>::public_key(&a, &mut a_pk)?;
248        <Self as KeyAgreement>::public_key(&b, &mut b_pk)?;
249
250        let mut z1 = [0u8; 48];
251        let mut z2 = [0u8; 48];
252        <Self as KeyAgreement>::agree(&a, &b_pk, &mut z1)?;
253        <Self as KeyAgreement>::agree(&b, &a_pk, &mut z2)?;
254        ensure!(ic_core::ct::verify(&z1, &z2), SelfTestFailed, "ecdh-p384");
255        ensure!(z1 != [0u8; 48], SelfTestFailed, "ecdh-p384");
256        Ok(())
257    }
258}
259
260/// A P-384 point in Jacobian coordinates.
261pub type Point = crate::nist::point::Point<P384>;
262/// A P-384 point in affine coordinates.
263pub type AffinePoint = crate::nist::point::AffinePoint<P384>;
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268    use ic_core::codec::{hex, unhex};
269
270    fn scalar(v: u64) -> Fn {
271        Fn::to_mont([v, 0, 0, 0, 0, 0])
272    }
273
274    fn fp(v: u64) -> Fp {
275        Fp::to_mont([v, 0, 0, 0, 0, 0])
276    }
277
278    // -- field ------------------------------------------------------------
279
280    #[test]
281    fn montgomery_constants_are_consistent() {
282        assert_eq!(Fp::MODULUS[0].wrapping_mul(Fp::NEG_INV), u64::MAX, "p");
283        assert_eq!(Fn::MODULUS[0].wrapping_mul(Fn::NEG_INV), u64::MAX, "n");
284    }
285
286    #[test]
287    fn small_arithmetic_matches_integers() {
288        assert_eq!(fp(2).add(&fp(3)), fp(5));
289        assert_eq!(fp(5).sub(&fp(3)), fp(2));
290        assert_eq!(fp(6).mul(&fp(7)), fp(42));
291        assert_eq!(fp(9).square(), fp(81));
292        assert_eq!(fp(5).triple(), fp(15));
293        assert_eq!(Fp::ONE.from_mont(), [1, 0, 0, 0, 0, 0]);
294    }
295
296    #[test]
297    fn inversion_is_correct() {
298        for v in [1u64, 2, 3, 19, 65537, u32::MAX as u64] {
299            assert_eq!(fp(v).mul(&fp(v).invert()), Fp::ONE, "1/{v} in Fp");
300            assert_eq!(scalar(v).mul(&scalar(v).invert()), Fn::ONE, "1/{v} in Fn");
301        }
302        assert_eq!(Fp::ZERO.invert(), Fp::ZERO);
303    }
304
305    #[test]
306    fn arithmetic_laws_hold_on_large_values() {
307        let a = P384::field_from_slice(&[0x3a; 48]).unwrap();
308        let b = P384::field_from_slice(&[0x91; 48]).unwrap();
309        let c = P384::field_from_slice(&[0xc7; 48]).unwrap();
310        assert_eq!(a.mul(&b).mul(&c), a.mul(&b.mul(&c)), "associativity");
311        assert_eq!(a.mul(&b), b.mul(&a), "commutativity");
312        assert_eq!(
313            a.mul(&b.add(&c)),
314            a.mul(&b).add(&a.mul(&c)),
315            "distributivity"
316        );
317        assert_eq!(a.add(&a.neg()), Fp::ZERO);
318    }
319
320    #[test]
321    fn byte_encoding_round_trips() {
322        let bytes = [0x7fu8; 48];
323        let a = P384::field_from_slice(&bytes).unwrap();
324        assert_eq!(a.to_bytes(), bytes);
325    }
326
327    // -- group law --------------------------------------------------------
328
329    /// Validates B, GX, GY and the curve equation together: if any of the four
330    /// constants were mistranscribed, the base point would not satisfy it.
331    #[test]
332    fn the_base_point_is_on_the_curve() {
333        let g = Point::generator().to_affine().unwrap();
334        assert!(bool::from(g.is_on_curve()));
335    }
336
337    /// Validates the group order n against the base point. Together with the
338    /// test above this pins down every curve constant.
339    #[test]
340    fn the_base_point_has_order_n() {
341        let n_minus_1 = Fn::ZERO.sub(&Fn::ONE);
342        let p = Point::generator().mul_scalar(&n_minus_1);
343        assert!(
344            bool::from(p.ct_eq(&Point::generator().neg())),
345            "[n-1]G == -G"
346        );
347        assert!(
348            bool::from(p.add(&Point::generator()).is_identity()),
349            "[n]G is the identity"
350        );
351    }
352
353    #[test]
354    fn identity_and_negation_behave() {
355        let g = Point::generator();
356        assert!(bool::from(g.add(&Point::identity()).ct_eq(&g)));
357        assert!(bool::from(Point::identity().double().is_identity()));
358        assert!(bool::from(g.add(&g.neg()).is_identity()));
359    }
360
361    #[test]
362    fn addition_handles_equal_inputs_as_a_doubling() {
363        let g = Point::generator();
364        assert!(bool::from(g.add(&g).ct_eq(&g.double())));
365    }
366
367    #[test]
368    fn scalar_multiplication_matches_repeated_addition() {
369        let g = Point::generator();
370        let mut acc = Point::identity();
371        for k in 1..=8u64 {
372            acc = acc.add(&g);
373            assert!(bool::from(acc.ct_eq(&g.mul_scalar(&scalar(k)))), "[{k}]G");
374        }
375    }
376
377    #[test]
378    fn scalar_multiplication_is_linear() {
379        let g = Point::generator();
380        let a = scalar(1_234_567);
381        let b = scalar(7_654_321);
382        assert!(bool::from(
383            g.mul_scalar(&a.add(&b))
384                .ct_eq(&g.mul_scalar(&a).add(&g.mul_scalar(&b)))
385        ));
386    }
387
388    /// The published `[2]G`, an independent check on the group law rather than
389    /// on self-consistency.
390    #[test]
391    fn two_g_matches_the_published_value() {
392        let two_g = Point::generator().double().to_affine().unwrap();
393        assert_eq!(
394            hex(two_g.x.to_bytes().as_ref()),
395            "08d999057ba3d2d969260045c55b97f089025959a6f434d651d207d19fb96e9e\
396             4fe0e86ebe0e64f85b96a9c75295df61"
397                .replace(char::is_whitespace, "")
398        );
399        assert_eq!(
400            hex(two_g.y.to_bytes().as_ref()),
401            "8e80f1fa5b1b3cedb7bfe8dffd6dba74b275d875bc6cc43e904e505f256ab425\
402             5ffd43e94d39e22d61501e700a940e80"
403                .replace(char::is_whitespace, "")
404        );
405    }
406
407    #[test]
408    fn every_multiple_stays_on_the_curve() {
409        let g = Point::generator();
410        for k in [1u64, 2, 3, 17, 255, 65537] {
411            let p = g.mul_scalar(&scalar(k)).to_affine().unwrap();
412            assert!(bool::from(p.is_on_curve()), "[{k}]G is off the curve");
413        }
414    }
415
416    #[test]
417    fn sec1_round_trips_in_both_forms() {
418        let g = Point::generator();
419        for k in [1u64, 2, 3, 4, 5, 6] {
420            let p = g.mul_scalar(&scalar(k)).to_affine().unwrap();
421            let mut unc = [0u8; 97];
422            let mut comp = [0u8; 49];
423            assert!(p.write_uncompressed(&mut unc));
424            assert!(p.write_compressed(&mut comp));
425
426            let a = AffinePoint::from_sec1(&unc).unwrap();
427            let b = AffinePoint::from_sec1(&comp).unwrap();
428            assert_eq!(a.x, p.x);
429            assert_eq!(a.y, p.y);
430            assert_eq!(b.x, p.x);
431            assert_eq!(b.y, p.y, "compressed y for [{k}]G");
432        }
433    }
434
435    #[test]
436    fn decoding_rejects_bad_encodings() {
437        let g = Point::generator().to_affine().unwrap();
438        let mut unc = [0u8; 97];
439        assert!(g.write_uncompressed(&mut unc));
440
441        assert!(AffinePoint::from_sec1(&[0u8; 97]).is_none(), "identity");
442        assert!(AffinePoint::from_sec1(&unc[..96]).is_none(), "truncated");
443        // A P-256-sized encoding must not be accepted here.
444        assert!(
445            AffinePoint::from_sec1(&[0x04u8; 65]).is_none(),
446            "wrong width"
447        );
448
449        let mut bad = unc;
450        bad[96] ^= 1;
451        assert!(AffinePoint::from_sec1(&bad).is_none(), "off curve");
452    }
453
454    // -- ECDSA ------------------------------------------------------------
455
456    /// RFC 6979 A.2.6: P-384 with SHA-384.
457    ///
458    /// The private key, public key and both message signatures are published
459    /// together, so matching them exercises the whole stack: the 6-limb field,
460    /// the group law, the scalar ring, the nonce derivation, and the signing
461    /// equation.
462    const KEY: &str = "6b9d3dad2e1b8c1c05b19875b6659f4de23c3b667bf297ba9aa47740787137d8\
463                       96d5724e4c70a825f872c9ea60d2edf5";
464
465    fn key_bytes() -> Vec<u8> {
466        unhex(&KEY.replace(char::is_whitespace, "")).unwrap()
467    }
468
469    #[test]
470    fn rfc6979_public_key() {
471        let mut pk = [0u8; 97];
472        EcdsaP384Sha384::public_key(&key_bytes(), &mut pk).unwrap();
473        assert_eq!(pk[0], 0x04);
474        assert_eq!(
475            hex(&pk[1..49]),
476            "ec3a4e415b4e19a4568618029f427fa5da9a8bc4ae92e02e06aae5286b300c64\
477             def8f0ea9055866064a254515480bc13"
478                .replace(char::is_whitespace, ""),
479            "Ux"
480        );
481        assert_eq!(
482            hex(&pk[49..]),
483            "8015d9b72d7d57244ea8ef9ac0c621896708a59367f9dfb9f54ca84b3f1c9db1\
484             288b231c3ae0d4fe7344fd2533264720"
485                .replace(char::is_whitespace, ""),
486            "Uy"
487        );
488    }
489
490    #[test]
491    fn rfc6979_sample_vector() {
492        let mut sig = [0u8; 96];
493        EcdsaP384Sha384::sign(&key_bytes(), b"sample", &mut sig).unwrap();
494        assert_eq!(
495            hex(&sig[..48]),
496            "94edbb92a5ecb8aad4736e56c691916b3f88140666ce9fa73d64c4ea95ad133c\
497             81a648152e44acf96e36dd1e80fabe46"
498                .replace(char::is_whitespace, ""),
499            "r"
500        );
501        assert_eq!(
502            hex(&sig[48..]),
503            "99ef4aeb15f178cea1fe40db2603138f130e740a19624526203b6351d0a3a94f\
504             a329c145786e679e7b82c71a38628ac8"
505                .replace(char::is_whitespace, ""),
506            "s"
507        );
508    }
509
510    #[test]
511    fn rfc6979_test_vector() {
512        let mut sig = [0u8; 96];
513        EcdsaP384Sha384::sign(&key_bytes(), b"test", &mut sig).unwrap();
514        assert_eq!(
515            hex(&sig[..48]),
516            "8203b63d3c853e8d77227fb377bcf7b7b772e97892a80f36ab775d509d7a5feb\
517             0542a7f0812998da8f1dd3ca3cf023db"
518                .replace(char::is_whitespace, ""),
519            "r"
520        );
521        assert_eq!(
522            hex(&sig[48..]),
523            "ddd0760448d42d8a43af45af836fce4de8be06b485e9b61b827c2f13173923e0\
524             6a739f040649a667bf3b828246baa5a5"
525                .replace(char::is_whitespace, ""),
526            "s"
527        );
528    }
529
530    #[test]
531    fn signing_is_deterministic_and_message_bound() {
532        let key = key_bytes();
533        let mut a = [0u8; 96];
534        let mut b = [0u8; 96];
535        EcdsaP384Sha384::sign(&key, b"same", &mut a).unwrap();
536        EcdsaP384Sha384::sign(&key, b"same", &mut b).unwrap();
537        assert_eq!(a, b);
538        EcdsaP384Sha384::sign(&key, b"other", &mut b).unwrap();
539        assert_ne!(&a[..48], &b[..48]);
540    }
541
542    #[test]
543    fn sign_and_verify_round_trip() {
544        let key = key_bytes();
545        let mut pk = [0u8; 97];
546        EcdsaP384Sha384::public_key(&key, &mut pk).unwrap();
547        for message in [&b""[..], b"short", &[0x5au8; 1000][..]] {
548            let mut sig = [0u8; 96];
549            EcdsaP384Sha384::sign(&key, message, &mut sig).unwrap();
550            EcdsaP384Sha384::verify(&pk, message, &sig).unwrap();
551        }
552    }
553
554    #[test]
555    fn verification_rejects_tampering() {
556        let key = key_bytes();
557        let mut pk = [0u8; 97];
558        EcdsaP384Sha384::public_key(&key, &mut pk).unwrap();
559        let mut sig = [0u8; 96];
560        EcdsaP384Sha384::sign(&key, b"authentic", &mut sig).unwrap();
561
562        assert!(EcdsaP384Sha384::verify(&pk, b"forged", &sig).is_err());
563        let mut bad = sig;
564        bad[0] ^= 1;
565        assert!(EcdsaP384Sha384::verify(&pk, b"authentic", &bad).is_err());
566        let mut bad = sig;
567        bad[95] ^= 1;
568        assert!(EcdsaP384Sha384::verify(&pk, b"authentic", &bad).is_err());
569
570        let mut other = [0u8; 97];
571        EcdsaP384Sha384::public_key(&[0x11u8; 48], &mut other).unwrap();
572        assert!(EcdsaP384Sha384::verify(&other, b"authentic", &sig).is_err());
573    }
574
575    #[test]
576    fn signing_rejects_invalid_private_keys() {
577        let mut sig = [0u8; 96];
578        assert!(
579            EcdsaP384Sha384::sign(&[0u8; 48], b"m", &mut sig).is_err(),
580            "zero"
581        );
582        assert!(
583            EcdsaP384Sha384::sign(&[0xffu8; 48], b"m", &mut sig).is_err(),
584            ">= n"
585        );
586        assert!(
587            EcdsaP384Sha384::sign(&[1u8; 32], b"m", &mut sig).is_err(),
588            "P-256 sized"
589        );
590    }
591
592    #[test]
593    fn malleability_and_normalization() {
594        let key = key_bytes();
595        let mut pk = [0u8; 97];
596        EcdsaP384Sha384::public_key(&key, &mut pk).unwrap();
597        let mut sig = [0u8; 96];
598        EcdsaP384Sha384::sign(&key, b"sample", &mut sig).unwrap();
599
600        let mut normalized = sig;
601        EcdsaP384Sha384::normalize_s(&mut normalized).unwrap();
602        assert!(EcdsaP384Sha384::has_low_s(&normalized).unwrap());
603        // Both forms verify: that is the malleability.
604        EcdsaP384Sha384::verify(&pk, b"sample", &normalized).unwrap();
605        EcdsaP384Sha384::verify(&pk, b"sample", &sig).unwrap();
606
607        let mut twice = normalized;
608        EcdsaP384Sha384::normalize_s(&mut twice).unwrap();
609        assert_eq!(twice, normalized, "normalization must be idempotent");
610    }
611
612    #[test]
613    fn ecdsa_self_test_passes() {
614        EcdsaP384Sha384::self_test().unwrap();
615    }
616
617    // -- ECDH -------------------------------------------------------------
618
619    #[test]
620    fn both_parties_derive_the_same_secret() {
621        let (alice, bob) = ([0x11u8; 48], [0x22u8; 48]);
622        let mut alice_pk = [0u8; 97];
623        let mut bob_pk = [0u8; 97];
624        EcdhP384::public_key(&alice, &mut alice_pk).unwrap();
625        EcdhP384::public_key(&bob, &mut bob_pk).unwrap();
626
627        let mut z1 = [0u8; 48];
628        let mut z2 = [0u8; 48];
629        EcdhP384::agree(&alice, &bob_pk, &mut z1).unwrap();
630        EcdhP384::agree(&bob, &alice_pk, &mut z2).unwrap();
631        assert_eq!(z1, z2);
632        assert_ne!(z1, [0u8; 48]);
633    }
634
635    #[test]
636    fn compressed_and_uncompressed_peers_agree() {
637        let (alice, bob) = ([0x33u8; 48], [0x44u8; 48]);
638        let mut unc = [0u8; 97];
639        let mut comp = [0u8; 49];
640        EcdhP384::public_key(&bob, &mut unc).unwrap();
641        EcdhP384::public_key_compressed(&bob, &mut comp).unwrap();
642
643        let mut z1 = [0u8; 48];
644        let mut z2 = [0u8; 48];
645        EcdhP384::agree(&alice, &unc, &mut z1).unwrap();
646        EcdhP384::agree(&alice, &comp, &mut z2).unwrap();
647        assert_eq!(z1, z2);
648    }
649
650    #[test]
651    fn ecdh_rejects_invalid_inputs() {
652        let alice = [0x11u8; 48];
653        let mut z = [0u8; 48];
654        assert!(EcdhP384::agree(&alice, &[0u8; 97], &mut z).is_err());
655        assert!(EcdhP384::agree(&alice, &[], &mut z).is_err());
656
657        let mut bob_pk = [0u8; 97];
658        EcdhP384::public_key(&[0x22u8; 48], &mut bob_pk).unwrap();
659        bob_pk[96] ^= 1;
660        assert!(
661            EcdhP384::agree(&alice, &bob_pk, &mut z).is_err(),
662            "off curve"
663        );
664    }
665
666    #[test]
667    fn ecdh_self_test_passes() {
668        EcdhP384::self_test().unwrap();
669    }
670}