Skip to main content

ic_ec/
p256.rs

1//! NIST P-256 (secp256r1, prime256v1).
2//!
3//! The most widely deployed approved curve. The field, group law, and schemes
4//! come from `crate::nist`; this module supplies the constants and the
5//! public API.
6
7use crate::mont_field;
8use crate::nist::arith::{sqrt_p3mod4, Field};
9use crate::nist::point::Curve;
10use crate::nist::{ecdh, ecdsa};
11use ic_core::traits::{Algorithm, KeyAgreement, SelfTest, SignatureScheme};
12use ic_core::{ensure, Result};
13
14mont_field!(
15    Fp,
16    4,
17    32,
18    [
19        0xffff_ffff_ffff_ffff,
20        0x0000_0000_ffff_ffff,
21        0x0000_0000_0000_0000,
22        0xffff_ffff_0000_0001,
23    ],
24    "The P-256 coordinate field, GF(p) with p = 2^256 - 2^224 + 2^192 + 2^96 - 1."
25);
26
27mont_field!(
28    Fn,
29    4,
30    32,
31    [
32        0xf3b9_cac2_fc63_2551,
33        0xbce6_faad_a717_9e84,
34        0xffff_ffff_ffff_ffff,
35        0xffff_ffff_0000_0000,
36    ],
37    "The P-256 scalar ring, Z/nZ where n is the order of the base point."
38);
39
40/// The P-256 curve.
41#[derive(Debug, Clone, Copy)]
42pub struct P256;
43
44// Its own generator table, with its own storage; see the macro, which
45// emits the table under `std` and the windowed multiplication without it.
46crate::nist::gentable::generator_table_for!(P256);
47
48impl Curve for P256 {
49    type Field = Fp;
50    type Scalar = Fn;
51
52    const NAME: &'static str = "P-256";
53    const FIELD_BYTES: usize = 32;
54    const SCALAR_BYTES: usize = 32;
55    const ORDER_BITS: usize = 256;
56
57    /// `b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b`
58    const B: Fp = Fp::to_mont_const([
59        0x3bce_3c3e_27d2_604b,
60        0x651d_06b0_cc53_b0f6,
61        0xb3eb_bd55_7698_86bc,
62        0x5ac6_35d8_aa3a_93e7,
63    ]);
64
65    const GX: Fp = Fp::to_mont_const([
66        0xf4a1_3945_d898_c296,
67        0x7703_7d81_2deb_33a0,
68        0xf8bc_e6e5_63a4_40f2,
69        0x6b17_d1f2_e12c_4247,
70    ]);
71
72    const GY: Fp = Fp::to_mont_const([
73        0xcbb6_4068_37bf_51f5,
74        0x2bce_3357_6b31_5ece,
75        0x8ee7_eb4a_7c0f_9e16,
76        0x4fe3_42e2_fe1a_7f9b,
77    ]);
78
79    /// `p = 3 mod 4`, so a square root is `x^((p+1)/4)`.
80    fn sqrt(x: &Fp) -> Fp {
81        // p = 3 mod 4, so the root is x^((p+1)/4). The shared helper computes
82        // that exponent rather than this file unrolling it by limb: an unrolled
83        // shift is easy to get subtly wrong and would only misbehave on inputs
84        // rare enough that a round-trip test would not find them.
85        sqrt_p3mod4(x, Fp::MODULUS, |v, e| v.pow(e))
86    }
87
88    fn field_from_slice(bytes: &[u8]) -> Option<Fp> {
89        let mut b = [0u8; 32];
90        if bytes.len() != 32 {
91            return None;
92        }
93        b.copy_from_slice(bytes);
94        Fp::from_bytes(&b)
95    }
96
97    fn scalar_from_slice(bytes: &[u8]) -> Option<Fn> {
98        let mut b = [0u8; 32];
99        if bytes.len() != 32 {
100            return None;
101        }
102        b.copy_from_slice(bytes);
103        Fn::from_bytes(&b)
104    }
105
106    fn scalar_reduce_slice(bytes: &[u8]) -> Fn {
107        let mut b = [0u8; 32];
108        let n = core::cmp::min(32, bytes.len());
109        // Take the leftmost bytes, which is what bits2int does when the input
110        // is at least as wide as the group order.
111        b[32 - n..].copy_from_slice(&bytes[..n]);
112        Fn::from_bytes_reduced(&b)
113    }
114}
115
116impl ecdsa::EcdsaCurve for P256 {
117    type Digest = ic_hash::Sha256;
118    type Hmac = ic_mac::HmacSha256;
119}
120
121/// ECDSA over P-256 with SHA-256.
122pub struct EcdsaP256Sha256;
123
124impl Algorithm for EcdsaP256Sha256 {
125    const ID: &'static str = "ecdsa-p256-sha256";
126    const NAME: &'static str = "ECDSA P-256 with SHA-256";
127}
128
129impl SignatureScheme for EcdsaP256Sha256 {
130    const PRIVATE_KEY_LEN: usize = 32;
131    /// SEC1 uncompressed: `0x04 || X || Y`.
132    const PUBLIC_KEY_LEN: usize = 65;
133    /// Fixed-width `r || s`.
134    const SIGNATURE_LEN: usize = 64;
135
136    fn public_key(private_key: &[u8], out: &mut [u8]) -> Result<()> {
137        ecdsa::public_key::<P256>(private_key, out)
138    }
139
140    fn sign(private_key: &[u8], message: &[u8], signature: &mut [u8]) -> Result<()> {
141        ecdsa::sign::<P256>(private_key, message, signature)
142    }
143
144    fn verify(public_key: &[u8], message: &[u8], signature: &[u8]) -> Result<()> {
145        ecdsa::verify::<P256>(public_key, message, signature)
146    }
147}
148
149impl EcdsaP256Sha256 {
150    /// Compute the public key in SEC1 compressed form (33 bytes).
151    pub fn public_key_compressed(private_key: &[u8], out: &mut [u8]) -> Result<()> {
152        ecdsa::public_key_compressed::<P256>(private_key, out)
153    }
154
155    /// Rewrite a signature to its low-`s` form, if it is not already.
156    ///
157    /// ECDSA is malleable: `(r, s)` and `(r, n - s)` are both valid for the
158    /// same message, so a signature is not a unique identifier unless one form
159    /// is chosen. FIPS 186-5 and RFC 6979 accept both, and this library signs
160    /// and verifies per the standard, so normalization is offered rather than
161    /// imposed -- apply it when a signature doubles as a database key or a
162    /// transaction id.
163    pub fn normalize_s(signature: &mut [u8]) -> Result<()> {
164        ecdsa::normalize_s::<P256>(signature)
165    }
166
167    /// Whether a signature is already in low-`s` form.
168    pub fn has_low_s(signature: &[u8]) -> Result<bool> {
169        ecdsa::has_low_s::<P256>(signature)
170    }
171}
172
173impl SelfTest for EcdsaP256Sha256 {
174    fn self_test() -> Result<()> {
175        // RFC 6979 A.2.5: P-256, SHA-256, message "sample".
176        let mut key = [0u8; 32];
177        ic_core::codec::hex_decode(
178            b"c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721",
179            &mut key,
180        )?;
181        let mut want = [0u8; 64];
182        ic_core::codec::hex_decode(
183            b"efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716f7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8",
184            &mut want,
185        )?;
186
187        let mut sig = [0u8; 64];
188        <Self as SignatureScheme>::sign(&key, b"sample", &mut sig)?;
189        ensure!(
190            ic_core::ct::verify(&want, &sig),
191            SelfTestFailed,
192            "ecdsa-p256-sha256"
193        );
194
195        let mut pk = [0u8; 65];
196        <Self as SignatureScheme>::public_key(&key, &mut pk)?;
197        <Self as SignatureScheme>::verify(&pk, b"sample", &sig)?;
198
199        // A flipped bit must be rejected.
200        sig[0] ^= 1;
201        ensure!(
202            <Self as SignatureScheme>::verify(&pk, b"sample", &sig).is_err(),
203            SelfTestFailed,
204            "ecdsa-p256-sha256"
205        );
206        Ok(())
207    }
208}
209
210/// ECDH over P-256.
211pub struct EcdhP256;
212
213impl Algorithm for EcdhP256 {
214    const ID: &'static str = "ecdh-p256";
215    const NAME: &'static str = "ECDH P-256";
216}
217
218impl KeyAgreement for EcdhP256 {
219    const PRIVATE_KEY_LEN: usize = 32;
220    /// SEC1 uncompressed: `0x04 || X || Y`.
221    const PUBLIC_KEY_LEN: usize = 65;
222    const SHARED_SECRET_LEN: usize = 32;
223
224    fn public_key(private_key: &[u8], out: &mut [u8]) -> Result<()> {
225        ecdh::public_key::<P256>(private_key, out)
226    }
227
228    fn agree(private_key: &[u8], peer_public_key: &[u8], out: &mut [u8]) -> Result<()> {
229        ecdh::agree::<P256>(private_key, peer_public_key, out)
230    }
231}
232
233impl EcdhP256 {
234    /// Compute the public key in SEC1 compressed form (33 bytes).
235    ///
236    /// Interoperates with TLS, COSE, and JOSE, which all prefer compressed
237    /// points. [`KeyAgreement::agree`] accepts either form.
238    pub fn public_key_compressed(private_key: &[u8], out: &mut [u8]) -> Result<()> {
239        ecdh::public_key_compressed::<P256>(private_key, out)
240    }
241}
242
243impl SelfTest for EcdhP256 {
244    fn self_test() -> Result<()> {
245        // NIST CAVP ECC CDH, P-256, the first published key-agreement case.
246        let mut d = [0u8; 32];
247        ic_core::codec::hex_decode(
248            b"7d7dc5f71eb29ddaf80d6214632eeae03d9058af1fb6d22ed80badb62bc1a534",
249            &mut d,
250        )?;
251        let mut peer = [0u8; 65];
252        peer[0] = 0x04;
253        ic_core::codec::hex_decode(
254            b"700c48f77f56584c5cc632ca65640db91b6bacce3a4df6b42ce7cc838833d287",
255            &mut peer[1..33],
256        )?;
257        ic_core::codec::hex_decode(
258            b"db71e509e3fd9b060ddb20ba5c51dcc5948d46fbf640dfe0441782cab85fa4ac",
259            &mut peer[33..],
260        )?;
261        let mut want = [0u8; 32];
262        ic_core::codec::hex_decode(
263            b"46fc62106420ff012e54a434fbdd2d25ccc5852060561e68040dd7778997bd7b",
264            &mut want,
265        )?;
266
267        let mut got = [0u8; 32];
268        <Self as KeyAgreement>::agree(&d, &peer, &mut got)?;
269        ensure!(
270            ic_core::ct::verify(&want, &got),
271            SelfTestFailed,
272            "ecdh-p256"
273        );
274        Ok(())
275    }
276}
277
278/// A P-256 point in Jacobian coordinates.
279pub type Point = crate::nist::point::Point<P256>;
280/// A P-256 point in affine coordinates.
281pub type AffinePoint = crate::nist::point::AffinePoint<P256>;
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286    use ic_core::codec::{hex, unhex};
287
288    fn scalar(v: u64) -> Fn {
289        Fn::to_mont([v, 0, 0, 0])
290    }
291
292    fn fp(v: u64) -> Fp {
293        Fp::to_mont([v, 0, 0, 0])
294    }
295
296    // -- field ------------------------------------------------------------
297
298    #[test]
299    fn montgomery_constants_are_consistent() {
300        assert_eq!(Fp::MODULUS[0].wrapping_mul(Fp::NEG_INV), u64::MAX, "p");
301        assert_eq!(Fn::MODULUS[0].wrapping_mul(Fn::NEG_INV), u64::MAX, "n");
302    }
303
304    #[test]
305    fn small_arithmetic_matches_integers() {
306        assert_eq!(fp(2).add(&fp(3)), fp(5));
307        assert_eq!(fp(5).sub(&fp(3)), fp(2));
308        assert_eq!(fp(6).mul(&fp(7)), fp(42));
309        assert_eq!(fp(9).square(), fp(81));
310        assert_eq!(fp(5).double(), fp(10));
311        assert_eq!(fp(5).triple(), fp(15));
312        assert_eq!(Fp::ONE.from_mont(), [1, 0, 0, 0]);
313    }
314
315    #[test]
316    fn inversion_is_correct() {
317        for v in [1u64, 2, 3, 19, 65537, u32::MAX as u64] {
318            assert_eq!(fp(v).mul(&fp(v).invert()), Fp::ONE, "1/{v} in Fp");
319            assert_eq!(scalar(v).mul(&scalar(v).invert()), Fn::ONE, "1/{v} in Fn");
320        }
321        assert_eq!(Fp::ZERO.invert(), Fp::ZERO);
322    }
323
324    #[test]
325    fn arithmetic_laws_hold_on_large_values() {
326        let a = P256::field_from_slice(&[0x3a; 32]).unwrap();
327        let b = P256::field_from_slice(&[0x91; 32]).unwrap();
328        let c = P256::field_from_slice(&[0xc7; 32]).unwrap();
329        assert_eq!(a.mul(&b).mul(&c), a.mul(&b.mul(&c)), "associativity");
330        assert_eq!(a.mul(&b), b.mul(&a), "commutativity");
331        assert_eq!(
332            a.mul(&b.add(&c)),
333            a.mul(&b).add(&a.mul(&c)),
334            "distributivity"
335        );
336        assert_eq!(a.add(&a.neg()), Fp::ZERO);
337    }
338
339    #[test]
340    fn byte_encoding_round_trips_and_rejects_non_canonical() {
341        let bytes = [0x7fu8; 32];
342        let a = P256::field_from_slice(&bytes).unwrap();
343        assert_eq!(a.to_bytes(), bytes);
344
345        // p itself must be refused but reduce to zero.
346        let mut p_bytes = [0u8; 32];
347        for i in 0..4 {
348            let hi = 32 - i * 8;
349            p_bytes[hi - 8..hi].copy_from_slice(&Fp::MODULUS[i].to_be_bytes());
350        }
351        assert!(P256::field_from_slice(&p_bytes).is_none());
352    }
353
354    // -- group law --------------------------------------------------------
355
356    /// Validates B, GX, GY and the curve equation together: if any of the four
357    /// constants were mistranscribed, the base point would not satisfy it.
358    #[test]
359    fn the_base_point_is_on_the_curve() {
360        let g = Point::generator().to_affine().unwrap();
361        assert!(bool::from(g.is_on_curve()));
362    }
363
364    /// Validates the group order n against the base point.
365    #[test]
366    fn the_base_point_has_order_n() {
367        let n_minus_1 = Fn::ZERO.sub(&Fn::ONE);
368        let p = Point::generator().mul_scalar(&n_minus_1);
369        assert!(
370            bool::from(p.ct_eq(&Point::generator().neg())),
371            "[n-1]G == -G"
372        );
373        assert!(
374            bool::from(p.add(&Point::generator()).is_identity()),
375            "[n]G is the identity"
376        );
377    }
378
379    #[test]
380    fn identity_and_negation_behave() {
381        let g = Point::generator();
382        assert!(bool::from(g.add(&Point::identity()).ct_eq(&g)));
383        assert!(bool::from(Point::identity().add(&g).ct_eq(&g)));
384        assert!(bool::from(Point::identity().double().is_identity()));
385        assert!(bool::from(g.add(&g.neg()).is_identity()));
386        assert!(Point::identity().to_affine().is_none());
387    }
388
389    /// The exceptional case a naive Jacobian addition gets wrong.
390    #[test]
391    fn addition_handles_equal_inputs_as_a_doubling() {
392        let g = Point::generator();
393        assert!(bool::from(g.add(&g).ct_eq(&g.double())));
394        let p = g.mul_scalar(&scalar(5));
395        assert!(bool::from(p.add(&p).ct_eq(&p.double())));
396    }
397
398    /// The variable-time path must agree with the constant-time one.
399    ///
400    /// The RFC 6979 vectors reach it with a couple of scalars, which says
401    /// little about a recoding whose digit pattern differs for every scalar.
402    /// The values here stress it: zero, one, a scalar that carries at every
403    /// position, alternating bits, and the top of the byte range -- which is
404    /// above the group order and so exercises the carry the extra limb exists
405    /// for.
406    #[test]
407    fn the_vartime_multiplication_agrees_with_the_ladder() {
408        let g = Point::generator();
409
410        let mut checked = 0;
411        for raw in [
412            [0u8; 32],
413            {
414                let mut v = [0u8; 32];
415                v[31] = 1;
416                v
417            },
418            [0xffu8; 32],
419            [0x55u8; 32],
420            [0xaau8; 32],
421            [0x9du8; 32],
422        ] {
423            let k = Fn::from_bytes_reduced(&raw);
424            assert!(
425                bool::from(g.mul_scalar_vartime(&k).ct_eq(&g.mul_scalar(&k))),
426                "vartime and ladder differ for {raw:02x?}"
427            );
428            checked += 1;
429        }
430        assert_eq!(checked, 6, "the comparison did not run");
431    }
432
433    #[test]
434    fn scalar_multiplication_matches_repeated_addition() {
435        let g = Point::generator();
436        let mut acc = Point::identity();
437        for k in 1..=10u64 {
438            acc = acc.add(&g);
439            assert!(bool::from(acc.ct_eq(&g.mul_scalar(&scalar(k)))), "[{k}]G");
440        }
441    }
442
443    #[test]
444    fn scalar_multiplication_is_linear() {
445        let g = Point::generator();
446        let a = scalar(1_234_567);
447        let b = scalar(7_654_321);
448        assert!(bool::from(
449            g.mul_scalar(&a.add(&b))
450                .ct_eq(&g.mul_scalar(&a).add(&g.mul_scalar(&b)))
451        ));
452        assert!(bool::from(
453            g.mul_scalar(&a)
454                .mul_scalar(&b)
455                .ct_eq(&g.mul_scalar(&a.mul(&b)))
456        ));
457    }
458
459    /// The published `[2]G`, an independent check on the group law rather than
460    /// on self-consistency.
461    #[test]
462    fn two_g_matches_the_published_value() {
463        let two_g = Point::generator().double().to_affine().unwrap();
464        assert_eq!(
465            hex(two_g.x.to_bytes().as_ref()),
466            "7cf27b188d034f7e8a52380304b51ac3c08969e277f21b35a60b48fc47669978"
467        );
468        assert_eq!(
469            hex(two_g.y.to_bytes().as_ref()),
470            "07775510db8ed040293d9ac69f7430dbba7dade63ce982299e04b79d227873d1"
471        );
472    }
473
474    #[test]
475    fn sec1_round_trips_in_both_forms() {
476        let g = Point::generator();
477        for k in [1u64, 2, 3, 4, 5, 6, 7, 8] {
478            let p = g.mul_scalar(&scalar(k)).to_affine().unwrap();
479            let mut unc = [0u8; 65];
480            let mut comp = [0u8; 33];
481            assert!(p.write_uncompressed(&mut unc));
482            assert!(p.write_compressed(&mut comp));
483            assert_eq!(unc[0], 0x04);
484            assert!(comp[0] == 0x02 || comp[0] == 0x03);
485
486            let a = AffinePoint::from_sec1(&unc).unwrap();
487            let b = AffinePoint::from_sec1(&comp).unwrap();
488            assert_eq!(a.x, p.x);
489            assert_eq!(a.y, p.y);
490            assert_eq!(b.x, p.x);
491            assert_eq!(b.y, p.y, "compressed y for [{k}]G");
492        }
493    }
494
495    #[test]
496    fn decoding_rejects_bad_encodings() {
497        let g = Point::generator().to_affine().unwrap();
498        let mut unc = [0u8; 65];
499        assert!(g.write_uncompressed(&mut unc));
500
501        assert!(AffinePoint::from_sec1(&[]).is_none());
502        assert!(AffinePoint::from_sec1(&[0u8; 65]).is_none(), "identity");
503        assert!(AffinePoint::from_sec1(&unc[..64]).is_none(), "truncated");
504
505        let mut bad = unc;
506        bad[0] = 0x05;
507        assert!(AffinePoint::from_sec1(&bad).is_none(), "bad tag");
508
509        let mut bad = unc;
510        bad[64] ^= 1;
511        assert!(AffinePoint::from_sec1(&bad).is_none(), "off curve");
512    }
513
514    // -- ECDSA ------------------------------------------------------------
515
516    const KEY: &str = "c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721";
517
518    /// RFC 6979 A.2.5, message "sample". Matching this exercises the field, the
519    /// group law, the scalar ring, the nonce derivation, and the signing
520    /// equation in one shot.
521    #[test]
522    fn rfc6979_sample_vector() {
523        let key = unhex(KEY).unwrap();
524        let mut sig = [0u8; 64];
525        EcdsaP256Sha256::sign(&key, b"sample", &mut sig).unwrap();
526        assert_eq!(
527            hex(&sig[..32]),
528            "efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716",
529            "r"
530        );
531        assert_eq!(
532            hex(&sig[32..]),
533            "f7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8",
534            "s"
535        );
536    }
537
538    /// RFC 6979 A.2.5, message "test".
539    #[test]
540    fn rfc6979_test_vector() {
541        let key = unhex(KEY).unwrap();
542        let mut sig = [0u8; 64];
543        EcdsaP256Sha256::sign(&key, b"test", &mut sig).unwrap();
544        assert_eq!(
545            hex(&sig[..32]),
546            "f1abb023518351cd71d881567b1ea663ed3efcf6c5132b354f28d3b0b7d38367",
547            "r"
548        );
549        assert_eq!(
550            hex(&sig[32..]),
551            "019f4113742a2b14bd25926b49c649155f267e60d3814b4c0cc84250e46f0083",
552            "s"
553        );
554    }
555
556    #[test]
557    fn rfc6979_public_key() {
558        let key = unhex(KEY).unwrap();
559        let mut pk = [0u8; 65];
560        EcdsaP256Sha256::public_key(&key, &mut pk).unwrap();
561        assert_eq!(
562            hex(&pk[1..33]),
563            "60fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6",
564            "Ux"
565        );
566        assert_eq!(
567            hex(&pk[33..]),
568            "7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299",
569            "Uy"
570        );
571    }
572
573    #[test]
574    fn signing_is_deterministic_and_message_bound() {
575        let key = unhex(KEY).unwrap();
576        let mut a = [0u8; 64];
577        let mut b = [0u8; 64];
578        EcdsaP256Sha256::sign(&key, b"same", &mut a).unwrap();
579        EcdsaP256Sha256::sign(&key, b"same", &mut b).unwrap();
580        assert_eq!(a, b, "RFC 6979 signing must not depend on an RNG");
581
582        EcdsaP256Sha256::sign(&key, b"other", &mut b).unwrap();
583        assert_ne!(&a[..32], &b[..32], "r must differ between messages");
584    }
585
586    #[test]
587    fn sign_and_verify_round_trip() {
588        let key = unhex(KEY).unwrap();
589        let mut pk = [0u8; 65];
590        EcdsaP256Sha256::public_key(&key, &mut pk).unwrap();
591        for message in [&b""[..], b"short", &[0x5au8; 1000][..]] {
592            let mut sig = [0u8; 64];
593            EcdsaP256Sha256::sign(&key, message, &mut sig).unwrap();
594            EcdsaP256Sha256::verify(&pk, message, &sig).unwrap();
595        }
596    }
597
598    #[test]
599    fn verification_rejects_tampering() {
600        let key = unhex(KEY).unwrap();
601        let mut pk = [0u8; 65];
602        EcdsaP256Sha256::public_key(&key, &mut pk).unwrap();
603        let mut sig = [0u8; 64];
604        EcdsaP256Sha256::sign(&key, b"authentic", &mut sig).unwrap();
605
606        assert!(EcdsaP256Sha256::verify(&pk, b"forged", &sig).is_err());
607        let mut bad = sig;
608        bad[0] ^= 1;
609        assert!(EcdsaP256Sha256::verify(&pk, b"authentic", &bad).is_err());
610        let mut bad = sig;
611        bad[63] ^= 1;
612        assert!(EcdsaP256Sha256::verify(&pk, b"authentic", &bad).is_err());
613
614        let mut other = [0u8; 65];
615        EcdsaP256Sha256::public_key(&[0x11u8; 32], &mut other).unwrap();
616        assert!(EcdsaP256Sha256::verify(&other, b"authentic", &sig).is_err());
617    }
618
619    #[test]
620    fn verification_rejects_degenerate_signatures() {
621        let key = unhex(KEY).unwrap();
622        let mut pk = [0u8; 65];
623        EcdsaP256Sha256::public_key(&key, &mut pk).unwrap();
624
625        let mut zero_r = [0u8; 64];
626        zero_r[63] = 1;
627        assert!(EcdsaP256Sha256::verify(&pk, b"m", &zero_r).is_err());
628
629        let mut zero_s = [0u8; 64];
630        zero_s[31] = 1;
631        assert!(EcdsaP256Sha256::verify(&pk, b"m", &zero_s).is_err());
632
633        let n_bytes =
634            unhex("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551").unwrap();
635        let mut at_n = [0u8; 64];
636        at_n[..32].copy_from_slice(&n_bytes);
637        at_n[32..].copy_from_slice(&n_bytes);
638        assert!(EcdsaP256Sha256::verify(&pk, b"m", &at_n).is_err());
639    }
640
641    #[test]
642    fn signing_rejects_invalid_private_keys() {
643        let mut sig = [0u8; 64];
644        assert!(
645            EcdsaP256Sha256::sign(&[0u8; 32], b"m", &mut sig).is_err(),
646            "zero"
647        );
648        assert!(
649            EcdsaP256Sha256::sign(&[0xffu8; 32], b"m", &mut sig).is_err(),
650            ">= n"
651        );
652        assert!(
653            EcdsaP256Sha256::sign(&[1u8; 31], b"m", &mut sig).is_err(),
654            "short"
655        );
656    }
657
658    /// Both `(r, s)` and `(r, n - s)` verify; normalization picks one.
659    #[test]
660    fn malleability_and_normalization() {
661        let key = unhex(KEY).unwrap();
662        let mut pk = [0u8; 65];
663        EcdsaP256Sha256::public_key(&key, &mut pk).unwrap();
664        let mut sig = [0u8; 64];
665        EcdsaP256Sha256::sign(&key, b"sample", &mut sig).unwrap();
666        assert!(
667            !EcdsaP256Sha256::has_low_s(&sig).unwrap(),
668            "RFC 6979 s is high here"
669        );
670
671        let mut flipped = sig;
672        EcdsaP256Sha256::normalize_s(&mut flipped).unwrap();
673        assert_ne!(flipped, sig);
674        EcdsaP256Sha256::verify(&pk, b"sample", &flipped).unwrap();
675        assert!(EcdsaP256Sha256::has_low_s(&flipped).unwrap());
676
677        let mut twice = flipped;
678        EcdsaP256Sha256::normalize_s(&mut twice).unwrap();
679        assert_eq!(twice, flipped, "normalization must be idempotent");
680    }
681
682    #[test]
683    fn ecdsa_self_test_passes() {
684        EcdsaP256Sha256::self_test().unwrap();
685    }
686
687    // -- ECDH -------------------------------------------------------------
688
689    /// NIST CAVP ECC CDH, first published case.
690    #[test]
691    fn cavp_ecc_cdh_vector() {
692        let d = unhex("7d7dc5f71eb29ddaf80d6214632eeae03d9058af1fb6d22ed80badb62bc1a534").unwrap();
693        let mut peer = vec![0x04u8];
694        peer.extend_from_slice(
695            &unhex("700c48f77f56584c5cc632ca65640db91b6bacce3a4df6b42ce7cc838833d287").unwrap(),
696        );
697        peer.extend_from_slice(
698            &unhex("db71e509e3fd9b060ddb20ba5c51dcc5948d46fbf640dfe0441782cab85fa4ac").unwrap(),
699        );
700        let mut z = [0u8; 32];
701        EcdhP256::agree(&d, &peer, &mut z).unwrap();
702        assert_eq!(
703            hex(&z),
704            "46fc62106420ff012e54a434fbdd2d25ccc5852060561e68040dd7778997bd7b"
705        );
706    }
707
708    #[test]
709    fn both_parties_derive_the_same_secret() {
710        let (alice, bob) = ([0x11u8; 32], [0x22u8; 32]);
711        let mut alice_pk = [0u8; 65];
712        let mut bob_pk = [0u8; 65];
713        EcdhP256::public_key(&alice, &mut alice_pk).unwrap();
714        EcdhP256::public_key(&bob, &mut bob_pk).unwrap();
715
716        let mut z1 = [0u8; 32];
717        let mut z2 = [0u8; 32];
718        EcdhP256::agree(&alice, &bob_pk, &mut z1).unwrap();
719        EcdhP256::agree(&bob, &alice_pk, &mut z2).unwrap();
720        assert_eq!(z1, z2);
721        assert_ne!(z1, [0u8; 32]);
722    }
723
724    #[test]
725    fn compressed_and_uncompressed_peers_agree() {
726        let (alice, bob) = ([0x33u8; 32], [0x44u8; 32]);
727        let mut unc = [0u8; 65];
728        let mut comp = [0u8; 33];
729        EcdhP256::public_key(&bob, &mut unc).unwrap();
730        EcdhP256::public_key_compressed(&bob, &mut comp).unwrap();
731
732        let mut z1 = [0u8; 32];
733        let mut z2 = [0u8; 32];
734        EcdhP256::agree(&alice, &unc, &mut z1).unwrap();
735        EcdhP256::agree(&alice, &comp, &mut z2).unwrap();
736        assert_eq!(z1, z2, "the peer key encoding must not matter");
737    }
738
739    #[test]
740    fn ecdh_rejects_invalid_inputs() {
741        let alice = [0x11u8; 32];
742        let mut z = [0u8; 32];
743        assert!(EcdhP256::agree(&alice, &[0u8; 65], &mut z).is_err());
744        assert!(EcdhP256::agree(&alice, &[], &mut z).is_err());
745
746        let mut bob_pk = [0u8; 65];
747        EcdhP256::public_key(&[0x22u8; 32], &mut bob_pk).unwrap();
748        bob_pk[64] ^= 1;
749        assert!(
750            EcdhP256::agree(&alice, &bob_pk, &mut z).is_err(),
751            "off curve"
752        );
753
754        let mut pk = [0u8; 65];
755        assert!(EcdhP256::public_key(&[0u8; 32], &mut pk).is_err());
756        assert!(EcdhP256::public_key(&[0xffu8; 32], &mut pk).is_err());
757    }
758
759    #[test]
760    fn ecdh_self_test_passes() {
761        EcdhP256::self_test().unwrap();
762    }
763}