Skip to main content

ed25519_dalek/
verifying.rs

1// -*- mode: rust; -*-
2//
3// This file is part of ed25519-dalek.
4// Copyright (c) 2017-2019 isis lovecruft
5// See LICENSE for licensing information.
6//
7// Authors:
8// - isis agora lovecruft <isis@patternsinthevoid.net>
9
10//! ed25519 public keys.
11
12#[cfg(feature = "digest")]
13use curve25519_dalek::digest::{common::KeySizeUser, typenum::U32};
14
15use core::fmt::Debug;
16use core::hash::{Hash, Hasher};
17
18use curve25519_dalek::{
19    digest::{Digest, array::typenum::U64},
20    edwards::{CompressedEdwardsY, EdwardsPoint},
21    montgomery::MontgomeryPoint,
22    scalar::Scalar,
23};
24
25use ed25519::signature::{MultipartVerifier, Verifier};
26
27use sha2::Sha512;
28
29#[cfg(feature = "pkcs8")]
30use ed25519::pkcs8;
31
32#[cfg(feature = "serde")]
33use serde::{Deserialize, Deserializer, Serialize, Serializer};
34
35#[cfg(feature = "digest")]
36use crate::context::Context;
37#[cfg(feature = "digest")]
38use curve25519_dalek::digest::Update;
39#[cfg(feature = "digest")]
40use signature::DigestVerifier;
41
42use crate::{
43    constants::PUBLIC_KEY_LENGTH,
44    errors::{InternalError, SignatureError},
45    hazmat::ExpandedSecretKey,
46    signature::InternalSignature,
47    signing::SigningKey,
48};
49
50#[cfg(feature = "hazmat")]
51mod stream;
52#[cfg(feature = "hazmat")]
53pub use self::stream::StreamVerifier;
54
55/// An ed25519 public key.
56///
57/// # Note
58///
59/// The `Eq` and `Hash` impls here use the compressed Edwards y encoding, _not_ the algebraic
60/// representation. This means if this `VerifyingKey` is non-canonically encoded, it will be
61/// considered unequal to the other equivalent encoding, despite the two representing the same
62/// point. More encoding details can be found
63/// [here](https://hdevalence.ca/blog/2020-10-04-its-25519am).
64/// If you want to make sure that signatures produced with respect to those sorts of public keys
65/// are rejected, use [`VerifyingKey::verify_strict`].
66// Invariant: VerifyingKey.1 is always the decompression of VerifyingKey.0
67#[derive(Copy, Clone, Default, Eq)]
68pub struct VerifyingKey {
69    /// Serialized compressed Edwards-y point.
70    pub(crate) compressed: CompressedEdwardsY,
71
72    /// Decompressed Edwards point used for curve arithmetic operations.
73    pub(crate) point: EdwardsPoint,
74}
75
76impl Debug for VerifyingKey {
77    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
78        write!(f, "VerifyingKey({:?}), {:?})", self.compressed, self.point)
79    }
80}
81
82impl AsRef<[u8]> for VerifyingKey {
83    fn as_ref(&self) -> &[u8] {
84        self.as_bytes()
85    }
86}
87
88impl Hash for VerifyingKey {
89    fn hash<H: Hasher>(&self, state: &mut H) {
90        self.as_bytes().hash(state);
91    }
92}
93
94impl PartialEq<VerifyingKey> for VerifyingKey {
95    fn eq(&self, other: &VerifyingKey) -> bool {
96        self.as_bytes() == other.as_bytes()
97    }
98}
99
100impl From<&ExpandedSecretKey> for VerifyingKey {
101    /// Derive this public key from its corresponding `ExpandedSecretKey`.
102    fn from(expanded_secret_key: &ExpandedSecretKey) -> VerifyingKey {
103        VerifyingKey::from(EdwardsPoint::mul_base(&expanded_secret_key.scalar))
104    }
105}
106
107impl From<&SigningKey> for VerifyingKey {
108    fn from(signing_key: &SigningKey) -> VerifyingKey {
109        signing_key.verifying_key()
110    }
111}
112
113impl From<EdwardsPoint> for VerifyingKey {
114    fn from(point: EdwardsPoint) -> VerifyingKey {
115        VerifyingKey {
116            point,
117            compressed: point.compress(),
118        }
119    }
120}
121
122#[cfg(feature = "digest")]
123impl KeySizeUser for VerifyingKey {
124    type KeySize = U32;
125}
126
127impl VerifyingKey {
128    /// Convert this public key to a byte array.
129    #[inline]
130    pub fn to_bytes(&self) -> [u8; PUBLIC_KEY_LENGTH] {
131        self.compressed.to_bytes()
132    }
133
134    /// View this public key as a byte array.
135    #[inline]
136    pub fn as_bytes(&self) -> &[u8; PUBLIC_KEY_LENGTH] {
137        &(self.compressed).0
138    }
139
140    /// Construct a `VerifyingKey` from a slice of bytes.
141    ///
142    /// Verifies the point is valid under [ZIP-215] rules. RFC 8032 / NIST point validation criteria
143    /// are currently unsupported (see [dalek-cryptography/curve25519-dalek#626]).
144    ///
145    /// # Example
146    ///
147    /// ```
148    /// use ed25519_dalek::VerifyingKey;
149    /// use ed25519_dalek::PUBLIC_KEY_LENGTH;
150    /// use ed25519_dalek::SignatureError;
151    ///
152    /// # fn doctest() -> Result<VerifyingKey, SignatureError> {
153    /// let public_key_bytes: [u8; PUBLIC_KEY_LENGTH] = [
154    ///    215,  90, 152,   1, 130, 177,  10, 183, 213,  75, 254, 211, 201, 100,   7,  58,
155    ///     14, 225, 114, 243, 218, 166,  35,  37, 175,   2,  26, 104, 247,   7,   81, 26];
156    ///
157    /// let public_key = VerifyingKey::from_bytes(&public_key_bytes)?;
158    /// #
159    /// # Ok(public_key)
160    /// # }
161    /// #
162    /// # fn main() {
163    /// #     doctest();
164    /// # }
165    /// ```
166    ///
167    /// # Returns
168    ///
169    /// A `Result` whose okay value is an EdDSA `VerifyingKey` or whose error value
170    /// is a `SignatureError` describing the error that occurred.
171    ///
172    /// [ZIP-215]: https://zips.z.cash/zip-0215
173    /// [dalek-cryptography/curve25519-dalek#626]: https://github.com/dalek-cryptography/curve25519-dalek/issues/626
174    #[inline]
175    pub fn from_bytes(bytes: &[u8; PUBLIC_KEY_LENGTH]) -> Result<VerifyingKey, SignatureError> {
176        let compressed = CompressedEdwardsY(*bytes);
177        let point = compressed
178            .decompress()
179            .ok_or(InternalError::PointDecompression)?;
180
181        // Invariant: VerifyingKey.1 is always the decompression of VerifyingKey.0
182        Ok(VerifyingKey { compressed, point })
183    }
184
185    /// Create a verifying context that can be used for Ed25519ph with
186    /// [`DigestVerifier`].
187    #[cfg(feature = "digest")]
188    pub fn with_context<'k, 'v>(
189        &'k self,
190        context_value: &'v [u8],
191    ) -> Result<Context<'k, 'v, Self>, SignatureError> {
192        Context::new(self, context_value)
193    }
194
195    /// Returns whether this is a _weak_ public key, i.e., if this public key has low order.
196    ///
197    /// A weak public key can be used to generate a signature that's valid for almost every
198    /// message. [`Self::verify_strict`] denies weak keys, but if you want to check for this
199    /// property before verification, then use this method.
200    pub fn is_weak(&self) -> bool {
201        self.point.is_small_order()
202    }
203
204    /// The ordinary non-batched Ed25519 verification check, rejecting non-canonical R values. (see
205    /// [`Self::RCompute`]). `CtxDigest` is the digest used to calculate the pseudorandomness
206    /// needed for signing. According to the spec, `CtxDigest = Sha512`.
207    ///
208    /// This definition is loose in its parameters so that end-users of the `hazmat` module can
209    /// change how the `ExpandedSecretKey` is calculated and which hash function to use.
210    #[allow(non_snake_case)]
211    pub(crate) fn raw_verify<CtxDigest>(
212        &self,
213        message: &[&[u8]],
214        signature: &ed25519::Signature,
215    ) -> Result<(), SignatureError>
216    where
217        CtxDigest: Digest<OutputSize = U64>,
218    {
219        let signature = InternalSignature::try_from(signature)?;
220
221        let expected_R = RCompute::<CtxDigest>::compute(self, signature, None, message);
222        if expected_R == signature.R {
223            Ok(())
224        } else {
225            Err(InternalError::Verify.into())
226        }
227    }
228
229    /// The prehashed non-batched Ed25519 verification check, rejecting non-canonical R values.
230    /// (see [`Self::recompute_R`]). `CtxDigest` is the digest used to calculate the
231    /// pseudorandomness needed for signing. `MsgDigest` is the digest used to hash the signed
232    /// message. According to the spec, `MsgDigest = CtxDigest = Sha512`.
233    ///
234    /// This definition is loose in its parameters so that end-users of the `hazmat` module can
235    /// change how the `ExpandedSecretKey` is calculated and which hash function to use.
236    #[cfg(feature = "digest")]
237    #[allow(non_snake_case)]
238    pub(crate) fn raw_verify_prehashed<CtxDigest, MsgDigest>(
239        &self,
240        prehashed_message: MsgDigest,
241        context: Option<&[u8]>,
242        signature: &ed25519::Signature,
243    ) -> Result<(), SignatureError>
244    where
245        CtxDigest: Digest<OutputSize = U64>,
246        MsgDigest: Digest<OutputSize = U64>,
247    {
248        let signature = InternalSignature::try_from(signature)?;
249
250        let ctx: &[u8] = context.unwrap_or(b"");
251        debug_assert!(
252            ctx.len() <= 255,
253            "The context must not be longer than 255 octets."
254        );
255
256        let message = prehashed_message.finalize();
257
258        let expected_R = RCompute::<CtxDigest>::compute(self, signature, Some(ctx), &[&message]);
259
260        if expected_R == signature.R {
261            Ok(())
262        } else {
263            Err(InternalError::Verify.into())
264        }
265    }
266
267    /// Verify a `signature` on a `prehashed_message` using the Ed25519ph algorithm.
268    ///
269    /// # Inputs
270    ///
271    /// * `prehashed_message` is an instantiated hash digest with 512-bits of
272    ///   output which has had the message to be signed previously fed into its
273    ///   state.
274    /// * `context` is an optional context string, up to 255 bytes inclusive,
275    ///   which may be used to provide additional domain separation.  If not
276    ///   set, this will default to an empty string.
277    /// * `signature` is a purported Ed25519ph signature on the `prehashed_message`.
278    ///
279    /// # Returns
280    ///
281    /// Returns `true` if the `signature` was a valid signature created by this
282    /// [`SigningKey`] on the `prehashed_message`.
283    ///
284    /// # Note
285    ///
286    /// The RFC only permits SHA-512 to be used for prehashing, i.e., `MsgDigest = Sha512`. This
287    /// function technically works, and is probably safe to use, with any secure hash function with
288    /// 512-bit digests, but anything outside of SHA-512 is NOT specification-compliant. We expose
289    /// [`crate::Sha512`] for user convenience.
290    #[cfg(feature = "digest")]
291    #[allow(non_snake_case)]
292    pub fn verify_prehashed<MsgDigest>(
293        &self,
294        prehashed_message: MsgDigest,
295        context: Option<&[u8]>,
296        signature: &ed25519::Signature,
297    ) -> Result<(), SignatureError>
298    where
299        MsgDigest: Digest<OutputSize = U64>,
300    {
301        self.raw_verify_prehashed::<Sha512, MsgDigest>(prehashed_message, context, signature)
302    }
303
304    /// Strictly verify a signature on a message with this keypair's public key.
305    ///
306    /// # On The (Multiple) Sources of Malleability in Ed25519 Signatures
307    ///
308    /// This version of verification is technically non-RFC8032 compliant.  The
309    /// following explains why.
310    ///
311    /// 1. Scalar Malleability
312    ///
313    /// The authors of the RFC explicitly stated that verification of an ed25519
314    /// signature must fail if the scalar `s` is not properly reduced mod $\ell$:
315    ///
316    /// > To verify a signature on a message M using public key A, with F
317    /// > being 0 for Ed25519ctx, 1 for Ed25519ph, and if Ed25519ctx or
318    /// > Ed25519ph is being used, C being the context, first split the
319    /// > signature into two 32-octet halves.  Decode the first half as a
320    /// > point R, and the second half as an integer S, in the range
321    /// > 0 <= s < L.  Decode the public key A as point A'.  If any of the
322    /// > decodings fail (including S being out of range), the signature is
323    /// > invalid.)
324    ///
325    /// All `verify_*()` functions within ed25519-dalek perform this check.
326    ///
327    /// 2. Point malleability
328    ///
329    /// The authors of the RFC added in a malleability check to step #3 in
330    /// ยง5.1.7, for small torsion components in the `R` value of the signature,
331    /// *which is not strictly required*, as they state:
332    ///
333    /// > Check the group equation \[8\]\[S\]B = \[8\]R + \[8\]\[k\]A'.  It's
334    /// > sufficient, but not required, to instead check \[S\]B = R + \[k\]A'.
335    ///
336    /// # History of Malleability Checks
337    ///
338    /// As originally defined (cf. the "Malleability" section in the README of
339    /// this repo), ed25519 signatures didn't consider *any* form of
340    /// malleability to be an issue.  Later the scalar malleability was
341    /// considered important.  Still later, particularly with interests in
342    /// cryptocurrency design and in unique identities (e.g. for Signal users,
343    /// Tor onion services, etc.), the group element malleability became a
344    /// concern.
345    ///
346    /// However, libraries had already been created to conform to the original
347    /// definition.  One well-used library in particular even implemented the
348    /// group element malleability check, *but only for batch verification*!
349    /// Which meant that even using the same library, a single signature could
350    /// verify fine individually, but suddenly, when verifying it with a bunch
351    /// of other signatures, the whole batch would fail!
352    ///
353    /// # "Strict" Verification
354    ///
355    /// This method performs *both* of the above signature malleability checks.
356    ///
357    /// It must be done as a separate method because one doesn't simply get to
358    /// change the definition of a cryptographic primitive ten years
359    /// after-the-fact with zero consideration for backwards compatibility in
360    /// hardware and protocols which have it already have the older definition
361    /// baked in.
362    ///
363    /// # Return
364    ///
365    /// Returns `Ok(())` if the signature is valid, and `Err` otherwise.
366    #[allow(non_snake_case)]
367    pub fn verify_strict(
368        &self,
369        message: &[u8],
370        signature: &ed25519::Signature,
371    ) -> Result<(), SignatureError> {
372        let signature = InternalSignature::try_from(signature)?;
373
374        let signature_R = signature
375            .R
376            .decompress()
377            .ok_or_else(|| SignatureError::from(InternalError::Verify))?;
378
379        // Logical OR is fine here as we're not trying to be constant time.
380        if signature_R.is_small_order() || self.point.is_small_order() {
381            return Err(InternalError::Verify.into());
382        }
383
384        let expected_R = RCompute::<Sha512>::compute(self, signature, None, &[message]);
385        if expected_R == signature.R {
386            Ok(())
387        } else {
388            Err(InternalError::Verify.into())
389        }
390    }
391
392    /// Constructs stream verifier with candidate `signature`.
393    ///
394    /// Useful for cases where the whole message is not available all at once, allowing the
395    /// internal signature state to be updated incrementally and verified at the end. In some cases,
396    /// this will reduce the need for additional allocations.
397    #[cfg(feature = "hazmat")]
398    pub fn verify_stream(
399        &self,
400        signature: &ed25519::Signature,
401    ) -> Result<StreamVerifier, SignatureError> {
402        let signature = InternalSignature::try_from(signature)?;
403        Ok(StreamVerifier::new(*self, signature))
404    }
405
406    /// Verify a `signature` on a `prehashed_message` using the Ed25519ph algorithm,
407    /// using strict signature checking as defined by [`Self::verify_strict`].
408    ///
409    /// # Inputs
410    ///
411    /// * `prehashed_message` is an instantiated hash digest with 512-bits of
412    ///   output which has had the message to be signed previously fed into its
413    ///   state.
414    /// * `context` is an optional context string, up to 255 bytes inclusive,
415    ///   which may be used to provide additional domain separation.  If not
416    ///   set, this will default to an empty string.
417    /// * `signature` is a purported Ed25519ph signature on the `prehashed_message`.
418    ///
419    /// # Returns
420    ///
421    /// Returns `true` if the `signature` was a valid signature created by this
422    /// [`SigningKey`] on the `prehashed_message`.
423    ///
424    /// # Note
425    ///
426    /// The RFC only permits SHA-512 to be used for prehashing, i.e., `MsgDigest = Sha512`. This
427    /// function technically works, and is probably safe to use, with any secure hash function with
428    /// 512-bit digests, but anything outside of SHA-512 is NOT specification-compliant. We expose
429    /// [`crate::Sha512`] for user convenience.
430    #[cfg(feature = "digest")]
431    #[allow(non_snake_case)]
432    pub fn verify_prehashed_strict<MsgDigest>(
433        &self,
434        prehashed_message: MsgDigest,
435        context: Option<&[u8]>,
436        signature: &ed25519::Signature,
437    ) -> Result<(), SignatureError>
438    where
439        MsgDigest: Digest<OutputSize = U64>,
440    {
441        let signature = InternalSignature::try_from(signature)?;
442
443        let ctx: &[u8] = context.unwrap_or(b"");
444        debug_assert!(
445            ctx.len() <= 255,
446            "The context must not be longer than 255 octets."
447        );
448
449        let signature_R = signature
450            .R
451            .decompress()
452            .ok_or_else(|| SignatureError::from(InternalError::Verify))?;
453
454        // Logical OR is fine here as we're not trying to be constant time.
455        if signature_R.is_small_order() || self.point.is_small_order() {
456            return Err(InternalError::Verify.into());
457        }
458
459        let message = prehashed_message.finalize();
460        let expected_R = RCompute::<Sha512>::compute(self, signature, Some(ctx), &[&message]);
461
462        if expected_R == signature.R {
463            Ok(())
464        } else {
465            Err(InternalError::Verify.into())
466        }
467    }
468
469    /// Convert this verifying key into Montgomery form.
470    ///
471    /// This can be used for performing X25519 Diffie-Hellman using Ed25519 keys. The output of
472    /// this function is a valid X25519 public key whose secret key is `sk.to_scalar_bytes()`,
473    /// where `sk` is a valid signing key for this `VerifyingKey`.
474    ///
475    /// # Note
476    ///
477    /// We do NOT recommend this usage of a signing/verifying key. Signing keys are usually
478    /// long-term keys, while keys used for key exchange should rather be ephemeral. If you can
479    /// help it, use a separate key for encryption.
480    ///
481    /// For more information on the security of systems which use the same keys for both signing
482    /// and Diffie-Hellman, see the paper
483    /// [On using the same key pair for Ed25519 and an X25519 based KEM](https://eprint.iacr.org/2021/509).
484    pub fn to_montgomery(&self) -> MontgomeryPoint {
485        self.point.to_montgomery()
486    }
487
488    /// Return this verifying key in Edwards form.
489    pub fn to_edwards(&self) -> EdwardsPoint {
490        self.point
491    }
492}
493
494/// Helper for verification. Computes the _expected_ R component of the signature. The
495/// caller compares this to the real R component.
496/// This computes `H(R || A || M)` where `H` is the 512-bit hash function
497/// given by `CtxDigest` (this is SHA-512 in spec-compliant Ed25519).
498///
499/// For pre-hashed variants a `h` with the context already included can be provided.
500/// Note that this returns the compressed form of R and the caller does a byte comparison. This
501/// means that all our verification functions do not accept non-canonically encoded R values.
502/// See the validation criteria blog post for more details:
503///     https://hdevalence.ca/blog/2020-10-04-its-25519am
504pub(crate) struct RCompute<CtxDigest> {
505    key: VerifyingKey,
506    signature: InternalSignature,
507    h: CtxDigest,
508}
509
510#[allow(non_snake_case)]
511impl<CtxDigest> RCompute<CtxDigest>
512where
513    CtxDigest: Digest<OutputSize = U64>,
514{
515    /// If `prehash_ctx.is_some()`, this does the prehashed variant of the computation using its
516    /// contents.
517    pub(crate) fn compute(
518        key: &VerifyingKey,
519        signature: InternalSignature,
520        prehash_ctx: Option<&[u8]>,
521        message: &[&[u8]],
522    ) -> CompressedEdwardsY {
523        let mut c = Self::new(key, signature, prehash_ctx);
524        message.iter().for_each(|slice| c.update(slice));
525        c.finish()
526    }
527
528    pub(crate) fn new(
529        key: &VerifyingKey,
530        signature: InternalSignature,
531        prehash_ctx: Option<&[u8]>,
532    ) -> Self {
533        let R = &signature.R;
534        let A = &key.compressed;
535
536        let mut h = CtxDigest::new();
537        if let Some(c) = prehash_ctx {
538            h.update(b"SigEd25519 no Ed25519 collisions");
539            h.update([1]); // Ed25519ph
540            h.update([c.len() as u8]);
541            h.update(c);
542        }
543
544        h.update(R.as_bytes());
545        h.update(A.as_bytes());
546        Self {
547            key: *key,
548            signature,
549            h,
550        }
551    }
552
553    pub(crate) fn update(&mut self, m: &[u8]) {
554        self.h.update(m)
555    }
556
557    pub(crate) fn finish(self) -> CompressedEdwardsY {
558        let k = Scalar::from_hash(self.h);
559
560        let minus_A: EdwardsPoint = -self.key.point;
561        // Recall the (non-batched) verification equation: -[k]A + [s]B = R
562        EdwardsPoint::vartime_double_scalar_mul_basepoint(&k, &(minus_A), &self.signature.s)
563            .compress()
564    }
565}
566
567impl Verifier<ed25519::Signature> for VerifyingKey {
568    /// Verify a signature on a message with this keypair's public key.
569    ///
570    /// # Return
571    ///
572    /// Returns `Ok(())` if the signature is valid, and `Err` otherwise.
573    fn verify(&self, message: &[u8], signature: &ed25519::Signature) -> Result<(), SignatureError> {
574        self.multipart_verify(&[message], signature)
575    }
576}
577
578impl MultipartVerifier<ed25519::Signature> for VerifyingKey {
579    fn multipart_verify(
580        &self,
581        message: &[&[u8]],
582        signature: &ed25519::Signature,
583    ) -> Result<(), SignatureError> {
584        self.raw_verify::<Sha512>(message, signature)
585    }
586}
587
588/// Equivalent to [`VerifyingKey::verify_prehashed`] with `context` set to [`None`].
589#[cfg(feature = "digest")]
590impl<MsgDigest> DigestVerifier<MsgDigest, ed25519::Signature> for VerifyingKey
591where
592    MsgDigest: Digest<OutputSize = U64> + Update,
593{
594    fn verify_digest<F: Fn(&mut MsgDigest) -> Result<(), SignatureError>>(
595        &self,
596        f: F,
597        signature: &ed25519::Signature,
598    ) -> Result<(), SignatureError> {
599        let mut digest = MsgDigest::new();
600        f(&mut digest)?;
601        self.verify_prehashed(digest, None, signature)
602    }
603}
604
605/// Equivalent to [`VerifyingKey::verify_prehashed`] with `context` set to [`Some`]
606/// containing `self.value()`.
607#[cfg(feature = "digest")]
608impl<MsgDigest> DigestVerifier<MsgDigest, ed25519::Signature> for Context<'_, '_, VerifyingKey>
609where
610    MsgDigest: Digest<OutputSize = U64> + Update,
611{
612    fn verify_digest<F: Fn(&mut MsgDigest) -> Result<(), SignatureError>>(
613        &self,
614        f: F,
615        signature: &ed25519::Signature,
616    ) -> Result<(), SignatureError> {
617        let mut digest = MsgDigest::new();
618        f(&mut digest)?;
619        self.key()
620            .verify_prehashed(digest, Some(self.value()), signature)
621    }
622}
623
624impl TryFrom<&[u8]> for VerifyingKey {
625    type Error = SignatureError;
626
627    #[inline]
628    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
629        let bytes = bytes.try_into().map_err(|_| InternalError::BytesLength {
630            name: "VerifyingKey",
631            length: PUBLIC_KEY_LENGTH,
632        })?;
633        Self::from_bytes(bytes)
634    }
635}
636
637#[cfg(feature = "pkcs8")]
638impl pkcs8::spki::SignatureAlgorithmIdentifier for VerifyingKey {
639    type Params = pkcs8::spki::der::AnyRef<'static>;
640
641    const SIGNATURE_ALGORITHM_IDENTIFIER: pkcs8::spki::AlgorithmIdentifier<Self::Params> =
642        <ed25519::Signature as pkcs8::spki::AssociatedAlgorithmIdentifier>::ALGORITHM_IDENTIFIER;
643}
644
645impl From<VerifyingKey> for EdwardsPoint {
646    fn from(vk: VerifyingKey) -> EdwardsPoint {
647        vk.point
648    }
649}
650
651#[cfg(all(feature = "alloc", feature = "pkcs8"))]
652impl pkcs8::EncodePublicKey for VerifyingKey {
653    fn to_public_key_der(&self) -> pkcs8::spki::Result<pkcs8::Document> {
654        pkcs8::PublicKeyBytes::from(self).to_public_key_der()
655    }
656}
657
658#[cfg(feature = "pkcs8")]
659impl TryFrom<pkcs8::PublicKeyBytes> for VerifyingKey {
660    type Error = pkcs8::spki::Error;
661
662    fn try_from(pkcs8_key: pkcs8::PublicKeyBytes) -> pkcs8::spki::Result<Self> {
663        VerifyingKey::try_from(&pkcs8_key)
664    }
665}
666
667#[cfg(feature = "pkcs8")]
668impl TryFrom<&pkcs8::PublicKeyBytes> for VerifyingKey {
669    type Error = pkcs8::spki::Error;
670
671    fn try_from(pkcs8_key: &pkcs8::PublicKeyBytes) -> pkcs8::spki::Result<Self> {
672        VerifyingKey::from_bytes(pkcs8_key.as_ref()).map_err(|_| pkcs8::spki::Error::KeyMalformed)
673    }
674}
675
676#[cfg(feature = "pkcs8")]
677impl From<VerifyingKey> for pkcs8::PublicKeyBytes {
678    fn from(verifying_key: VerifyingKey) -> pkcs8::PublicKeyBytes {
679        pkcs8::PublicKeyBytes::from(&verifying_key)
680    }
681}
682
683#[cfg(feature = "pkcs8")]
684impl From<&VerifyingKey> for pkcs8::PublicKeyBytes {
685    fn from(verifying_key: &VerifyingKey) -> pkcs8::PublicKeyBytes {
686        pkcs8::PublicKeyBytes(verifying_key.to_bytes())
687    }
688}
689
690#[cfg(feature = "pkcs8")]
691impl TryFrom<pkcs8::spki::SubjectPublicKeyInfoRef<'_>> for VerifyingKey {
692    type Error = pkcs8::spki::Error;
693
694    fn try_from(public_key: pkcs8::spki::SubjectPublicKeyInfoRef<'_>) -> pkcs8::spki::Result<Self> {
695        pkcs8::PublicKeyBytes::try_from(public_key)?.try_into()
696    }
697}
698
699#[cfg(feature = "serde")]
700impl Serialize for VerifyingKey {
701    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
702    where
703        S: Serializer,
704    {
705        serializer.serialize_bytes(&self.as_bytes()[..])
706    }
707}
708
709#[cfg(feature = "serde")]
710impl<'d> Deserialize<'d> for VerifyingKey {
711    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
712    where
713        D: Deserializer<'d>,
714    {
715        struct VerifyingKeyVisitor;
716
717        impl<'de> serde::de::Visitor<'de> for VerifyingKeyVisitor {
718            type Value = VerifyingKey;
719
720            fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
721                write!(formatter, "An ed25519 verifying (public) key")
722            }
723
724            fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
725                VerifyingKey::try_from(bytes).map_err(E::custom)
726            }
727
728            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
729            where
730                A: serde::de::SeqAccess<'de>,
731            {
732                let mut bytes = [0u8; 32];
733
734                #[allow(clippy::needless_range_loop)]
735                for i in 0..32 {
736                    bytes[i] = seq
737                        .next_element()?
738                        .ok_or_else(|| serde::de::Error::invalid_length(i, &"expected 32 bytes"))?;
739                }
740
741                let remaining = (0..)
742                    .map(|_| seq.next_element::<u8>())
743                    .take_while(|el| matches!(el, Ok(Some(_))))
744                    .count();
745
746                if remaining > 0 {
747                    return Err(serde::de::Error::invalid_length(
748                        32 + remaining,
749                        &"expected 32 bytes",
750                    ));
751                }
752
753                VerifyingKey::try_from(&bytes[..]).map_err(serde::de::Error::custom)
754            }
755        }
756
757        deserializer.deserialize_bytes(VerifyingKeyVisitor)
758    }
759}