Skip to main content

p256/arithmetic/
affine.rs

1//! Affine points
2
3use super::{FieldElement, ProjectivePoint, CURVE_EQUATION_A, CURVE_EQUATION_B, MODULUS};
4use crate::{CompressedPoint, EncodedPoint, FieldBytes, NistP256, Scalar};
5use core::ops::{Mul, Neg};
6use elliptic_curve::{
7    generic_array::arr,
8    group::{prime::PrimeCurveAffine, GroupEncoding},
9    sec1::{self, FromEncodedPoint, ToEncodedPoint},
10    subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption},
11    weierstrass::DecompressPoint,
12    AffineArithmetic,
13};
14
15#[cfg(feature = "zeroize")]
16use elliptic_curve::zeroize::Zeroize;
17
18impl AffineArithmetic for NistP256 {
19    type AffinePoint = AffinePoint;
20}
21
22/// A point on the secp256r1 curve in affine coordinates.
23#[derive(Clone, Copy, Debug)]
24#[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
25pub struct AffinePoint {
26    pub(crate) x: FieldElement,
27    pub(crate) y: FieldElement,
28    pub(super) infinity: Choice,
29}
30
31impl PrimeCurveAffine for AffinePoint {
32    type Scalar = Scalar;
33    type Curve = ProjectivePoint;
34
35    /// Returns the identity of the group: the point at infinity.
36    fn identity() -> AffinePoint {
37        Self {
38            x: FieldElement::zero(),
39            y: FieldElement::zero(),
40            infinity: Choice::from(1),
41        }
42    }
43
44    /// Returns the base point of P-256.
45    fn generator() -> AffinePoint {
46        // NIST P-256 basepoint in affine coordinates:
47        // x = 6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296
48        // y = 4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5
49        AffinePoint {
50            x: FieldElement::from_bytes(&arr![u8;
51                0x6b, 0x17, 0xd1, 0xf2, 0xe1, 0x2c, 0x42, 0x47, 0xf8, 0xbc, 0xe6, 0xe5, 0x63, 0xa4,
52                0x40, 0xf2, 0x77, 0x03, 0x7d, 0x81, 0x2d, 0xeb, 0x33, 0xa0, 0xf4, 0xa1, 0x39, 0x45,
53                0xd8, 0x98, 0xc2, 0x96
54            ])
55            .unwrap(),
56            y: FieldElement::from_bytes(&arr![u8;
57                0x4f, 0xe3, 0x42, 0xe2, 0xfe, 0x1a, 0x7f, 0x9b, 0x8e, 0xe7, 0xeb, 0x4a, 0x7c, 0x0f,
58                0x9e, 0x16, 0x2b, 0xce, 0x33, 0x57, 0x6b, 0x31, 0x5e, 0xce, 0xcb, 0xb6, 0x40, 0x68,
59                0x37, 0xbf, 0x51, 0xf5
60            ])
61            .unwrap(),
62            infinity: Choice::from(0),
63        }
64    }
65
66    /// Is this point the identity point?
67    fn is_identity(&self) -> Choice {
68        self.infinity
69    }
70
71    /// Convert to curve representation.
72    fn to_curve(&self) -> ProjectivePoint {
73        ProjectivePoint::from(*self)
74    }
75}
76
77impl ConditionallySelectable for AffinePoint {
78    fn conditional_select(a: &AffinePoint, b: &AffinePoint, choice: Choice) -> AffinePoint {
79        AffinePoint {
80            x: FieldElement::conditional_select(&a.x, &b.x, choice),
81            y: FieldElement::conditional_select(&a.y, &b.y, choice),
82            infinity: Choice::conditional_select(&a.infinity, &b.infinity, choice),
83        }
84    }
85}
86
87impl ConstantTimeEq for AffinePoint {
88    fn ct_eq(&self, other: &AffinePoint) -> Choice {
89        self.x.ct_eq(&other.x) & self.y.ct_eq(&other.y) & self.infinity.ct_eq(&other.infinity)
90    }
91}
92
93impl Default for AffinePoint {
94    fn default() -> Self {
95        Self::identity()
96    }
97}
98
99impl PartialEq for AffinePoint {
100    fn eq(&self, other: &AffinePoint) -> bool {
101        self.ct_eq(other).into()
102    }
103}
104
105impl Eq for AffinePoint {}
106
107impl AffinePoint {
108    fn decode(encoded_point: &EncodedPoint) -> CtOption<Self> {
109        match encoded_point.coordinates() {
110            sec1::Coordinates::Identity => CtOption::new(Self::identity(), 1.into()),
111            sec1::Coordinates::Compact { .. } => {
112                // TODO(tarcieri): add decompaction support
113                CtOption::new(Self::default(), 0.into())
114            }
115            sec1::Coordinates::Compressed { x, y_is_odd } => {
116                AffinePoint::decompress(x, Choice::from(y_is_odd as u8))
117            }
118            sec1::Coordinates::Uncompressed { x, y } => {
119                let x = FieldElement::from_bytes(x);
120                let y = FieldElement::from_bytes(y);
121
122                x.and_then(|x| {
123                    y.and_then(|y| {
124                        // Check that the point is on the curve
125                        let lhs = y * &y;
126                        let rhs = x * &x * &x + &(CURVE_EQUATION_A * &x) + &CURVE_EQUATION_B;
127                        let point = AffinePoint {
128                            x,
129                            y,
130                            infinity: Choice::from(0),
131                        };
132                        CtOption::new(point, lhs.ct_eq(&rhs))
133                    })
134                })
135            }
136        }
137    }
138}
139
140impl DecompressPoint<NistP256> for AffinePoint {
141    fn decompress(x_bytes: &FieldBytes, y_is_odd: Choice) -> CtOption<Self> {
142        FieldElement::from_bytes(x_bytes).and_then(|x| {
143            let alpha = x * &x * &x + &(CURVE_EQUATION_A * &x) + &CURVE_EQUATION_B;
144            let beta = alpha.sqrt();
145
146            beta.map(|beta| {
147                let y = FieldElement::conditional_select(
148                    &(MODULUS - &beta),
149                    &beta,
150                    beta.is_odd().ct_eq(&y_is_odd),
151                );
152
153                Self {
154                    x,
155                    y,
156                    infinity: Choice::from(0),
157                }
158            })
159        })
160    }
161}
162
163impl GroupEncoding for AffinePoint {
164    type Repr = CompressedPoint;
165
166    fn from_bytes(bytes: &Self::Repr) -> CtOption<Self> {
167        let tag = bytes[0];
168        let y_is_odd = tag.ct_eq(&sec1::Tag::CompressedOddY.into());
169        let is_compressed_point = y_is_odd | tag.ct_eq(&sec1::Tag::CompressedEvenY.into());
170        Self::decompress(FieldBytes::from_slice(&bytes[1..]), y_is_odd)
171            .and_then(|point| CtOption::new(point, is_compressed_point))
172    }
173
174    fn from_bytes_unchecked(bytes: &Self::Repr) -> CtOption<Self> {
175        // No unchecked conversion possible for compressed points
176        Self::from_bytes(bytes)
177    }
178
179    fn to_bytes(&self) -> Self::Repr {
180        CompressedPoint::clone_from_slice(self.to_encoded_point(true).as_bytes())
181    }
182}
183
184impl FromEncodedPoint<NistP256> for AffinePoint {
185    /// Attempts to parse the given [`EncodedPoint`] as an SEC1-encoded [`AffinePoint`].
186    ///
187    /// # Returns
188    ///
189    /// `None` value if `encoded_point` is not on the secp256r1 curve.
190    fn from_encoded_point(encoded_point: &EncodedPoint) -> Option<Self> {
191        Self::decode(encoded_point).into()
192    }
193}
194
195impl ToEncodedPoint<NistP256> for AffinePoint {
196    fn to_encoded_point(&self, compress: bool) -> EncodedPoint {
197        EncodedPoint::conditional_select(
198            &EncodedPoint::from_affine_coordinates(
199                &self.x.to_bytes(),
200                &self.y.to_bytes(),
201                compress,
202            ),
203            &EncodedPoint::identity(),
204            self.infinity,
205        )
206    }
207}
208
209impl From<AffinePoint> for EncodedPoint {
210    /// Returns the SEC1 compressed encoding of this point.
211    fn from(affine_point: AffinePoint) -> EncodedPoint {
212        affine_point.to_encoded_point(false)
213    }
214}
215
216impl Mul<Scalar> for AffinePoint {
217    type Output = ProjectivePoint;
218
219    fn mul(self, scalar: Scalar) -> ProjectivePoint {
220        ProjectivePoint::from(self) * scalar
221    }
222}
223
224impl Mul<&Scalar> for AffinePoint {
225    type Output = ProjectivePoint;
226
227    fn mul(self, scalar: &Scalar) -> ProjectivePoint {
228        ProjectivePoint::from(self) * scalar
229    }
230}
231
232impl Neg for AffinePoint {
233    type Output = AffinePoint;
234
235    fn neg(self) -> Self::Output {
236        AffinePoint {
237            x: self.x,
238            y: -self.y,
239            infinity: self.infinity,
240        }
241    }
242}
243
244#[cfg(feature = "zeroize")]
245impl Zeroize for AffinePoint {
246    fn zeroize(&mut self) {
247        self.x.zeroize();
248        self.y.zeroize();
249    }
250}
251
252#[cfg(test)]
253mod tests {
254    use super::AffinePoint;
255    use crate::EncodedPoint;
256    use elliptic_curve::{
257        group::prime::PrimeCurveAffine,
258        sec1::{FromEncodedPoint, ToEncodedPoint},
259    };
260    use hex_literal::hex;
261
262    const UNCOMPRESSED_BASEPOINT: &[u8] = &hex!(
263        "046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296
264         4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"
265    );
266
267    const COMPRESSED_BASEPOINT: &[u8] =
268        &hex!("036B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296");
269
270    #[test]
271    fn uncompressed_round_trip() {
272        let pubkey = EncodedPoint::from_bytes(UNCOMPRESSED_BASEPOINT).unwrap();
273        let point = AffinePoint::from_encoded_point(&pubkey).unwrap();
274        assert_eq!(point, AffinePoint::generator());
275
276        let res: EncodedPoint = point.into();
277        assert_eq!(res, pubkey);
278    }
279
280    #[test]
281    fn compressed_round_trip() {
282        let pubkey = EncodedPoint::from_bytes(COMPRESSED_BASEPOINT).unwrap();
283        let point = AffinePoint::from_encoded_point(&pubkey).unwrap();
284        assert_eq!(point, AffinePoint::generator());
285
286        let res: EncodedPoint = point.to_encoded_point(true);
287        assert_eq!(res, pubkey);
288    }
289
290    #[test]
291    fn uncompressed_to_compressed() {
292        let encoded = EncodedPoint::from_bytes(UNCOMPRESSED_BASEPOINT).unwrap();
293
294        let res = AffinePoint::from_encoded_point(&encoded)
295            .unwrap()
296            .to_encoded_point(true);
297
298        assert_eq!(res.as_bytes(), COMPRESSED_BASEPOINT);
299    }
300
301    #[test]
302    fn compressed_to_uncompressed() {
303        let encoded = EncodedPoint::from_bytes(COMPRESSED_BASEPOINT).unwrap();
304
305        let res = AffinePoint::from_encoded_point(&encoded)
306            .unwrap()
307            .to_encoded_point(false);
308
309        assert_eq!(res.as_bytes(), UNCOMPRESSED_BASEPOINT);
310    }
311
312    #[test]
313    fn decompress() {
314        let encoded = EncodedPoint::from_bytes(COMPRESSED_BASEPOINT).unwrap();
315        let decompressed = encoded.decompress().unwrap();
316        assert_eq!(decompressed.as_bytes(), UNCOMPRESSED_BASEPOINT);
317    }
318
319    #[test]
320    fn affine_negation() {
321        let basepoint = AffinePoint::generator();
322        assert_eq!(-(-basepoint), basepoint);
323    }
324}