1use 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
31pub type CompressedPointSize<C> = <FieldSize<C> as Add<U1>>::Output;
35
36pub type UncompressedPointSize<C> = <UntaggedPointSize<C> as Add<U1>>::Output;
40
41pub type UntaggedPointSize<C> = <FieldSize<C> as Add>::Output;
43
44#[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 pub fn from_bytes(input: impl AsRef<[u8]>) -> Result<Self> {
73 let input = input.as_ref();
74
75 let tag = input.first().cloned().ok_or(Error).and_then(Tag::from_u8)?;
77
78 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 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 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 #[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 pub fn identity() -> Self {
139 Self::default()
140 }
141
142 pub fn len(&self) -> usize {
144 self.tag().message_len(C::UInt::BYTE_SIZE)
145 }
146
147 pub fn as_bytes(&self) -> &[u8] {
149 &self.bytes[..self.len()]
150 }
151
152 #[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 #[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 pub fn is_compact(&self) -> bool {
177 self.tag().is_compact()
178 }
179
180 pub fn is_compressed(&self) -> bool {
182 self.tag().is_compressed()
183 }
184
185 pub fn is_identity(&self) -> bool {
187 self.tag().is_identity()
188 }
189
190 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 #[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 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 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 pub fn tag(&self) -> Tag {
237 Tag::from_u8(self.bytes[0]).expect("invalid tag")
239 }
240
241 #[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 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 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#[derive(Copy, Clone, Debug, Eq, PartialEq)]
354pub enum Coordinates<'a, C: Curve> {
355 Identity,
357
358 Compact {
360 x: &'a FieldBytes<C>,
362 },
363
364 Compressed {
366 x: &'a FieldBytes<C>,
368
369 y_is_odd: bool,
371 },
372
373 Uncompressed {
375 x: &'a FieldBytes<C>,
377
378 y: &'a FieldBytes<C>,
380 },
381}
382
383impl<'a, C: Curve> Coordinates<'a, C> {
384 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#[derive(Copy, Clone, Debug, Eq, PartialEq)]
403#[repr(u8)]
404pub enum Tag {
405 Identity = 0,
407
408 CompressedEvenY = 2,
410
411 CompressedOddY = 3,
413
414 Uncompressed = 4,
416
417 Compact = 5,
419}
420
421impl Tag {
422 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 pub fn is_compact(self) -> bool {
436 matches!(self, Tag::Compact)
437 }
438
439 pub fn is_compressed(self) -> bool {
441 matches!(self, Tag::CompressedEvenY | Tag::CompressedOddY)
442 }
443
444 pub fn is_identity(self) -> bool {
446 self == Tag::Identity
447 }
448
449 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 fn compress_y(y: &[u8]) -> Self {
463 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
478pub trait FromEncodedPoint<C>
482where
483 Self: Sized,
484 C: Curve,
485 UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
486 UncompressedPointSize<C>: ArrayLength<u8>,
487{
488 fn from_encoded_point(public_key: &EncodedPoint<C>) -> Option<Self>;
494}
495
496pub trait ToEncodedPoint<C>
500where
501 C: Curve,
502 UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
503 UncompressedPointSize<C>: ArrayLength<u8>,
504{
505 fn to_encoded_point(&self, compress: bool) -> EncodedPoint<C>;
508}
509
510pub trait ToCompactEncodedPoint<C>
514where
515 C: Curve,
516 UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
517 UncompressedPointSize<C>: ArrayLength<u8>,
518{
519 fn to_compact_encoded_point(&self) -> Option<EncodedPoint<C>>;
522}
523
524#[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 #[allow(unused_variables)]
540 fn validate_public_key(
541 secret_key: &SecretKey<Self>,
542 public_key: &EncodedPoint<Self>,
543 ) -> Result<()> {
544 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 const IDENTITY_BYTES: [u8; 1] = [0];
589
590 const UNCOMPRESSED_BYTES: [u8; 65] = hex!("0411111111111111111111111111111111111111111111111111111111111111112222222222222222222222222222222222222222222222222222222222222222");
592
593 const COMPRESSED_BYTES: [u8; 33] =
595 hex!("021111111111111111111111111111111111111111111111111111111111111111");
596
597 #[test]
598 fn decode_compressed_point() {
599 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 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 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 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}