Skip to main content

elliptic_curve/
public_key.rs

1//! Elliptic curve public keys.
2
3use crate::{
4    consts::U1,
5    sec1::{
6        EncodedPoint, FromEncodedPoint, ToEncodedPoint, UncompressedPointSize, UntaggedPointSize,
7    },
8    weierstrass::{Curve, PointCompression},
9    AffinePoint, Error, NonZeroScalar, ProjectiveArithmetic, ProjectivePoint, Result,
10};
11use core::{
12    cmp::Ordering,
13    convert::{TryFrom, TryInto},
14    fmt::Debug,
15    ops::Add,
16};
17use generic_array::ArrayLength;
18use group::{Curve as _, Group};
19
20#[cfg(feature = "jwk")]
21use crate::{JwkEcKey, JwkParameters};
22
23#[cfg(feature = "pkcs8")]
24use {
25    crate::{AlgorithmParameters, ALGORITHM_OID},
26    pkcs8::FromPublicKey,
27};
28
29#[cfg(feature = "pem")]
30use {core::str::FromStr, pkcs8::ToPublicKey};
31
32#[cfg(any(feature = "jwk", feature = "pem"))]
33use alloc::string::{String, ToString};
34
35/// Elliptic curve public keys.
36///
37/// This is a wrapper type for [`AffinePoint`] which ensures an inner
38/// non-identity point and provides a common place to handle encoding/decoding.
39///
40/// # Parsing "SPKI" Keys
41///
42/// X.509 `SubjectPublicKeyInfo` (SPKI) is a commonly used format for encoding
43/// public keys, notably public keys corresponding to PKCS#8 private keys.
44/// (especially ones generated by OpenSSL).
45///
46/// Keys in SPKI format are either binary (ASN.1 BER/DER), or PEM encoded
47/// (ASCII) and begin with the following:
48///
49/// ```text
50/// -----BEGIN PUBLIC KEY-----
51/// ```
52///
53/// To decode an elliptic curve public key from SPKI, enable the `pkcs8`
54/// feature of this crate (or the `pkcs8` feature of a specific RustCrypto
55/// elliptic curve crate) and use the
56/// [`elliptic_curve::pkcs8::FromPublicKey`][`pkcs8::FromPublicKey`]
57/// trait to parse it.
58///
59/// When the `pem` feature of this crate (or a specific RustCrypto elliptic
60/// curve crate) is enabled, a [`FromStr`] impl is also available.
61#[cfg_attr(docsrs, doc(cfg(feature = "arithmetic")))]
62#[derive(Clone, Debug)]
63pub struct PublicKey<C>
64where
65    C: Curve + ProjectiveArithmetic,
66{
67    point: AffinePoint<C>,
68}
69
70impl<C> PublicKey<C>
71where
72    C: Curve + ProjectiveArithmetic,
73{
74    /// Convert an [`AffinePoint`] into a [`PublicKey`]
75    pub fn from_affine(point: AffinePoint<C>) -> Result<Self> {
76        if ProjectivePoint::<C>::from(point).is_identity().into() {
77            Err(Error)
78        } else {
79            Ok(Self { point })
80        }
81    }
82
83    /// Compute a [`PublicKey`] from a secret [`NonZeroScalar`] value
84    /// (i.e. a secret key represented as a raw scalar value)
85    pub fn from_secret_scalar(scalar: &NonZeroScalar<C>) -> Self {
86        // `NonZeroScalar` ensures the resulting point is not the identity
87        Self {
88            point: (C::ProjectivePoint::generator() * scalar.as_ref()).to_affine(),
89        }
90    }
91
92    /// Decode [`PublicKey`] (compressed or uncompressed) from the
93    /// `Elliptic-Curve-Point-to-Octet-String` encoding described in
94    /// SEC 1: Elliptic Curve Cryptography (Version 2.0) section
95    /// 2.3.3 (page 10).
96    ///
97    /// <http://www.secg.org/sec1-v2.pdf>
98    pub fn from_sec1_bytes(bytes: &[u8]) -> Result<Self>
99    where
100        Self: TryFrom<EncodedPoint<C>, Error = Error>,
101        UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
102        UncompressedPointSize<C>: ArrayLength<u8>,
103    {
104        EncodedPoint::from_bytes(bytes)
105            .map_err(|_| Error)
106            .and_then(TryInto::try_into)
107    }
108
109    /// Borrow the inner [`AffinePoint`] from this [`PublicKey`].
110    ///
111    /// In ECC, public keys are elliptic curve points.
112    pub fn as_affine(&self) -> &AffinePoint<C> {
113        &self.point
114    }
115
116    /// Convert this [`PublicKey`] to a [`ProjectivePoint`] for the given curve
117    pub fn to_projective(&self) -> ProjectivePoint<C> {
118        self.point.clone().into()
119    }
120
121    /// Parse a [`JwkEcKey`] JSON Web Key (JWK) into a [`PublicKey`].
122    #[cfg(feature = "jwk")]
123    #[cfg_attr(docsrs, doc(cfg(feature = "jwk")))]
124    pub fn from_jwk(jwk: &JwkEcKey) -> Result<Self>
125    where
126        C: JwkParameters,
127        AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
128        UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
129        UncompressedPointSize<C>: ArrayLength<u8>,
130    {
131        jwk.try_into()
132    }
133
134    /// Parse a string containing a JSON Web Key (JWK) into a [`PublicKey`].
135    #[cfg(feature = "jwk")]
136    #[cfg_attr(docsrs, doc(cfg(feature = "jwk")))]
137    pub fn from_jwk_str(jwk: &str) -> Result<Self>
138    where
139        C: JwkParameters,
140        AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
141        UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
142        UncompressedPointSize<C>: ArrayLength<u8>,
143    {
144        jwk.parse::<JwkEcKey>().and_then(|jwk| Self::from_jwk(&jwk))
145    }
146
147    /// Serialize this public key as [`JwkEcKey`] JSON Web Key (JWK).
148    #[cfg(feature = "jwk")]
149    #[cfg_attr(docsrs, doc(cfg(feature = "jwk")))]
150    pub fn to_jwk(&self) -> JwkEcKey
151    where
152        C: JwkParameters,
153        AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
154        UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
155        UncompressedPointSize<C>: ArrayLength<u8>,
156    {
157        self.into()
158    }
159
160    /// Serialize this public key as JSON Web Key (JWK) string.
161    #[cfg(feature = "jwk")]
162    #[cfg_attr(docsrs, doc(cfg(feature = "jwk")))]
163    pub fn to_jwk_string(&self) -> String
164    where
165        C: JwkParameters,
166        AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
167        UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
168        UncompressedPointSize<C>: ArrayLength<u8>,
169    {
170        self.to_jwk().to_string()
171    }
172}
173
174impl<C> AsRef<AffinePoint<C>> for PublicKey<C>
175where
176    C: Curve + ProjectiveArithmetic,
177{
178    fn as_ref(&self) -> &AffinePoint<C> {
179        self.as_affine()
180    }
181}
182
183impl<C> Copy for PublicKey<C> where C: Curve + ProjectiveArithmetic {}
184
185impl<C> TryFrom<EncodedPoint<C>> for PublicKey<C>
186where
187    C: Curve + ProjectiveArithmetic,
188    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
189    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
190    UncompressedPointSize<C>: ArrayLength<u8>,
191{
192    type Error = Error;
193
194    fn try_from(encoded_point: EncodedPoint<C>) -> Result<Self> {
195        encoded_point.decode()
196    }
197}
198
199impl<C> TryFrom<&EncodedPoint<C>> for PublicKey<C>
200where
201    C: Curve + ProjectiveArithmetic,
202    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
203    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
204    UncompressedPointSize<C>: ArrayLength<u8>,
205{
206    type Error = Error;
207
208    fn try_from(encoded_point: &EncodedPoint<C>) -> Result<Self> {
209        encoded_point.decode()
210    }
211}
212
213impl<C> From<PublicKey<C>> for EncodedPoint<C>
214where
215    C: Curve + ProjectiveArithmetic + PointCompression,
216    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
217    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
218    UncompressedPointSize<C>: ArrayLength<u8>,
219{
220    fn from(public_key: PublicKey<C>) -> EncodedPoint<C> {
221        EncodedPoint::<C>::from(&public_key)
222    }
223}
224
225impl<C> From<&PublicKey<C>> for EncodedPoint<C>
226where
227    C: Curve + ProjectiveArithmetic + PointCompression,
228    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
229    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
230    UncompressedPointSize<C>: ArrayLength<u8>,
231{
232    fn from(public_key: &PublicKey<C>) -> EncodedPoint<C> {
233        public_key.to_encoded_point(C::COMPRESS_POINTS)
234    }
235}
236
237impl<C> FromEncodedPoint<C> for PublicKey<C>
238where
239    C: Curve + ProjectiveArithmetic,
240    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
241    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
242    UncompressedPointSize<C>: ArrayLength<u8>,
243{
244    /// Initialize [`PublicKey`] from an [`EncodedPoint`]
245    fn from_encoded_point(encoded_point: &EncodedPoint<C>) -> Option<Self> {
246        AffinePoint::<C>::from_encoded_point(encoded_point)
247            .and_then(|point| PublicKey::from_affine(point).ok())
248    }
249}
250
251impl<C> ToEncodedPoint<C> for PublicKey<C>
252where
253    C: Curve + ProjectiveArithmetic,
254    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
255    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
256    UncompressedPointSize<C>: ArrayLength<u8>,
257{
258    /// Serialize this [`PublicKey`] as a SEC1 [`EncodedPoint`], optionally applying
259    /// point compression
260    fn to_encoded_point(&self, compress: bool) -> EncodedPoint<C> {
261        self.point.to_encoded_point(compress)
262    }
263}
264
265impl<C> Eq for PublicKey<C>
266where
267    C: Curve + ProjectiveArithmetic,
268    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
269    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
270    UncompressedPointSize<C>: ArrayLength<u8>,
271{
272}
273
274impl<C> PartialEq for PublicKey<C>
275where
276    C: Curve + ProjectiveArithmetic,
277    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
278    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
279    UncompressedPointSize<C>: ArrayLength<u8>,
280{
281    fn eq(&self, other: &Self) -> bool {
282        self.cmp(other) == Ordering::Equal
283    }
284}
285
286impl<C> PartialOrd for PublicKey<C>
287where
288    C: Curve + ProjectiveArithmetic,
289    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
290    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
291    UncompressedPointSize<C>: ArrayLength<u8>,
292{
293    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
294        Some(self.cmp(other))
295    }
296}
297
298impl<C> Ord for PublicKey<C>
299where
300    C: Curve + ProjectiveArithmetic,
301    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
302    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
303    UncompressedPointSize<C>: ArrayLength<u8>,
304{
305    fn cmp(&self, other: &Self) -> Ordering {
306        // TODO(tarcieri): more efficient implementation?
307        // This is implemented this way to reduce bounds for `AffinePoint<C>`
308        self.to_encoded_point(false)
309            .cmp(&other.to_encoded_point(false))
310    }
311}
312
313#[cfg(feature = "pkcs8")]
314#[cfg_attr(docsrs, doc(cfg(feature = "pkcs8")))]
315impl<C> FromPublicKey for PublicKey<C>
316where
317    Self: TryFrom<EncodedPoint<C>, Error = Error>,
318    C: Curve + AlgorithmParameters + ProjectiveArithmetic,
319    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
320    UncompressedPointSize<C>: ArrayLength<u8>,
321{
322    fn from_spki(spki: pkcs8::SubjectPublicKeyInfo<'_>) -> pkcs8::Result<Self> {
323        if spki.algorithm.oid != ALGORITHM_OID {
324            return Err(pkcs8::der::ErrorKind::UnknownOid {
325                oid: spki.algorithm.oid,
326            }
327            .into());
328        }
329
330        let params_oid = spki.algorithm.parameters_oid()?;
331
332        if params_oid != C::OID {
333            return Err(pkcs8::der::ErrorKind::UnknownOid { oid: params_oid }.into());
334        }
335
336        Self::from_sec1_bytes(&spki.subject_public_key)
337            .map_err(|_| pkcs8::der::Tag::BitString.value_error().into())
338    }
339}
340
341#[cfg(feature = "pem")]
342#[cfg_attr(docsrs, doc(cfg(feature = "pem")))]
343impl<C> ToPublicKey for PublicKey<C>
344where
345    C: Curve + AlgorithmParameters + ProjectiveArithmetic,
346    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
347    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
348    UncompressedPointSize<C>: ArrayLength<u8>,
349{
350    fn to_public_key_der(&self) -> pkcs8::Result<pkcs8::PublicKeyDocument> {
351        let public_key_bytes = self.to_encoded_point(false);
352
353        Ok(pkcs8::SubjectPublicKeyInfo {
354            algorithm: C::algorithm_identifier(),
355            subject_public_key: public_key_bytes.as_ref(),
356        }
357        .into())
358    }
359}
360
361#[cfg(feature = "pem")]
362#[cfg_attr(docsrs, doc(cfg(feature = "pem")))]
363impl<C> FromStr for PublicKey<C>
364where
365    Self: TryFrom<EncodedPoint<C>, Error = Error>,
366    C: Curve + AlgorithmParameters + ProjectiveArithmetic,
367    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
368    UncompressedPointSize<C>: ArrayLength<u8>,
369{
370    type Err = Error;
371
372    fn from_str(s: &str) -> Result<Self> {
373        Self::from_public_key_pem(s).map_err(|_| Error)
374    }
375}
376
377#[cfg(feature = "pem")]
378#[cfg_attr(docsrs, doc(cfg(feature = "pem")))]
379impl<C> ToString for PublicKey<C>
380where
381    C: Curve + AlgorithmParameters + ProjectiveArithmetic,
382    AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
383    UntaggedPointSize<C>: Add<U1> + ArrayLength<u8>,
384    UncompressedPointSize<C>: ArrayLength<u8>,
385{
386    fn to_string(&self) -> String {
387        self.to_public_key_pem().expect("PEM encoding error")
388    }
389}
390
391#[cfg(all(feature = "dev", test))]
392mod tests {
393    use crate::{dev::MockCurve, sec1::FromEncodedPoint};
394
395    type EncodedPoint = crate::sec1::EncodedPoint<MockCurve>;
396    type PublicKey = super::PublicKey<MockCurve>;
397
398    #[test]
399    fn from_encoded_point_rejects_identity() {
400        let identity = EncodedPoint::identity();
401        assert_eq!(PublicKey::from_encoded_point(&identity), None);
402    }
403}