Skip to main content

elliptic_curve/
sec1.rs

1//! SEC1 encoding support.
2//!
3//! Support for the `Elliptic-Curve-Point-to-Octet-String` encoding described
4//! in SEC1: Elliptic Curve Cryptography (Version 2.0) section 2.3.3 (p.10):
5//!
6//! <https://www.secg.org/sec1-v2.pdf>
7
8use crate::{bigint::Encoding as _, weierstrass::Curve, Error, FieldBytes, FieldSize, Result};
9use core::{
10    fmt::{self, Debug},
11    ops::Add,
12};
13use generic_array::{typenum::U1, ArrayLength, GenericArray};
14use subtle::{Choice, ConditionallySelectable};
15
16#[cfg(feature = "alloc")]
17use alloc::boxed::Box;
18
19#[cfg(feature = "arithmetic")]
20use crate::{weierstrass::DecompressPoint, AffinePoint, ProjectiveArithmetic};
21
22#[cfg(all(feature = "arithmetic", feature = "zeroize"))]
23use crate::{
24    group::{Curve as _, Group},
25    Scalar,
26};
27
28#[cfg(feature = "zeroize")]
29use crate::{secret_key::SecretKey, zeroize::Zeroize};
30
31/// Size of a compressed point for the given elliptic curve when encoded
32/// using the SEC1 `Elliptic-Curve-Point-to-Octet-String` algorithm
33/// (including leading `0x02` or `0x03` tag byte).
34pub type CompressedPointSize<C> = <FieldSize<C> as Add<U1>>::Output;
35
36/// Size of an uncompressed point for the given elliptic curve when encoded
37/// using the SEC1 `Elliptic-Curve-Point-to-Octet-String` algorithm
38/// (including leading `0x04` tag byte).
39pub type UncompressedPointSize<C> = <UntaggedPointSize<C> as Add<U1>>::Output;
40
41/// Size of an untagged point for given elliptic curve.
42pub type UntaggedPointSize<C> = <FieldSize<C> as Add>::Output;
43
44/// SEC1 encoded curve point.
45///
46/// This type is an enum over the compressed and uncompressed encodings,
47/// useful for cases where either encoding can be supported, or conversions
48/// between the two forms.
49#[derive(Clone, Default, Eq, PartialEq, PartialOrd, Ord)]
50pub struct EncodedPoint<C>
51where
52    C: Curve,
53    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
54    UncompressedPointSize<C>: ArrayLength<u8>,
55{
56    bytes: GenericArray<u8, UncompressedPointSize<C>>,
57}
58
59#[allow(clippy::len_without_is_empty)]
60impl<C> EncodedPoint<C>
61where
62    C: Curve,
63    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
64    UncompressedPointSize<C>: ArrayLength<u8>,
65{
66    /// Decode elliptic curve point (compressed or uncompressed) from the
67    /// `Elliptic-Curve-Point-to-Octet-String` encoding described in
68    /// SEC 1: Elliptic Curve Cryptography (Version 2.0) section
69    /// 2.3.3 (page 10).
70    ///
71    /// <http://www.secg.org/sec1-v2.pdf>
72    pub fn from_bytes(input: impl AsRef<[u8]>) -> Result<Self> {
73        let input = input.as_ref();
74
75        // Validate tag
76        let tag = input.first().cloned().ok_or(Error).and_then(Tag::from_u8)?;
77
78        // Validate length
79        let expected_len = tag.message_len(C::UInt::BYTE_SIZE);
80
81        if input.len() != expected_len {
82            return Err(Error);
83        }
84
85        let mut bytes = GenericArray::default();
86        bytes[..expected_len].copy_from_slice(input);
87        Ok(Self { bytes })
88    }
89
90    /// Decode elliptic curve point from raw uncompressed coordinates, i.e.
91    /// encoded as the concatenated `x || y` coordinates with no leading SEC1
92    /// tag byte (which would otherwise be `0x04` for an uncompressed point).
93    pub fn from_untagged_bytes(bytes: &GenericArray<u8, UntaggedPointSize<C>>) -> Self {
94        let (x, y) = bytes.split_at(C::UInt::BYTE_SIZE);
95        Self::from_affine_coordinates(x.into(), y.into(), false)
96    }
97
98    /// Encode an elliptic curve point from big endian serialized coordinates
99    /// (with optional point compression)
100    pub fn from_affine_coordinates(x: &FieldBytes<C>, y: &FieldBytes<C>, compress: bool) -> Self {
101        let tag = if compress {
102            Tag::compress_y(y.as_slice())
103        } else {
104            Tag::Uncompressed
105        };
106
107        let mut bytes = GenericArray::default();
108        bytes[0] = tag.into();
109        bytes[1..(C::UInt::BYTE_SIZE + 1)].copy_from_slice(x);
110
111        if !compress {
112            bytes[(C::UInt::BYTE_SIZE + 1)..].copy_from_slice(y);
113        }
114
115        Self { bytes }
116    }
117
118    /// Compute [`EncodedPoint`] representing the public key for the provided
119    /// [`SecretKey`].
120    ///
121    /// The `compress` flag requests point compression.
122    #[cfg(all(feature = "arithmetic", feature = "zeroize"))]
123    #[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
124    #[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
125    pub fn from_secret_key(secret_key: &SecretKey<C>, compress: bool) -> Self
126    where
127        C: Curve + ProjectiveArithmetic,
128        AffinePoint<C>: ToEncodedPoint<C>,
129        Scalar<C>: Zeroize,
130    {
131        (C::ProjectivePoint::generator() * secret_key.to_secret_scalar().as_ref())
132            .to_affine()
133            .to_encoded_point(compress)
134    }
135
136    /// Return [`EncodedPoint`] representing the additive identity
137    /// (a.k.a. point at infinity)
138    pub fn identity() -> Self {
139        Self::default()
140    }
141
142    /// Get the length of the encoded point in bytes
143    pub fn len(&self) -> usize {
144        self.tag().message_len(C::UInt::BYTE_SIZE)
145    }
146
147    /// Get byte slice containing the serialized [`EncodedPoint`].
148    pub fn as_bytes(&self) -> &[u8] {
149        &self.bytes[..self.len()]
150    }
151
152    /// Get boxed byte slice containing the serialized [`EncodedPoint`]
153    #[cfg(feature = "alloc")]
154    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
155    pub fn to_bytes(&self) -> Box<[u8]> {
156        self.as_bytes().to_vec().into_boxed_slice()
157    }
158
159    /// Serialize point as raw uncompressed coordinates without tag byte, i.e.
160    /// encoded as the concatenated `x || y` coordinates.
161    #[cfg(feature = "arithmetic")]
162    #[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
163    pub fn to_untagged_bytes(&self) -> Option<GenericArray<u8, UntaggedPointSize<C>>>
164    where
165        C: Curve + ProjectiveArithmetic,
166        AffinePoint<C>: DecompressPoint<C> + ToEncodedPoint<C>,
167    {
168        self.decompress().map(|point| {
169            let mut bytes = GenericArray::<u8, UntaggedPointSize<C>>::default();
170            bytes.copy_from_slice(&point.as_bytes()[1..]);
171            bytes
172        })
173    }
174
175    /// Is this [`EncodedPoint`] compact?
176    pub fn is_compact(&self) -> bool {
177        self.tag().is_compact()
178    }
179
180    /// Is this [`EncodedPoint`] compressed?
181    pub fn is_compressed(&self) -> bool {
182        self.tag().is_compressed()
183    }
184
185    /// Is this [`EncodedPoint`] the additive identity? (a.k.a. point at infinity)
186    pub fn is_identity(&self) -> bool {
187        self.tag().is_identity()
188    }
189
190    /// Compress this [`EncodedPoint`], returning a new [`EncodedPoint`].
191    pub fn compress(&self) -> Self {
192        match self.coordinates() {
193            Coordinates::Compressed { .. }
194            | Coordinates::Compact { .. }
195            | Coordinates::Identity => self.clone(),
196            Coordinates::Uncompressed { x, y } => Self::from_affine_coordinates(x, y, true),
197        }
198    }
199
200    /// Decompress this [`EncodedPoint`], returning a new [`EncodedPoint`].
201    #[cfg(feature = "arithmetic")]
202    #[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
203    pub fn decompress(&self) -> Option<Self>
204    where
205        C: Curve + ProjectiveArithmetic,
206        AffinePoint<C>: DecompressPoint<C> + ToEncodedPoint<C>,
207    {
208        match self.coordinates() {
209            Coordinates::Compressed { x, y_is_odd } => {
210                AffinePoint::<C>::decompress(x, Choice::from(y_is_odd as u8))
211                    .map(|s| s.to_encoded_point(false))
212                    .into()
213            }
214            Coordinates::Compact { .. } | Coordinates::Identity => None,
215            Coordinates::Uncompressed { .. } => Some(self.clone()),
216        }
217    }
218
219    /// Encode an [`EncodedPoint`] from the desired type
220    pub fn encode<T>(encodable: T, compress: bool) -> Self
221    where
222        T: ToEncodedPoint<C>,
223    {
224        encodable.to_encoded_point(compress)
225    }
226
227    /// Decode this [`EncodedPoint`] into the desired type
228    pub fn decode<T>(&self) -> Result<T>
229    where
230        T: FromEncodedPoint<C>,
231    {
232        T::from_encoded_point(self).ok_or(Error)
233    }
234
235    /// Get the SEC1 tag for this [`EncodedPoint`]
236    pub fn tag(&self) -> Tag {
237        // Tag is ensured valid by the constructor
238        Tag::from_u8(self.bytes[0]).expect("invalid tag")
239    }
240
241    /// Get the [`Coordinates`] for this [`EncodedPoint`].
242    #[inline]
243    pub fn coordinates(&self) -> Coordinates<'_, C> {
244        if self.is_identity() {
245            return Coordinates::Identity;
246        }
247
248        let (x, y) = self.bytes[1..].split_at(C::UInt::BYTE_SIZE);
249
250        if self.is_compressed() {
251            Coordinates::Compressed {
252                x: x.into(),
253                y_is_odd: self.tag() as u8 & 1 == 1,
254            }
255        } else if self.is_compact() {
256            Coordinates::Compact { x: x.into() }
257        } else {
258            Coordinates::Uncompressed {
259                x: x.into(),
260                y: y.into(),
261            }
262        }
263    }
264
265    /// Get the x-coordinate for this [`EncodedPoint`].
266    ///
267    /// Returns `None` if this point is the identity point.
268    pub fn x(&self) -> Option<&FieldBytes<C>> {
269        match self.coordinates() {
270            Coordinates::Identity => None,
271            Coordinates::Compressed { x, .. } => Some(x),
272            Coordinates::Uncompressed { x, .. } => Some(x),
273            Coordinates::Compact { x } => Some(x),
274        }
275    }
276
277    /// Get the y-coordinate for this [`EncodedPoint`].
278    ///
279    /// Returns `None` if this point is compressed or the identity point.
280    pub fn y(&self) -> Option<&FieldBytes<C>> {
281        match self.coordinates() {
282            Coordinates::Compressed { .. } | Coordinates::Identity => None,
283            Coordinates::Uncompressed { y, .. } => Some(y),
284            Coordinates::Compact { .. } => None,
285        }
286    }
287}
288
289impl<C> AsRef<[u8]> for EncodedPoint<C>
290where
291    C: Curve,
292    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
293    UncompressedPointSize<C>: ArrayLength<u8>,
294{
295    #[inline]
296    fn as_ref(&self) -> &[u8] {
297        self.as_bytes()
298    }
299}
300
301impl<C> ConditionallySelectable for EncodedPoint<C>
302where
303    C: Curve,
304    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
305    UncompressedPointSize<C>: ArrayLength<u8>,
306    <UncompressedPointSize<C> as ArrayLength<u8>>::ArrayType: Copy,
307{
308    fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
309        let mut bytes = GenericArray::default();
310
311        for (i, byte) in bytes.iter_mut().enumerate() {
312            *byte = u8::conditional_select(&a.bytes[i], &b.bytes[i], choice);
313        }
314
315        Self { bytes }
316    }
317}
318
319impl<C> Copy for EncodedPoint<C>
320where
321    C: Curve,
322    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
323    UncompressedPointSize<C>: ArrayLength<u8>,
324    <UncompressedPointSize<C> as ArrayLength<u8>>::ArrayType: Copy,
325{
326}
327
328impl<C> Debug for EncodedPoint<C>
329where
330    C: Curve,
331    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
332    UncompressedPointSize<C>: ArrayLength<u8>,
333{
334    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335        write!(f, "EncodedPoint<{:?}>({:?})", C::default(), &self.bytes)
336    }
337}
338
339#[cfg(feature = "zeroize")]
340impl<C> Zeroize for EncodedPoint<C>
341where
342    C: Curve,
343    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
344    UncompressedPointSize<C>: ArrayLength<u8>,
345{
346    fn zeroize(&mut self) {
347        self.bytes.zeroize()
348    }
349}
350
351/// Enum representing the coordinates of either compressed or uncompressed
352/// SEC1-encoded elliptic curve points.
353#[derive(Copy, Clone, Debug, Eq, PartialEq)]
354pub enum Coordinates<'a, C: Curve> {
355    /// Identity point (a.k.a. point at infinity)
356    Identity,
357
358    /// Compact curve point
359    Compact {
360        /// x-coordinate
361        x: &'a FieldBytes<C>,
362    },
363
364    /// Compressed curve point
365    Compressed {
366        /// x-coordinate
367        x: &'a FieldBytes<C>,
368
369        /// Is the y-coordinate odd?
370        y_is_odd: bool,
371    },
372
373    /// Uncompressed curve point
374    Uncompressed {
375        /// x-coordinate
376        x: &'a FieldBytes<C>,
377
378        /// y-coordinate
379        y: &'a FieldBytes<C>,
380    },
381}
382
383impl<'a, C: Curve> Coordinates<'a, C> {
384    /// Get the tag octet needed to encode this set of [`Coordinates`]
385    pub fn tag(&self) -> Tag {
386        match self {
387            Coordinates::Compact { .. } => Tag::Compact,
388            Coordinates::Compressed { y_is_odd, .. } => {
389                if *y_is_odd {
390                    Tag::CompressedOddY
391                } else {
392                    Tag::CompressedEvenY
393                }
394            }
395            Coordinates::Identity => Tag::Identity,
396            Coordinates::Uncompressed { .. } => Tag::Uncompressed,
397        }
398    }
399}
400
401/// Tag byte used by the `Elliptic-Curve-Point-to-Octet-String` encoding.
402#[derive(Copy, Clone, Debug, Eq, PartialEq)]
403#[repr(u8)]
404pub enum Tag {
405    /// Identity point (`0x00`)
406    Identity = 0,
407
408    /// Compressed point with even y-coordinate (`0x02`)
409    CompressedEvenY = 2,
410
411    /// Compressed point with odd y-coordinate (`0x03`)
412    CompressedOddY = 3,
413
414    /// Uncompressed point (`0x04`)
415    Uncompressed = 4,
416
417    /// Compact point (`0x05`)
418    Compact = 5,
419}
420
421impl Tag {
422    /// Parse a tag value from a byte
423    pub fn from_u8(byte: u8) -> Result<Self> {
424        match byte {
425            0 => Ok(Tag::Identity),
426            2 => Ok(Tag::CompressedEvenY),
427            3 => Ok(Tag::CompressedOddY),
428            4 => Ok(Tag::Uncompressed),
429            5 => Ok(Tag::Compact),
430            _ => Err(Error),
431        }
432    }
433
434    /// Is this point compact?
435    pub fn is_compact(self) -> bool {
436        matches!(self, Tag::Compact)
437    }
438
439    /// Is this point compressed?
440    pub fn is_compressed(self) -> bool {
441        matches!(self, Tag::CompressedEvenY | Tag::CompressedOddY)
442    }
443
444    /// Is this point the identity point?
445    pub fn is_identity(self) -> bool {
446        self == Tag::Identity
447    }
448
449    /// Compute the expected total message length for a message prefixed
450    /// with this tag (including the tag byte), given the field element size
451    /// (in bytes) for a particular elliptic curve.
452    pub fn message_len(self, field_element_size: usize) -> usize {
453        1 + match self {
454            Tag::Identity => 0,
455            Tag::CompressedEvenY | Tag::CompressedOddY => field_element_size,
456            Tag::Uncompressed => field_element_size * 2,
457            Tag::Compact => field_element_size,
458        }
459    }
460
461    /// Compress the given y-coordinate, returning a `Tag::Compressed*` value
462    fn compress_y(y: &[u8]) -> Self {
463        // Is the y-coordinate odd in the SEC1 sense: `self mod 2 == 1`?
464        if y.as_ref().last().expect("empty y-coordinate") & 1 == 1 {
465            Tag::CompressedOddY
466        } else {
467            Tag::CompressedEvenY
468        }
469    }
470}
471
472impl From<Tag> for u8 {
473    fn from(tag: Tag) -> u8 {
474        tag as u8
475    }
476}
477
478/// Trait for deserializing a value from a SEC1 encoded curve point.
479///
480/// This is intended for use with the `AffinePoint` type for a given elliptic curve.
481pub trait FromEncodedPoint<C>
482where
483    Self: Sized,
484    C: Curve,
485    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
486    UncompressedPointSize<C>: ArrayLength<u8>,
487{
488    /// Deserialize the type this trait is impl'd on from an [`EncodedPoint`].
489    ///
490    /// # Returns
491    ///
492    /// `None` if the [`EncodedPoint`] is invalid.
493    fn from_encoded_point(public_key: &EncodedPoint<C>) -> Option<Self>;
494}
495
496/// Trait for serializing a value to a SEC1 encoded curve point.
497///
498/// This is intended for use with the `AffinePoint` type for a given elliptic curve.
499pub trait ToEncodedPoint<C>
500where
501    C: Curve,
502    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
503    UncompressedPointSize<C>: ArrayLength<u8>,
504{
505    /// Serialize this value as a SEC1 [`EncodedPoint`], optionally applying
506    /// point compression.
507    fn to_encoded_point(&self, compress: bool) -> EncodedPoint<C>;
508}
509
510/// Trait for serializing a value to a SEC1 encoded curve point with compaction.
511///
512/// This is intended for use with the `AffinePoint` type for a given elliptic curve.
513pub trait ToCompactEncodedPoint<C>
514where
515    C: Curve,
516    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
517    UncompressedPointSize<C>: ArrayLength<u8>,
518{
519    /// Serialize this value as a SEC1 [`EncodedPoint`], optionally applying
520    /// point compression.
521    fn to_compact_encoded_point(&self) -> Option<EncodedPoint<C>>;
522}
523
524/// Validate that the given [`EncodedPoint`] represents the encoded public key
525/// value of the given secret.
526///
527/// Curve implementations which also impl [`ProjectiveArithmetic`] will receive
528/// a blanket default impl of this trait.
529#[cfg(feature = "zeroize")]
530#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
531pub trait ValidatePublicKey
532where
533    Self: Curve,
534    UntaggedPointSize<Self>: Add<U1> + ArrayLength<u8>,
535    UncompressedPointSize<Self>: ArrayLength<u8>,
536{
537    /// Validate that the given [`EncodedPoint`] is a valid public key for the
538    /// provided secret value.
539    #[allow(unused_variables)]
540    fn validate_public_key(
541        secret_key: &SecretKey<Self>,
542        public_key: &EncodedPoint<Self>,
543    ) -> Result<()> {
544        // Provide a default "always succeeds" implementation.
545        // This is the intended default for curve implementations which
546        // do not provide an arithmetic implementation, since they have no
547        // way to verify this.
548        //
549        // Implementations with an arithmetic impl will receive a blanket impl
550        // of this trait.
551        Ok(())
552    }
553}
554
555#[cfg(all(feature = "arithmetic", feature = "zeroize"))]
556impl<C> ValidatePublicKey for C
557where
558    C: Curve + ProjectiveArithmetic,
559    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
560    Scalar<C>: Zeroize,
561    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
562    UncompressedPointSize<C>: ArrayLength<u8>,
563{
564    fn validate_public_key(secret_key: &SecretKey<C>, public_key: &EncodedPoint<C>) -> Result<()> {
565        let pk = secret_key
566            .public_key()
567            .to_encoded_point(public_key.is_compressed());
568
569        if public_key == &pk {
570            Ok(())
571        } else {
572            Err(Error)
573        }
574    }
575}
576
577#[cfg(all(test, feature = "dev"))]
578mod tests {
579    use super::{Coordinates, Tag};
580    use crate::dev::MockCurve;
581    use generic_array::GenericArray;
582    use hex_literal::hex;
583    use subtle::ConditionallySelectable;
584
585    type EncodedPoint = super::EncodedPoint<MockCurve>;
586
587    /// Identity point
588    const IDENTITY_BYTES: [u8; 1] = [0];
589
590    /// Example uncompressed point
591    const UNCOMPRESSED_BYTES: [u8; 65] = hex!("0411111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222");
592
593    /// Example compressed point: `UNCOMPRESSED_BYTES` after point compression
594    const COMPRESSED_BYTES: [u8; 33] =
595        hex!("021111111111111111111111111111111111111111111111111111111111111111");
596
597    #[test]
598    fn decode_compressed_point() {
599        // Even y-coordinate
600        let compressed_even_y_bytes =
601            hex!("020100000000000000000000000000000000000000000000000000000000000000");
602
603        let compressed_even_y = EncodedPoint::from_bytes(&compressed_even_y_bytes[..]).unwrap();
604
605        assert!(compressed_even_y.is_compressed());
606        assert_eq!(compressed_even_y.tag(), Tag::CompressedEvenY);
607        assert_eq!(compressed_even_y.len(), 33);
608        assert_eq!(compressed_even_y.as_bytes(), &compressed_even_y_bytes[..]);
609
610        assert_eq!(
611            compressed_even_y.coordinates(),
612            Coordinates::Compressed {
613                x: &hex!("0100000000000000000000000000000000000000000000000000000000000000").into(),
614                y_is_odd: false
615            }
616        );
617
618        assert_eq!(
619            compressed_even_y.x().unwrap(),
620            &hex!("0100000000000000000000000000000000000000000000000000000000000000").into()
621        );
622        assert_eq!(compressed_even_y.y(), None);
623
624        // Odd y-coordinate
625        let compressed_odd_y_bytes =
626            hex!("030200000000000000000000000000000000000000000000000000000000000000");
627
628        let compressed_odd_y = EncodedPoint::from_bytes(&compressed_odd_y_bytes[..]).unwrap();
629
630        assert!(compressed_odd_y.is_compressed());
631        assert_eq!(compressed_odd_y.tag(), Tag::CompressedOddY);
632        assert_eq!(compressed_odd_y.len(), 33);
633        assert_eq!(compressed_odd_y.as_bytes(), &compressed_odd_y_bytes[..]);
634
635        assert_eq!(
636            compressed_odd_y.coordinates(),
637            Coordinates::Compressed {
638                x: &hex!("0200000000000000000000000000000000000000000000000000000000000000").into(),
639                y_is_odd: true
640            }
641        );
642
643        assert_eq!(
644            compressed_odd_y.x().unwrap(),
645            &hex!("0200000000000000000000000000000000000000000000000000000000000000").into()
646        );
647        assert_eq!(compressed_odd_y.y(), None);
648    }
649
650    #[test]
651    fn decode_uncompressed_point() {
652        let uncompressed_point = EncodedPoint::from_bytes(&UNCOMPRESSED_BYTES[..]).unwrap();
653
654        assert!(!uncompressed_point.is_compressed());
655        assert_eq!(uncompressed_point.tag(), Tag::Uncompressed);
656        assert_eq!(uncompressed_point.len(), 65);
657        assert_eq!(uncompressed_point.as_bytes(), &UNCOMPRESSED_BYTES[..]);
658
659        assert_eq!(
660            uncompressed_point.coordinates(),
661            Coordinates::Uncompressed {
662                x: &hex!("1111111111111111111111111111111111111111111111111111111111111111").into(),
663                y: &hex!("2222222222222222222222222222222222222222222222222222222222222222").into()
664            }
665        );
666
667        assert_eq!(
668            uncompressed_point.x().unwrap(),
669            &hex!("1111111111111111111111111111111111111111111111111111111111111111").into()
670        );
671        assert_eq!(
672            uncompressed_point.y().unwrap(),
673            &hex!("2222222222222222222222222222222222222222222222222222222222222222").into()
674        );
675    }
676
677    #[test]
678    fn decode_identity() {
679        let identity_point = EncodedPoint::from_bytes(&IDENTITY_BYTES[..]).unwrap();
680        assert!(identity_point.is_identity());
681        assert_eq!(identity_point.tag(), Tag::Identity);
682        assert_eq!(identity_point.len(), 1);
683        assert_eq!(identity_point.as_bytes(), &IDENTITY_BYTES[..]);
684        assert_eq!(identity_point.coordinates(), Coordinates::Identity);
685        assert_eq!(identity_point.x(), None);
686        assert_eq!(identity_point.y(), None);
687    }
688
689    #[test]
690    fn decode_invalid_tag() {
691        let mut compressed_bytes = COMPRESSED_BYTES.clone();
692        let mut uncompressed_bytes = UNCOMPRESSED_BYTES.clone();
693
694        for bytes in &mut [&mut compressed_bytes[..], &mut uncompressed_bytes[..]] {
695            for tag in 0..=0xFF {
696                // valid tags
697                if tag == 2 || tag == 3 || tag == 4 || tag == 5 {
698                    continue;
699                }
700
701                (*bytes)[0] = tag;
702                let decode_result = EncodedPoint::from_bytes(&*bytes);
703                assert!(decode_result.is_err());
704            }
705        }
706    }
707
708    #[test]
709    fn decode_truncated_point() {
710        for bytes in &[&COMPRESSED_BYTES[..], &UNCOMPRESSED_BYTES[..]] {
711            for len in 0..bytes.len() {
712                let decode_result = EncodedPoint::from_bytes(&bytes[..len]);
713                assert!(decode_result.is_err());
714            }
715        }
716    }
717
718    #[test]
719    fn from_untagged_point() {
720        let untagged_bytes = hex!("11111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222");
721        let uncompressed_point =
722            EncodedPoint::from_untagged_bytes(GenericArray::from_slice(&untagged_bytes[..]));
723        assert_eq!(uncompressed_point.as_bytes(), &UNCOMPRESSED_BYTES[..]);
724    }
725
726    #[test]
727    fn from_affine_coordinates() {
728        let x = hex!("1111111111111111111111111111111111111111111111111111111111111111");
729        let y = hex!("2222222222222222222222222222222222222222222222222222222222222222");
730
731        let uncompressed_point = EncodedPoint::from_affine_coordinates(&x.into(), &y.into(), false);
732        assert_eq!(uncompressed_point.as_bytes(), &UNCOMPRESSED_BYTES[..]);
733
734        let compressed_point = EncodedPoint::from_affine_coordinates(&x.into(), &y.into(), true);
735        assert_eq!(compressed_point.as_bytes(), &COMPRESSED_BYTES[..]);
736    }
737
738    #[test]
739    fn compress() {
740        let uncompressed_point = EncodedPoint::from_bytes(&UNCOMPRESSED_BYTES[..]).unwrap();
741        let compressed_point = uncompressed_point.compress();
742        assert_eq!(compressed_point.as_bytes(), &COMPRESSED_BYTES[..]);
743    }
744
745    #[test]
746    fn conditional_select() {
747        let a = EncodedPoint::from_bytes(&COMPRESSED_BYTES[..]).unwrap();
748        let b = EncodedPoint::from_bytes(&UNCOMPRESSED_BYTES[..]).unwrap();
749
750        let a_selected = EncodedPoint::conditional_select(&a, &b, 0.into());
751        assert_eq!(a, a_selected);
752
753        let b_selected = EncodedPoint::conditional_select(&a, &b, 1.into());
754        assert_eq!(b, b_selected);
755    }
756
757    #[test]
758    fn identity() {
759        let identity_point = EncodedPoint::identity();
760        assert_eq!(identity_point.tag(), Tag::Identity);
761        assert_eq!(identity_point.len(), 1);
762        assert_eq!(identity_point.as_bytes(), &IDENTITY_BYTES[..]);
763
764        // identity is default
765        assert_eq!(identity_point, EncodedPoint::default());
766    }
767
768    #[cfg(feature = "alloc")]
769    #[test]
770    fn to_bytes() {
771        let uncompressed_point = EncodedPoint::from_bytes(&UNCOMPRESSED_BYTES[..]).unwrap();
772        assert_eq!(&*uncompressed_point.to_bytes(), &UNCOMPRESSED_BYTES[..]);
773    }
774}