1use 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#[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 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 pub fn from_secret_scalar(scalar: &NonZeroScalar<C>) -> Self {
86 Self {
88 point: (C::ProjectivePoint::generator() * scalar.as_ref()).to_affine(),
89 }
90 }
91
92 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 pub fn as_affine(&self) -> &AffinePoint<C> {
113 &self.point
114 }
115
116 pub fn to_projective(&self) -> ProjectivePoint<C> {
118 self.point.clone().into()
119 }
120
121 #[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 #[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 #[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 #[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 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 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 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}