Skip to main content

bssl_crypto/
ec.rs

1// Copyright 2023 The BoringSSL Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Definitions of NIST elliptic curves.
16//!
17//! If you're looking for curve25519, see the `x25519` and `ed25519` modules.
18
19// This module is substantially internal-only and is only public for the
20// [`Curve`] trait, which is shared by ECDH and ECDSA.
21
22use crate::{cbb_to_buffer, parse_with_cbs, scoped, sealed, Buffer, FfiSlice};
23use alloc::{fmt::Debug, vec::Vec};
24use core::ptr::{null, null_mut};
25
26/// An elliptic curve.
27///
28/// ## Safety
29/// The current EC implementation are thread-safe.
30/// Implementers should make sure that further additions to the curve family
31/// should respect thread-safety, too.
32pub trait Curve: Debug + Sync + Send + sealed::Sealed {
33    /// Return the underlying [`Group`] of the curve
34    fn group() -> Group;
35
36    /// Hash `data` using a hash function suitable for the curve. (I.e.
37    /// SHA-256 for P-256 and SHA-384 for P-384.)
38    #[doc(hidden)]
39    fn hash(data: &[u8]) -> Vec<u8>;
40}
41
42/// The NIST P-256 curve, also called secp256r1.
43#[derive(Debug)]
44pub struct P256;
45
46impl sealed::Sealed for P256 {}
47
48impl Curve for P256 {
49    fn group() -> Group {
50        Group::P256
51    }
52
53    fn hash(data: &[u8]) -> Vec<u8> {
54        crate::digest::Sha256::hash(data).to_vec()
55    }
56}
57
58/// The NIST P-384 curve, also called secp384r1.
59#[derive(Debug)]
60pub struct P384;
61
62impl sealed::Sealed for P384 {}
63
64impl Curve for P384 {
65    fn group() -> Group {
66        Group::P384
67    }
68
69    fn hash(data: &[u8]) -> Vec<u8> {
70        crate::digest::Sha384::hash(data).to_vec()
71    }
72}
73
74#[derive(Copy, Clone, Eq, PartialEq, Debug)]
75#[doc(hidden)]
76pub enum Group {
77    P256,
78    P384,
79}
80
81impl Group {
82    fn as_ffi_ptr(self) -> *const bssl_sys::EC_GROUP {
83        // Safety: These functions cannot fail and no resources need to be
84        // released in the future.
85        match self {
86            Group::P256 => unsafe { bssl_sys::EC_group_p256() },
87            Group::P384 => unsafe { bssl_sys::EC_group_p384() },
88        }
89    }
90
91    fn as_evp_pkey_alg(self) -> *const bssl_sys::EVP_PKEY_ALG {
92        // Safety: These functions cannot fail and no resources need to be
93        // released in the future.
94        match self {
95            Group::P256 => unsafe { bssl_sys::EVP_pkey_ec_p256() },
96            Group::P384 => unsafe { bssl_sys::EVP_pkey_ec_p384() },
97        }
98    }
99}
100
101/// Point is a valid, finite point on some curve.
102pub(crate) struct Point {
103    group: *const bssl_sys::EC_GROUP,
104    point: *mut bssl_sys::EC_POINT,
105}
106
107impl Point {
108    /// Construct an uninitialized curve point. This is not public and all
109    /// callers must ensure that the point is initialized before being returned.
110    fn new(group: Group) -> Self {
111        let group = group.as_ffi_ptr();
112        // Safety: `group` is valid because it was constructed just above.
113        let point = unsafe { bssl_sys::EC_POINT_new(group) };
114        // `EC_POINT_new` only fails if out of memory, which is not a case that
115        // is handled short of panicking.
116        assert!(!point.is_null());
117        Self { group, point }
118    }
119
120    /// Construct a point by multiplying the curve's base point by the given
121    /// scalar.
122    ///
123    /// Safety: `scalar` must be a valid pointer.
124    unsafe fn from_scalar(group: Group, scalar: *const bssl_sys::BIGNUM) -> Option<Self> {
125        let point = Self::new(group);
126        // Safety: the members of `point` are valid by construction. `scalar`
127        // is assumed to be valid.
128        let result = unsafe {
129            bssl_sys::EC_POINT_mul(
130                point.group,
131                point.point,
132                scalar,
133                /*q=*/ null(),
134                /*m=*/ null(),
135                /*ctx=*/ null_mut(),
136            )
137        };
138        if result != 1 {
139            return None;
140        }
141        if 1 == unsafe { bssl_sys::EC_POINT_is_at_infinity(point.group, point.point) } {
142            return None;
143        }
144        Some(point)
145    }
146
147    /// Duplicate the given finite point.
148    unsafe fn clone_from_ptr(
149        group: *const bssl_sys::EC_GROUP,
150        point: *const bssl_sys::EC_POINT,
151    ) -> Point {
152        assert_eq!(0, unsafe {
153            bssl_sys::EC_POINT_is_at_infinity(group, point)
154        });
155
156        // Safety: we assume that the caller is passing valid pointers
157        let new_point = unsafe { bssl_sys::EC_POINT_dup(point, group) };
158        // `EC_POINT_dup` only fails if out of memory, which is not a case that
159        // is handled short of panicking.
160        assert!(!new_point.is_null());
161
162        Self {
163            group,
164            point: new_point,
165        }
166    }
167
168    pub fn as_ffi_ptr(&self) -> *const bssl_sys::EC_POINT {
169        self.point
170    }
171
172    fn from_x962(group: Group, x962: &[u8]) -> Option<Self> {
173        let point = Self::new(group);
174        // Safety: `point` is valid by construction. `x962` is a valid memory
175        // buffer.
176        let result = unsafe {
177            bssl_sys::EC_POINT_oct2point(
178                point.group,
179                point.point,
180                x962.as_ffi_ptr(),
181                x962.len(),
182                /*bn_ctx=*/ null_mut(),
183            )
184        };
185        if result == 1 {
186            // The X9.62 encoding of the point at infinity is 0x00, but
187            // BoringSSL will never parse it. So this should be moot,
188            // but `Point` must never contain infinity.
189            assert_eq!(0, unsafe {
190                bssl_sys::EC_POINT_is_at_infinity(point.group, point.point)
191            });
192            Some(point)
193        } else {
194            None
195        }
196    }
197
198    /// Create a new point from an uncompressed X9.62 representation.
199    ///
200    /// (X9.62 is the standard representation of an elliptic-curve point that
201    /// starts with an 0x04 byte.)
202    pub fn from_x962_uncompressed(group: Group, x962: &[u8]) -> Option<Self> {
203        const UNCOMPRESSED: u8 =
204            bssl_sys::point_conversion_form_t::POINT_CONVERSION_UNCOMPRESSED as u8;
205        if x962.first()? != &UNCOMPRESSED {
206            return None;
207        }
208
209        Self::from_x962(group, x962)
210    }
211
212    pub fn to_x962_uncompressed(&self) -> Buffer {
213        // Safety: arguments are valid, `EC_KEY` ensures that the group is
214        // correct for the point, and a `Point` is always finite.
215        unsafe {
216            to_x962(
217                self.group,
218                self.point,
219                bssl_sys::point_conversion_form_t::POINT_CONVERSION_UNCOMPRESSED,
220            )
221        }
222    }
223
224    pub fn from_x962_compressed(group: Group, x962: &[u8]) -> Option<Self> {
225        // The first byte of the compressed format can be either 0x02 or 0x03,
226        // to indicate whether the y coordinate of the point is even or odd.
227        let first_byte = *x962.first()?;
228        if first_byte != 2 && first_byte != 3 {
229            return None;
230        }
231
232        Self::from_x962(group, x962)
233    }
234
235    /// WARNING: compressed form is rarely used and is not as well supported as
236    /// the uncompressed form.
237    pub fn to_x962_compressed(&self) -> Buffer {
238        // Safety: arguments are valid, `EC_KEY` ensures that the group is
239        // correct for the point, and a `Point` is always finite.
240        unsafe {
241            to_x962(
242                self.group,
243                self.point,
244                bssl_sys::point_conversion_form_t::POINT_CONVERSION_COMPRESSED,
245            )
246        }
247    }
248
249    pub fn from_der_subject_public_key_info(group: Group, spki: &[u8]) -> Option<Self> {
250        let alg = group.as_evp_pkey_alg();
251        let mut pkey =
252            scoped::EvpPkey::from_der_subject_public_key_info(spki, core::slice::from_ref(&alg))?;
253        let ec_key = unsafe { bssl_sys::EVP_PKEY_get0_EC_KEY(pkey.as_ffi_ptr()) };
254        // We only passed in one allowed algorithm, an EC algorithm.
255        assert!(!ec_key.is_null());
256        let parsed_group = unsafe { bssl_sys::EC_KEY_get0_group(ec_key) };
257        // We only passed in one allowed algorithm, this EC group.
258        assert!(parsed_group == group.as_ffi_ptr());
259        let point = unsafe { bssl_sys::EC_KEY_get0_public_key(ec_key) };
260        // A valid EC SPKI cannot be missing the public key.
261        assert!(!point.is_null());
262        // Safety: `ec_key` is still owned by `pkey` and doesn't need to be freed.
263        Some(unsafe { Self::clone_from_ptr(parsed_group, point) })
264    }
265
266    /// Calls `func` with an `EC_KEY` that contains a copy of this point.
267    pub fn with_point_as_ec_key<F, T>(&self, func: F) -> T
268    where
269        F: FnOnce(*mut bssl_sys::EC_KEY) -> T,
270    {
271        let mut ec_key = scoped::EcKey::new();
272        // Safety: `self.group` is always valid by construction and this doesn't
273        // pass ownership.
274        assert_eq!(1, unsafe {
275            bssl_sys::EC_KEY_set_group(ec_key.as_ffi_ptr(), self.group)
276        });
277        // Safety: `self.point` is always valid by construction and this doesn't
278        // pass ownership.
279        assert_eq!(1, unsafe {
280            bssl_sys::EC_KEY_set_public_key(ec_key.as_ffi_ptr(), self.point)
281        });
282        func(ec_key.as_ffi_ptr())
283    }
284
285    pub fn to_der_subject_public_key_info(&self) -> Buffer {
286        // Safety: `ec_key` is a valid pointer in this context.
287        self.with_point_as_ec_key(|ec_key| unsafe { to_der_subject_public_key_info(ec_key) })
288    }
289}
290
291// Safety:
292//
293// An `EC_POINT` can be used concurrently from multiple threads so long as no
294// mutating operations are performed. The mutating operations used here are
295// `EC_POINT_mul` and `EC_POINT_oct2point`, which can be observed by setting
296// `point` to be `*const` in the struct and seeing what errors trigger.
297//
298// Both those operations are done internally, however, before a `Point` is
299// returned. So, after construction, callers cannot mutate the `EC_POINT`.
300unsafe impl Sync for Point {}
301unsafe impl Send for Point {}
302
303impl Drop for Point {
304    fn drop(&mut self) {
305        // Safety: `self.point` must be valid because only valid `Point`s can
306        // be constructed. `self.group` does not need to be freed.
307        unsafe { bssl_sys::EC_POINT_free(self.point) }
308    }
309}
310
311/// Key holds both a public and private key. While BoringSSL allows an `EC_KEY`
312/// to also be a) empty, b) holding only a private scalar, or c) holding only
313// a public key, those cases are never exposed as a `Key`.
314pub(crate) struct Key(*mut bssl_sys::EC_KEY);
315
316impl Key {
317    /// Construct an uninitialized key. This is not public and all
318    /// callers must ensure that the key is initialized before being returned.
319    fn new(group: Group) -> Self {
320        let key = unsafe { bssl_sys::EC_KEY_new() };
321        // `EC_KEY_new` only fails if out of memory, which is not a case that
322        // is handled short of panicking.
323        assert!(!key.is_null());
324
325        // Setting the group on a fresh `EC_KEY` never fails.
326        assert_eq!(1, unsafe {
327            bssl_sys::EC_KEY_set_group(key, group.as_ffi_ptr())
328        });
329
330        Self(key)
331    }
332
333    pub fn as_ffi_ptr(&self) -> *const bssl_sys::EC_KEY {
334        self.0
335    }
336
337    /// Generate a random private key.
338    pub fn generate(group: Group) -> Self {
339        let key = Self::new(group);
340        // Generation only fails if out of memory, which is only handled by
341        // panicking.
342        assert_eq!(1, unsafe { bssl_sys::EC_KEY_generate_key(key.0) });
343        // `EC_KEY_generate_key` is documented as also setting the public key.
344        key
345    }
346
347    /// Construct a private key from a big-endian representation of the private
348    /// scalar. The scalar must be zero padded to the correct length for the
349    /// curve.
350    pub fn from_big_endian(group: Group, scalar: &[u8]) -> Option<Self> {
351        let key = Self::new(group);
352        // Safety: `key.0` is always valid by construction.
353        let result = unsafe { bssl_sys::EC_KEY_oct2priv(key.0, scalar.as_ffi_ptr(), scalar.len()) };
354        if result != 1 {
355            return None;
356        }
357
358        // BoringSSL allows an `EC_KEY` to have a private scalar without a
359        // public point, but `Key` is never exposed in that state.
360
361        // Safety: `key.0` is valid by construction. The returned value is
362        // still owned the `EC_KEY`.
363        let scalar = unsafe { bssl_sys::EC_KEY_get0_private_key(key.0) };
364        assert!(!scalar.is_null());
365
366        // Safety: `scalar` is a valid pointer.
367        let point = unsafe { Point::from_scalar(group, scalar)? };
368        // Safety: `key.0` is valid by construction, as is `point.point`. The
369        // point is copied into the `EC_KEY` so ownership isn't being moved.
370        let result = unsafe { bssl_sys::EC_KEY_set_public_key(key.0, point.point) };
371        // Setting the public key should only fail if out of memory, which this
372        // crate doesn't handle, or if the groups don't match, which is
373        // impossible.
374        assert_eq!(result, 1);
375
376        Some(key)
377    }
378
379    pub fn to_big_endian(&self) -> Buffer {
380        let mut ptr: *mut u8 = null_mut();
381        // Safety: `self.0` is valid by construction. If this returns non-zero
382        // then ptr holds ownership of a buffer.
383        unsafe {
384            let len = bssl_sys::EC_KEY_priv2buf(self.0, &mut ptr);
385            assert!(len != 0);
386            Buffer::new(ptr, len)
387        }
388    }
389
390    /// Parses an ECPrivateKey structure from [RFC 5915].
391    ///
392    /// [RFC 5915]: <https://datatracker.ietf.org/doc/html/rfc5915>
393    pub fn from_der_ec_private_key(group: Group, der: &[u8]) -> Option<Self> {
394        let key = parse_with_cbs(
395            der,
396            // Safety: in this context, `key` is the non-null result of
397            // `EC_KEY_parse_private_key`.
398            |key| unsafe { bssl_sys::EC_KEY_free(key) },
399            // Safety: `cbs` is valid per `parse_with_cbs` and `group` always
400            // returns a valid pointer.
401            |cbs| unsafe { bssl_sys::EC_KEY_parse_private_key(cbs, group.as_ffi_ptr()) },
402        )?;
403        Some(Self(key))
404    }
405
406    /// Parses an ECPrivateKey structure from [RFC 5915], whose curve is specified by
407    /// the `ECParameters`.
408    ///
409    /// Unless the curve group is one of the variants of [`Group`], this method returns [`None`].
410    ///
411    /// [RFC 5915]: <https://datatracker.ietf.org/doc/html/rfc5915>
412    pub fn from_der_ec_private_key_with_curve_names(der: &[u8]) -> Option<Self> {
413        let key = parse_with_cbs(
414            der,
415            // Safety: in this context, `key` is the non-null result of
416            // `EC_KEY_parse_private_key`.
417            |key| unsafe { bssl_sys::EC_KEY_free(key) },
418            // Safety: `cbs` is valid per `parse_with_cbs`.
419            |cbs| unsafe { bssl_sys::EC_KEY_parse_private_key(cbs, null()) },
420        )?;
421        let key = Self(key);
422        if key.get_group().is_none() {
423            None
424        } else {
425            Some(key)
426        }
427    }
428
429    /// Serializes this private key as an ECPrivateKey structure from [RFC 5915].
430    ///
431    /// This method also **serialise** known curve names as `ECParameters`.
432    ///
433    /// [RFC 5915]: <https://datatracker.ietf.org/doc/html/rfc5915>
434    pub fn to_der_ec_private_key(&self) -> Buffer {
435        cbb_to_buffer(64, |cbb| unsafe {
436            // Safety: the `EC_KEY` is always valid so `EC_KEY_marshal_private_key`
437            // should only fail if out of memory, which this crate doesn't handle.
438            assert_eq!(1, bssl_sys::EC_KEY_marshal_private_key(cbb, self.0, 0));
439        })
440    }
441
442    /// Parses a PrivateKeyInfo structure (from RFC 5208).
443    pub fn from_der_private_key_info(group: Group, der: &[u8]) -> Option<Self> {
444        let alg = group.as_evp_pkey_alg();
445        let pkey = scoped::EvpPkey::from_der_private_key_info(der, core::slice::from_ref(&alg))?;
446        // Safety: the pkey is not aliased
447        let ec_key = Self::from_evp_pkey(pkey)?;
448        // We only passed in one allowed algorithm, this EC group.
449        (ec_key.get_group()? == group).then_some(ec_key)
450    }
451
452    // Safety: the pkey must not be aliased via `as_ffi_ptr`
453    pub(crate) fn from_evp_pkey(mut pkey: scoped::EvpPkey) -> Option<Self> {
454        let ec_key = unsafe { bssl_sys::EVP_PKEY_get1_EC_KEY(pkey.as_ffi_ptr()) };
455        if ec_key.is_null() {
456            return None;
457        }
458        // Safety: `EVP_PKEY_get1_EC_KEY` returned owned key, which we can move
459        // into the returned object and whose lifetime is independent of the EVP pkey.
460        Some(Self(ec_key))
461    }
462
463    pub(crate) fn get_group(&self) -> Option<Group> {
464        // Safety: we own the `EC_KEY`
465        let id = unsafe { bssl_sys::EC_KEY_get0_group(self.0) };
466        if id == Group::P256.as_ffi_ptr() {
467            Some(Group::P256)
468        } else if id == Group::P384.as_ffi_ptr() {
469            Some(Group::P384)
470        } else {
471            None
472        }
473    }
474
475    /// Serializes this private key as a PrivateKeyInfo structure from RFC 5208.
476    pub fn to_der_private_key_info(&self) -> Buffer {
477        let mut pkey = scoped::EvpPkey::new();
478        // Safety: `pkey` was just allocated above; the `EC_KEY` is valid by
479        // construction. This call takes a reference to the `EC_KEY` and so
480        // hasn't stolen ownership from `self`.
481        assert_eq!(1, unsafe {
482            bssl_sys::EVP_PKEY_set1_EC_KEY(pkey.as_ffi_ptr(), self.0)
483        });
484        cbb_to_buffer(64, |cbb| unsafe {
485            // `EVP_marshal_private_key` should always return one because this
486            // key is valid by construction.
487            assert_eq!(1, bssl_sys::EVP_marshal_private_key(cbb, pkey.as_ffi_ptr()));
488        })
489    }
490
491    pub fn to_point(&self) -> Point {
492        // Safety: `self.0` is valid by construction.
493        let group = unsafe { bssl_sys::EC_KEY_get0_group(self.0) };
494        let point = unsafe { bssl_sys::EC_KEY_get0_public_key(self.0) };
495        // A `Key` is never constructed without a public key.
496        assert!(!point.is_null());
497        // Safety: pointers are valid and `clone_from_ptr` doesn't take
498        // ownership.
499        unsafe { Point::clone_from_ptr(group, point) }
500    }
501
502    pub fn to_x962_uncompressed(&self) -> Buffer {
503        // Safety: `self.0` is valid by construction.
504        let group = unsafe { bssl_sys::EC_KEY_get0_group(self.0) };
505        let point = unsafe { bssl_sys::EC_KEY_get0_public_key(self.0) };
506        // Safety: arguments are valid, `EC_KEY` ensures that the group is
507        // correct for the point, and a `Key` always holds a finite public point.
508        unsafe {
509            to_x962(
510                group,
511                point,
512                bssl_sys::point_conversion_form_t::POINT_CONVERSION_UNCOMPRESSED,
513            )
514        }
515    }
516
517    /// WARNING: compressed form is rarely used and is not as well supported as
518    /// the uncompressed form.
519    pub fn to_x962_compressed(&self) -> Buffer {
520        // Safety: `self.0` is valid by construction.
521        let group = unsafe { bssl_sys::EC_KEY_get0_group(self.0) };
522        let point = unsafe { bssl_sys::EC_KEY_get0_public_key(self.0) };
523        // Safety: arguments are valid, `EC_KEY` ensures that the group is
524        // correct for the point, and a `Key` always holds a finite public point.
525        unsafe {
526            to_x962(
527                group,
528                point,
529                bssl_sys::point_conversion_form_t::POINT_CONVERSION_COMPRESSED,
530            )
531        }
532    }
533
534    pub fn to_der_subject_public_key_info(&self) -> Buffer {
535        // Safety: `self.0` is always valid by construction.
536        unsafe { to_der_subject_public_key_info(self.0) }
537    }
538}
539
540// Safety:
541//
542// An `EC_KEY` is safe to use from multiple threads so long as no mutating
543// operations are performed. (Reference count changes don't count as mutating.)
544// The mutating operations used here are:
545//   * EC_KEY_generate_key
546//   * EC_KEY_oct2priv
547//   * EC_KEY_set_public_key
548// But those are all done internally, before a `Key` is returned. So, once
549// constructed, callers cannot mutate the `EC_KEY`.
550unsafe impl Sync for Key {}
551unsafe impl Send for Key {}
552
553impl Drop for Key {
554    fn drop(&mut self) {
555        // Safety: `self.0` must be valid because only valid `Key`s can
556        // be constructed.
557        unsafe { bssl_sys::EC_KEY_free(self.0) }
558    }
559}
560
561impl Clone for Key {
562    fn clone(&self) -> Self {
563        unsafe {
564            bssl_sys::EC_KEY_up_ref(self.0);
565        }
566        Self(self.0)
567    }
568}
569
570/// Serialize a finite point to X9.62 format.
571///
572/// Callers must ensure that the arguments are valid, that the point has the
573/// specified group, and that the point is finite.
574unsafe fn to_x962(
575    group: *const bssl_sys::EC_GROUP,
576    point: *const bssl_sys::EC_POINT,
577    form: bssl_sys::point_conversion_form_t,
578) -> Buffer {
579    cbb_to_buffer(
580        // This length is just a hint and is tuned for P-256's output length.
581        if form == bssl_sys::point_conversion_form_t::POINT_CONVERSION_UNCOMPRESSED {
582            1 + 32 + 32
583        } else {
584            1 + 32
585        },
586        |cbb| unsafe {
587            // Safety: the caller must ensure that the arguments are valid.
588            let result =
589                bssl_sys::EC_POINT_point2cbb(cbb, group, point, form, /*bn_ctx=*/ null_mut());
590            // The public key is always finite, so `EC_POINT_point2cbb` only fails
591            // if out of memory, which isn't handled by this crate.
592            assert_eq!(result, 1);
593        },
594    )
595}
596
597unsafe fn to_der_subject_public_key_info(ec_key: *mut bssl_sys::EC_KEY) -> Buffer {
598    let mut pkey = scoped::EvpPkey::new();
599    // Safety: this takes a reference to `ec_key` and so doesn't steal ownership.
600    assert_eq!(1, unsafe {
601        bssl_sys::EVP_PKEY_set1_EC_KEY(pkey.as_ffi_ptr(), ec_key)
602    });
603    cbb_to_buffer(
604        // This length is just a hint and is tuned for P-256's output length.
605        65,
606        |cbb| unsafe {
607            // The arguments are valid so this will only fail if out of memory,
608            // which this crate doesn't handle.
609            assert_eq!(1, bssl_sys::EVP_marshal_public_key(cbb, pkey.as_ffi_ptr()));
610        },
611    )
612}
613
614#[cfg(test)]
615mod test {
616    use super::*;
617
618    #[derive(PartialEq)]
619    enum Corruption {
620        ShouldBeDetected,
621        DontTest,
622    }
623
624    fn test_point_format<Serialize, Parse>(
625        group: Group,
626        serialize_func: Serialize,
627        parse_func: Parse,
628        corruption: Corruption,
629    ) where
630        Serialize: FnOnce(&Point) -> Buffer,
631        Parse: Fn(&[u8]) -> Option<Point>,
632    {
633        let key = Key::generate(group);
634        let point = key.to_point();
635
636        let mut vec = serialize_func(&point).as_ref().to_vec();
637        let point2 = parse_func(vec.as_slice()).unwrap();
638        assert_eq!(
639            point.to_x962_uncompressed().as_ref(),
640            point2.to_x962_uncompressed().as_ref()
641        );
642
643        assert!(parse_func(&vec.as_slice()[0..16]).is_none());
644
645        // Messing with the first byte should always cause an error.
646        vec[0] ^= 64;
647        assert!(parse_func(vec.as_slice()).is_none());
648        vec[0] ^= 64;
649
650        if corruption == Corruption::ShouldBeDetected {
651            vec[11] ^= 1;
652            assert!(parse_func(vec.as_slice()).is_none());
653            vec[11] ^= 1;
654        }
655
656        assert!(parse_func(b"").is_none());
657    }
658
659    #[test]
660    fn x962() {
661        let x962 = b"\x04\x74\xcf\x69\xcb\xd1\x2b\x75\x07\x42\x85\xcf\x69\x6f\xc2\x56\x4b\x90\xe7\xeb\xbc\xd0\xe7\x20\x36\x86\x66\xbe\xcc\x94\x75\xa2\xa4\x4c\x2a\xf8\xa2\x56\xb8\x92\xb7\x7d\x17\xba\x97\x93\xbb\xf2\x9f\x52\x26\x7d\x90\xf9\x2c\x37\x26\x02\xbb\x4e\xd1\x89\x7c\xad\x54";
662        assert!(Point::from_x962_uncompressed(Group::P256, x962).is_some());
663
664        test_point_format(
665            Group::P256,
666            |point| point.to_x962_uncompressed(),
667            |buf| Point::from_x962_uncompressed(Group::P256, buf),
668            Corruption::ShouldBeDetected,
669        );
670
671        test_point_format(
672            Group::P384,
673            |point| point.to_x962_uncompressed(),
674            |buf| Point::from_x962_uncompressed(Group::P384, buf),
675            Corruption::ShouldBeDetected,
676        );
677
678        test_point_format(
679            Group::P256,
680            |point| point.to_x962_compressed(),
681            |buf| Point::from_x962_compressed(Group::P256, buf),
682            // Flipping a bit in a compressed point has a reasonable chance of
683            // producing another valid point, so we can't run a bit-flip test
684            // in this case.
685            Corruption::DontTest,
686        );
687
688        test_point_format(
689            Group::P384,
690            |point| point.to_x962_compressed(),
691            |buf| Point::from_x962_compressed(Group::P384, buf),
692            // Flipping a bit in a compressed point has a reasonable chance of
693            // producing another valid point, so we can't run a bit-flip test
694            // in this case.
695            Corruption::DontTest,
696        );
697    }
698
699    #[test]
700    fn x962_crossing_formats() {
701        let point = Key::generate(Group::P256).to_point();
702        let uncompressed = point.to_x962_uncompressed();
703        let compressed = point.to_x962_compressed();
704
705        // Compressed points won't be accepted by the uncompressed function and
706        // vice-versa.
707        assert!(Point::from_x962_uncompressed(Group::P256, compressed.as_ref()).is_none());
708        assert!(Point::from_x962_compressed(Group::P256, uncompressed.as_ref()).is_none());
709    }
710
711    #[test]
712    fn x962_infinity_not_accepted() {
713        // 0x00 is the X9.62 encoding of the point at infinity.
714        let infinity = &[0];
715        assert!(Point::from_x962_uncompressed(Group::P256, infinity).is_none());
716        assert!(Point::from_x962_compressed(Group::P256, infinity).is_none());
717    }
718
719    #[test]
720    fn x962_empty() {
721        // The X9.62 functions look at the first byte to check the type. They
722        // must handle the case of an empty input correctly.
723        let empty = b"";
724        assert!(Point::from_x962_uncompressed(Group::P256, empty).is_none());
725        assert!(Point::from_x962_compressed(Group::P256, empty).is_none());
726    }
727
728    #[test]
729    fn spki() {
730        test_point_format(
731            Group::P256,
732            |point| point.to_der_subject_public_key_info(),
733            |buf| Point::from_der_subject_public_key_info(Group::P256, buf),
734            Corruption::ShouldBeDetected,
735        );
736
737        test_point_format(
738            Group::P384,
739            |point| point.to_der_subject_public_key_info(),
740            |buf| Point::from_der_subject_public_key_info(Group::P384, buf),
741            Corruption::ShouldBeDetected,
742        );
743    }
744
745    fn test_key_format<Serialize, Parse>(group: Group, serialize_func: Serialize, parse_func: Parse)
746    where
747        Serialize: FnOnce(&Key) -> Buffer,
748        Parse: Fn(&[u8]) -> Option<Key>,
749    {
750        let key = Key::generate(group);
751        assert_eq!(key.get_group().unwrap(), group);
752
753        let vec = serialize_func(&key).as_ref().to_vec();
754        let key2 = parse_func(vec.as_slice()).unwrap();
755        assert_eq!(
756            key.to_x962_uncompressed().as_ref(),
757            key2.to_x962_uncompressed().as_ref()
758        );
759        assert_eq!(key.get_group(), key2.get_group());
760
761        assert!(parse_func(&vec.as_slice()[0..16]).is_none());
762        assert!(parse_func(b"").is_none());
763    }
764
765    #[test]
766    fn der_ec_private_key() {
767        for group in [Group::P256, Group::P384] {
768            test_key_format(
769                group,
770                |key| key.to_der_ec_private_key(),
771                |buf| Key::from_der_ec_private_key(group, buf),
772            );
773            test_key_format(
774                group,
775                |key| key.to_der_ec_private_key(),
776                |buf| Key::from_der_ec_private_key_with_curve_names(buf),
777            );
778        }
779    }
780
781    #[test]
782    fn der_private_key_info() {
783        for group in [Group::P256, Group::P384] {
784            test_key_format(
785                group,
786                |key| key.to_der_private_key_info(),
787                |buf| Key::from_der_private_key_info(group, buf),
788            );
789        }
790    }
791
792    #[test]
793    fn big_endian() {
794        for group in [Group::P256, Group::P384] {
795            test_key_format(
796                group,
797                |key| key.to_big_endian(),
798                |buf| Key::from_big_endian(group, buf),
799            );
800        }
801    }
802}