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