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    /// Where P-256's time goes, piece by piece. A measurement, not a check:
289    /// run with `cargo test --release -p ic-ec -- --ignored --nocapture
290    /// where_the_time_goes`.
291    #[test]
292    #[ignore = "timing; run manually with --release"]
293    fn where_the_time_goes() {
294        use crate::nist::arith::Field;
295        use std::hint::black_box;
296        use std::time::Instant;
297        fn ns(label: &str, iters: u32, mut f: impl FnMut()) {
298            let mut best = f64::INFINITY;
299            for _ in 0..7 {
300                let t = Instant::now();
301                for _ in 0..iters {
302                    f();
303                }
304                best = best.min(t.elapsed().as_secs_f64() * 1e9 / iters as f64);
305            }
306            std::println!("{label:32} {best:10.1} ns");
307        }
308        let a = Fp::to_mont([7, 11, 13, 17]);
309        let b = Fp::to_mont([19, 23, 29, 31]);
310        ns("fp mul", 2_000_000, || {
311            black_box(black_box(a).mul(&black_box(b)));
312        });
313        ns("fp square", 2_000_000, || {
314            black_box(black_box(a).square());
315        });
316        ns("fp add", 2_000_000, || {
317            black_box(black_box(a).add(&black_box(b)));
318        });
319        ns("fp sub", 2_000_000, || {
320            black_box(black_box(a).sub(&black_box(b)));
321        });
322        ns("fp invert", 2_000, || {
323            black_box(black_box(a).invert());
324        });
325        let g = Point::generator();
326        let p = g.double();
327        ns("point double", 200_000, || {
328            black_box(black_box(p).double());
329        });
330        ns("point add (complete)", 200_000, || {
331            black_box(black_box(p).add(&black_box(g)));
332        });
333        let k = Fn::to_mont([0x1234_5678, 0x9abc_def0, 0x1357_9bdf, 0x2468_ace0]);
334        ns("scalar invert", 2_000, || {
335            black_box(black_box(k).invert());
336        });
337        ns("mul_generator (table)", 2_000, || {
338            black_box(Point::mul_generator(&black_box(k)));
339        });
340        ns("mul_scalar (windowed)", 500, || {
341            black_box(black_box(p).mul_scalar(&black_box(k)));
342        });
343        ns("mul_scalar_vartime", 500, || {
344            black_box(black_box(p).mul_scalar_vartime(&black_box(k)));
345        });
346        ns("to_affine", 2_000, || {
347            black_box(black_box(p).to_affine());
348        });
349        let mut sig = [0u8; 64];
350        ns("ecdsa sign", 500, || {
351            EcdsaP256Sha256::sign(&[0x5a; 32], b"message", &mut sig).unwrap();
352        });
353    }
354
355    fn scalar(v: u64) -> Fn {
356        Fn::to_mont([v, 0, 0, 0])
357    }
358
359    fn fp(v: u64) -> Fp {
360        Fp::to_mont([v, 0, 0, 0])
361    }
362
363    // -- field ------------------------------------------------------------
364
365    #[test]
366    fn montgomery_constants_are_consistent() {
367        assert_eq!(Fp::MODULUS[0].wrapping_mul(Fp::NEG_INV), u64::MAX, "p");
368        assert_eq!(Fn::MODULUS[0].wrapping_mul(Fn::NEG_INV), u64::MAX, "n");
369    }
370
371    #[test]
372    fn small_arithmetic_matches_integers() {
373        assert_eq!(fp(2).add(&fp(3)), fp(5));
374        assert_eq!(fp(5).sub(&fp(3)), fp(2));
375        assert_eq!(fp(6).mul(&fp(7)), fp(42));
376        assert_eq!(fp(9).square(), fp(81));
377        assert_eq!(fp(5).double(), fp(10));
378        assert_eq!(fp(5).triple(), fp(15));
379        assert_eq!(Fp::ONE.from_mont(), [1, 0, 0, 0]);
380    }
381
382    #[test]
383    fn inversion_is_correct() {
384        for v in [1u64, 2, 3, 19, 65537, u32::MAX as u64] {
385            assert_eq!(fp(v).mul(&fp(v).invert()), Fp::ONE, "1/{v} in Fp");
386            assert_eq!(scalar(v).mul(&scalar(v).invert()), Fn::ONE, "1/{v} in Fn");
387        }
388        assert_eq!(Fp::ZERO.invert(), Fp::ZERO);
389    }
390
391    #[test]
392    fn arithmetic_laws_hold_on_large_values() {
393        let a = P256::field_from_slice(&[0x3a; 32]).unwrap();
394        let b = P256::field_from_slice(&[0x91; 32]).unwrap();
395        let c = P256::field_from_slice(&[0xc7; 32]).unwrap();
396        assert_eq!(a.mul(&b).mul(&c), a.mul(&b.mul(&c)), "associativity");
397        assert_eq!(a.mul(&b), b.mul(&a), "commutativity");
398        assert_eq!(
399            a.mul(&b.add(&c)),
400            a.mul(&b).add(&a.mul(&c)),
401            "distributivity"
402        );
403        assert_eq!(a.add(&a.neg()), Fp::ZERO);
404    }
405
406    #[test]
407    fn byte_encoding_round_trips_and_rejects_non_canonical() {
408        let bytes = [0x7fu8; 32];
409        let a = P256::field_from_slice(&bytes).unwrap();
410        assert_eq!(a.to_bytes(), bytes);
411
412        // p itself must be refused but reduce to zero.
413        let mut p_bytes = [0u8; 32];
414        for i in 0..4 {
415            let hi = 32 - i * 8;
416            p_bytes[hi - 8..hi].copy_from_slice(&Fp::MODULUS[i].to_be_bytes());
417        }
418        assert!(P256::field_from_slice(&p_bytes).is_none());
419    }
420
421    // -- group law --------------------------------------------------------
422
423    /// Validates B, GX, GY and the curve equation together: if any of the four
424    /// constants were mistranscribed, the base point would not satisfy it.
425    #[test]
426    fn the_base_point_is_on_the_curve() {
427        let g = Point::generator().to_affine().unwrap();
428        assert!(bool::from(g.is_on_curve()));
429    }
430
431    /// Validates the group order n against the base point.
432    #[test]
433    fn the_base_point_has_order_n() {
434        let n_minus_1 = Fn::ZERO.sub(&Fn::ONE);
435        let p = Point::generator().mul_scalar(&n_minus_1);
436        assert!(
437            bool::from(p.ct_eq(&Point::generator().neg())),
438            "[n-1]G == -G"
439        );
440        assert!(
441            bool::from(p.add(&Point::generator()).is_identity()),
442            "[n]G is the identity"
443        );
444    }
445
446    #[test]
447    fn identity_and_negation_behave() {
448        let g = Point::generator();
449        assert!(bool::from(g.add(&Point::identity()).ct_eq(&g)));
450        assert!(bool::from(Point::identity().add(&g).ct_eq(&g)));
451        assert!(bool::from(Point::identity().double().is_identity()));
452        assert!(bool::from(g.add(&g.neg()).is_identity()));
453        assert!(Point::identity().to_affine().is_none());
454    }
455
456    /// The exceptional case a naive Jacobian addition gets wrong.
457    #[test]
458    fn addition_handles_equal_inputs_as_a_doubling() {
459        let g = Point::generator();
460        assert!(bool::from(g.add(&g).ct_eq(&g.double())));
461        let p = g.mul_scalar(&scalar(5));
462        assert!(bool::from(p.add(&p).ct_eq(&p.double())));
463    }
464
465    /// The variable-time path must agree with the constant-time one.
466    ///
467    /// The RFC 6979 vectors reach it with a couple of scalars, which says
468    /// little about a recoding whose digit pattern differs for every scalar.
469    /// The values here stress it: zero, one, a scalar that carries at every
470    /// position, alternating bits, and the top of the byte range -- which is
471    /// above the group order and so exercises the carry the extra limb exists
472    /// for.
473    #[test]
474    fn the_vartime_multiplication_agrees_with_the_ladder() {
475        let g = Point::generator();
476
477        let mut checked = 0;
478        for raw in [
479            [0u8; 32],
480            {
481                let mut v = [0u8; 32];
482                v[31] = 1;
483                v
484            },
485            [0xffu8; 32],
486            [0x55u8; 32],
487            [0xaau8; 32],
488            [0x9du8; 32],
489        ] {
490            let k = Fn::from_bytes_reduced(&raw);
491            assert!(
492                bool::from(g.mul_scalar_vartime(&k).ct_eq(&g.mul_scalar(&k))),
493                "vartime and ladder differ for {raw:02x?}"
494            );
495            checked += 1;
496        }
497        assert_eq!(checked, 6, "the comparison did not run");
498    }
499
500    #[test]
501    fn scalar_multiplication_matches_repeated_addition() {
502        let g = Point::generator();
503        let mut acc = Point::identity();
504        for k in 1..=10u64 {
505            acc = acc.add(&g);
506            assert!(bool::from(acc.ct_eq(&g.mul_scalar(&scalar(k)))), "[{k}]G");
507        }
508    }
509
510    #[test]
511    fn scalar_multiplication_is_linear() {
512        let g = Point::generator();
513        let a = scalar(1_234_567);
514        let b = scalar(7_654_321);
515        assert!(bool::from(
516            g.mul_scalar(&a.add(&b))
517                .ct_eq(&g.mul_scalar(&a).add(&g.mul_scalar(&b)))
518        ));
519        assert!(bool::from(
520            g.mul_scalar(&a)
521                .mul_scalar(&b)
522                .ct_eq(&g.mul_scalar(&a.mul(&b)))
523        ));
524    }
525
526    /// The published `[2]G`, an independent check on the group law rather than
527    /// on self-consistency.
528    #[test]
529    fn two_g_matches_the_published_value() {
530        let two_g = Point::generator().double().to_affine().unwrap();
531        assert_eq!(
532            hex(two_g.x.to_bytes().as_ref()),
533            "7cf27b188d034f7e8a52380304b51ac3c08969e277f21b35a60b48fc47669978"
534        );
535        assert_eq!(
536            hex(two_g.y.to_bytes().as_ref()),
537            "07775510db8ed040293d9ac69f7430dbba7dade63ce982299e04b79d227873d1"
538        );
539    }
540
541    #[test]
542    fn sec1_round_trips_in_both_forms() {
543        let g = Point::generator();
544        for k in [1u64, 2, 3, 4, 5, 6, 7, 8] {
545            let p = g.mul_scalar(&scalar(k)).to_affine().unwrap();
546            let mut unc = [0u8; 65];
547            let mut comp = [0u8; 33];
548            assert!(p.write_uncompressed(&mut unc));
549            assert!(p.write_compressed(&mut comp));
550            assert_eq!(unc[0], 0x04);
551            assert!(comp[0] == 0x02 || comp[0] == 0x03);
552
553            let a = AffinePoint::from_sec1(&unc).unwrap();
554            let b = AffinePoint::from_sec1(&comp).unwrap();
555            assert_eq!(a.x, p.x);
556            assert_eq!(a.y, p.y);
557            assert_eq!(b.x, p.x);
558            assert_eq!(b.y, p.y, "compressed y for [{k}]G");
559        }
560    }
561
562    #[test]
563    fn decoding_rejects_bad_encodings() {
564        let g = Point::generator().to_affine().unwrap();
565        let mut unc = [0u8; 65];
566        assert!(g.write_uncompressed(&mut unc));
567
568        assert!(AffinePoint::from_sec1(&[]).is_none());
569        assert!(AffinePoint::from_sec1(&[0u8; 65]).is_none(), "identity");
570        assert!(AffinePoint::from_sec1(&unc[..64]).is_none(), "truncated");
571
572        let mut bad = unc;
573        bad[0] = 0x05;
574        assert!(AffinePoint::from_sec1(&bad).is_none(), "bad tag");
575
576        let mut bad = unc;
577        bad[64] ^= 1;
578        assert!(AffinePoint::from_sec1(&bad).is_none(), "off curve");
579    }
580
581    // -- ECDSA ------------------------------------------------------------
582
583    const KEY: &str = "c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721";
584
585    /// RFC 6979 A.2.5, message "sample". Matching this exercises the field, the
586    /// group law, the scalar ring, the nonce derivation, and the signing
587    /// equation in one shot.
588    #[test]
589    fn rfc6979_sample_vector() {
590        let key = unhex(KEY).unwrap();
591        let mut sig = [0u8; 64];
592        EcdsaP256Sha256::sign(&key, b"sample", &mut sig).unwrap();
593        assert_eq!(
594            hex(&sig[..32]),
595            "efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716",
596            "r"
597        );
598        assert_eq!(
599            hex(&sig[32..]),
600            "f7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8",
601            "s"
602        );
603    }
604
605    /// RFC 6979 A.2.5, message "test".
606    #[test]
607    fn rfc6979_test_vector() {
608        let key = unhex(KEY).unwrap();
609        let mut sig = [0u8; 64];
610        EcdsaP256Sha256::sign(&key, b"test", &mut sig).unwrap();
611        assert_eq!(
612            hex(&sig[..32]),
613            "f1abb023518351cd71d881567b1ea663ed3efcf6c5132b354f28d3b0b7d38367",
614            "r"
615        );
616        assert_eq!(
617            hex(&sig[32..]),
618            "019f4113742a2b14bd25926b49c649155f267e60d3814b4c0cc84250e46f0083",
619            "s"
620        );
621    }
622
623    #[test]
624    fn rfc6979_public_key() {
625        let key = unhex(KEY).unwrap();
626        let mut pk = [0u8; 65];
627        EcdsaP256Sha256::public_key(&key, &mut pk).unwrap();
628        assert_eq!(
629            hex(&pk[1..33]),
630            "60fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6",
631            "Ux"
632        );
633        assert_eq!(
634            hex(&pk[33..]),
635            "7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299",
636            "Uy"
637        );
638    }
639
640    #[test]
641    fn signing_is_deterministic_and_message_bound() {
642        let key = unhex(KEY).unwrap();
643        let mut a = [0u8; 64];
644        let mut b = [0u8; 64];
645        EcdsaP256Sha256::sign(&key, b"same", &mut a).unwrap();
646        EcdsaP256Sha256::sign(&key, b"same", &mut b).unwrap();
647        assert_eq!(a, b, "RFC 6979 signing must not depend on an RNG");
648
649        EcdsaP256Sha256::sign(&key, b"other", &mut b).unwrap();
650        assert_ne!(&a[..32], &b[..32], "r must differ between messages");
651    }
652
653    #[test]
654    fn sign_and_verify_round_trip() {
655        let key = unhex(KEY).unwrap();
656        let mut pk = [0u8; 65];
657        EcdsaP256Sha256::public_key(&key, &mut pk).unwrap();
658        for message in [&b""[..], b"short", &[0x5au8; 1000][..]] {
659            let mut sig = [0u8; 64];
660            EcdsaP256Sha256::sign(&key, message, &mut sig).unwrap();
661            EcdsaP256Sha256::verify(&pk, message, &sig).unwrap();
662        }
663    }
664
665    #[test]
666    fn verification_rejects_tampering() {
667        let key = unhex(KEY).unwrap();
668        let mut pk = [0u8; 65];
669        EcdsaP256Sha256::public_key(&key, &mut pk).unwrap();
670        let mut sig = [0u8; 64];
671        EcdsaP256Sha256::sign(&key, b"authentic", &mut sig).unwrap();
672
673        assert!(EcdsaP256Sha256::verify(&pk, b"forged", &sig).is_err());
674        let mut bad = sig;
675        bad[0] ^= 1;
676        assert!(EcdsaP256Sha256::verify(&pk, b"authentic", &bad).is_err());
677        let mut bad = sig;
678        bad[63] ^= 1;
679        assert!(EcdsaP256Sha256::verify(&pk, b"authentic", &bad).is_err());
680
681        let mut other = [0u8; 65];
682        EcdsaP256Sha256::public_key(&[0x11u8; 32], &mut other).unwrap();
683        assert!(EcdsaP256Sha256::verify(&other, b"authentic", &sig).is_err());
684    }
685
686    #[test]
687    fn verification_rejects_degenerate_signatures() {
688        let key = unhex(KEY).unwrap();
689        let mut pk = [0u8; 65];
690        EcdsaP256Sha256::public_key(&key, &mut pk).unwrap();
691
692        let mut zero_r = [0u8; 64];
693        zero_r[63] = 1;
694        assert!(EcdsaP256Sha256::verify(&pk, b"m", &zero_r).is_err());
695
696        let mut zero_s = [0u8; 64];
697        zero_s[31] = 1;
698        assert!(EcdsaP256Sha256::verify(&pk, b"m", &zero_s).is_err());
699
700        let n_bytes =
701            unhex("ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551").unwrap();
702        let mut at_n = [0u8; 64];
703        at_n[..32].copy_from_slice(&n_bytes);
704        at_n[32..].copy_from_slice(&n_bytes);
705        assert!(EcdsaP256Sha256::verify(&pk, b"m", &at_n).is_err());
706    }
707
708    #[test]
709    fn signing_rejects_invalid_private_keys() {
710        let mut sig = [0u8; 64];
711        assert!(
712            EcdsaP256Sha256::sign(&[0u8; 32], b"m", &mut sig).is_err(),
713            "zero"
714        );
715        assert!(
716            EcdsaP256Sha256::sign(&[0xffu8; 32], b"m", &mut sig).is_err(),
717            ">= n"
718        );
719        assert!(
720            EcdsaP256Sha256::sign(&[1u8; 31], b"m", &mut sig).is_err(),
721            "short"
722        );
723    }
724
725    /// Both `(r, s)` and `(r, n - s)` verify; normalization picks one.
726    #[test]
727    fn malleability_and_normalization() {
728        let key = unhex(KEY).unwrap();
729        let mut pk = [0u8; 65];
730        EcdsaP256Sha256::public_key(&key, &mut pk).unwrap();
731        let mut sig = [0u8; 64];
732        EcdsaP256Sha256::sign(&key, b"sample", &mut sig).unwrap();
733        assert!(
734            !EcdsaP256Sha256::has_low_s(&sig).unwrap(),
735            "RFC 6979 s is high here"
736        );
737
738        let mut flipped = sig;
739        EcdsaP256Sha256::normalize_s(&mut flipped).unwrap();
740        assert_ne!(flipped, sig);
741        EcdsaP256Sha256::verify(&pk, b"sample", &flipped).unwrap();
742        assert!(EcdsaP256Sha256::has_low_s(&flipped).unwrap());
743
744        let mut twice = flipped;
745        EcdsaP256Sha256::normalize_s(&mut twice).unwrap();
746        assert_eq!(twice, flipped, "normalization must be idempotent");
747    }
748
749    #[test]
750    fn ecdsa_self_test_passes() {
751        EcdsaP256Sha256::self_test().unwrap();
752    }
753
754    // -- ECDH -------------------------------------------------------------
755
756    /// NIST CAVP ECC CDH, first published case.
757    #[test]
758    fn cavp_ecc_cdh_vector() {
759        let d = unhex("7d7dc5f71eb29ddaf80d6214632eeae03d9058af1fb6d22ed80badb62bc1a534").unwrap();
760        let mut peer = vec![0x04u8];
761        peer.extend_from_slice(
762            &unhex("700c48f77f56584c5cc632ca65640db91b6bacce3a4df6b42ce7cc838833d287").unwrap(),
763        );
764        peer.extend_from_slice(
765            &unhex("db71e509e3fd9b060ddb20ba5c51dcc5948d46fbf640dfe0441782cab85fa4ac").unwrap(),
766        );
767        let mut z = [0u8; 32];
768        EcdhP256::agree(&d, &peer, &mut z).unwrap();
769        assert_eq!(
770            hex(&z),
771            "46fc62106420ff012e54a434fbdd2d25ccc5852060561e68040dd7778997bd7b"
772        );
773    }
774
775    #[test]
776    fn both_parties_derive_the_same_secret() {
777        let (alice, bob) = ([0x11u8; 32], [0x22u8; 32]);
778        let mut alice_pk = [0u8; 65];
779        let mut bob_pk = [0u8; 65];
780        EcdhP256::public_key(&alice, &mut alice_pk).unwrap();
781        EcdhP256::public_key(&bob, &mut bob_pk).unwrap();
782
783        let mut z1 = [0u8; 32];
784        let mut z2 = [0u8; 32];
785        EcdhP256::agree(&alice, &bob_pk, &mut z1).unwrap();
786        EcdhP256::agree(&bob, &alice_pk, &mut z2).unwrap();
787        assert_eq!(z1, z2);
788        assert_ne!(z1, [0u8; 32]);
789    }
790
791    #[test]
792    fn compressed_and_uncompressed_peers_agree() {
793        let (alice, bob) = ([0x33u8; 32], [0x44u8; 32]);
794        let mut unc = [0u8; 65];
795        let mut comp = [0u8; 33];
796        EcdhP256::public_key(&bob, &mut unc).unwrap();
797        EcdhP256::public_key_compressed(&bob, &mut comp).unwrap();
798
799        let mut z1 = [0u8; 32];
800        let mut z2 = [0u8; 32];
801        EcdhP256::agree(&alice, &unc, &mut z1).unwrap();
802        EcdhP256::agree(&alice, &comp, &mut z2).unwrap();
803        assert_eq!(z1, z2, "the peer key encoding must not matter");
804    }
805
806    #[test]
807    fn ecdh_rejects_invalid_inputs() {
808        let alice = [0x11u8; 32];
809        let mut z = [0u8; 32];
810        assert!(EcdhP256::agree(&alice, &[0u8; 65], &mut z).is_err());
811        assert!(EcdhP256::agree(&alice, &[], &mut z).is_err());
812
813        let mut bob_pk = [0u8; 65];
814        EcdhP256::public_key(&[0x22u8; 32], &mut bob_pk).unwrap();
815        bob_pk[64] ^= 1;
816        assert!(
817            EcdhP256::agree(&alice, &bob_pk, &mut z).is_err(),
818            "off curve"
819        );
820
821        let mut pk = [0u8; 65];
822        assert!(EcdhP256::public_key(&[0u8; 32], &mut pk).is_err());
823        assert!(EcdhP256::public_key(&[0xffu8; 32], &mut pk).is_err());
824    }
825
826    #[test]
827    fn ecdh_self_test_passes() {
828        EcdhP256::self_test().unwrap();
829    }
830}