Skip to main content

ndn_protocol/
signature.rs

1//! Signing and verifying [`Interest`](crate::Interest)s and
2//! [`Data`]s.
3//!
4//! Signing goes through the [`SignMethod`] trait and verifying through
5//! [`SignatureVerifier`]; a type can implement either or both, and
6//! [`DigestSha256`] and [`SignatureSha256WithRsa`] implement both, since
7//! both take a certificate/key pair that's just as capable of checking a
8//! signature as producing one. [`KnownSigners`]/[`KnownVerifiers`] can
9//! build the right signer/verifier for a certificate purely from the
10//! signature type it declares, for code that doesn't know in advance
11//! which scheme it's dealing with.
12//!
13//! The rest of this module is the wire-format types that make up a
14//! [`SignatureInfo`]/`InterestSignatureInfo` -- [`SignatureType`],
15//! [`KeyLocator`], [`ValidityPeriod`], and so on. Most application code
16//! only needs to read them back via [`SignatureInfo::key_locator`]/
17//! `InterestSignatureInfo::key_locator` after verifying.
18
19use std::io::Read;
20
21use bytes::{Buf, BufMut, Bytes, BytesMut};
22use derive_more::{AsMut, AsRef, Constructor, Display, From, Into};
23use ndn_tlv::{NonNegativeInteger, Tlv, TlvDecode, TlvEncode, TlvError, VarNum};
24
25use rand::SeedableRng;
26use rsa::{
27    pkcs1v15::{Signature, SigningKey},
28    signature::{RandomizedSigner, SignatureEncoding},
29    Pkcs1v15Sign,
30};
31use sha2::{Digest, Sha256};
32use time::{OffsetDateTime, UtcOffset};
33
34use crate::{
35    certificate::ToCertificate, Certificate, ContentType, Data, MetaInfo, Name, RsaCertificate,
36};
37
38use self::signature_type::get_signature_type;
39
40/// The signature type numbers used in a [`SignatureType`], identifying
41/// which signing scheme was used.
42pub mod signature_type {
43    use ndn_tlv::TlvEncode;
44
45    use crate::Data;
46
47    /// A plain SHA-256 digest, with no key involved (see [`DigestSha256`](crate::DigestSha256)).
48    pub const DIGEST_SHA256: usize = 0;
49    /// An RSA signature over a SHA-256 digest (see [`SignatureSha256WithRsa`](crate::SignatureSha256WithRsa)).
50    pub const SIGNATURE_SHA256_WITH_RSA: usize = 1;
51    /// An ECDSA signature over a SHA-256 digest. Not implemented by this crate.
52    pub const SIGNATURE_SHA256_WITH_ECDSA: usize = 3;
53    /// A HMAC over a SHA-256 digest. Not implemented by this crate.
54    pub const SIGNATRUE_HMAC_WITH_SHA256: usize = 4;
55    /// An Ed25519 signature. Not implemented by this crate.
56    pub const SIGNATURE_ED25519: usize = 5;
57
58    pub(super) fn get_signature_type<T: TlvEncode>(data: &Data<T>) -> Option<usize> {
59        Some(
60            data.signature_info()
61                .as_ref()?
62                .signature_type
63                .signature_type
64                .into(),
65        )
66    }
67
68    pub(super) fn ensure_signature_type<T: TlvEncode>(data: &Data<T>, typ: usize) -> Option<()> {
69        if get_signature_type(data)? != typ {
70            return None;
71        }
72        Some(())
73    }
74}
75
76/// Which signing scheme a signature was produced with -- see the
77/// [`signature_type`] module for the well-known values.
78#[derive(
79    Debug, Tlv, PartialEq, Eq, Clone, Hash, From, Into, AsRef, AsMut, Display, Constructor,
80)]
81#[tlv(27)]
82pub struct SignatureType {
83    signature_type: VarNum,
84}
85
86/// A digest identifying a public key, used as a compact alternative to a
87/// full [`Name`] in a [`KeyLocator`].
88#[derive(Debug, Tlv, PartialEq, Eq, Clone, Hash, From, Into, AsRef, AsMut, Constructor)]
89#[tlv(29)]
90pub struct KeyDigest {
91    data: Bytes,
92}
93
94/// What a [`KeyLocator`] points at: either the signing certificate's
95/// [`Name`] (the `Name` variant), or a [`KeyDigest`] of its key (the
96/// `KeyDigest` variant).
97#[derive(Debug, Tlv, PartialEq, Eq, Clone, Hash)]
98pub enum KeyLocatorData {
99    /// The signing certificate's name.
100    Name(Name),
101    /// A digest of the signing key.
102    KeyDigest(KeyDigest),
103}
104
105impl KeyLocatorData {
106    /// The name, if this locator points at one.
107    pub fn as_name(&self) -> Option<&Name> {
108        if let Self::Name(v) = self {
109            Some(v)
110        } else {
111            None
112        }
113    }
114
115    /// The key digest, if this locator points at one.
116    pub fn as_key_digest(&self) -> Option<&KeyDigest> {
117        if let Self::KeyDigest(v) = self {
118            Some(v)
119        } else {
120            None
121        }
122    }
123}
124
125/// Identifies the key used to produce a signature, so a verifier knows
126/// which certificate to check it against.
127#[derive(Debug, Tlv, PartialEq, Eq, Clone, Hash, AsRef, AsMut, Constructor, From, Into)]
128#[tlv(28)]
129pub struct KeyLocator {
130    locator: KeyLocatorData,
131}
132
133impl KeyLocator {
134    /// What the locator points at.
135    pub fn locator(&self) -> &KeyLocatorData {
136        &self.locator
137    }
138}
139
140/// A point in time in the `YYYYMMDDTHHMMSS` format NDN certificate
141/// validity periods use, e.g. `20240301T200915`.
142#[derive(Debug, PartialEq, Eq, Clone, Hash, Constructor)]
143pub struct Timestamp {
144    date: [u8; 8],
145    time: [u8; 6],
146}
147
148impl From<OffsetDateTime> for Timestamp {
149    fn from(value: OffsetDateTime) -> Self {
150        let datetime = value.to_offset(UtcOffset::UTC);
151        let date = format!(
152            "{:02}{:02}{:04}",
153            datetime.day(),
154            datetime.month() as u8,
155            datetime.year()
156        );
157
158        let mut date_buf = [0; 8];
159        date_buf.copy_from_slice(&date.as_bytes());
160
161        let time = format!(
162            "{:02}{:02}{:02}",
163            datetime.hour(),
164            datetime.minute(),
165            datetime.second()
166        );
167
168        let mut time_buf = [0; 6];
169        time_buf.copy_from_slice(&time.as_bytes());
170        Timestamp {
171            date: date_buf,
172            time: time_buf,
173        }
174    }
175}
176
177impl TlvEncode for Timestamp {
178    fn encode(&self) -> Bytes {
179        let mut bytes = BytesMut::with_capacity(self.size());
180        bytes.put(&self.date[..]);
181        bytes.put_u8(b'T');
182        bytes.put(&self.time[..]);
183        bytes.freeze()
184    }
185
186    fn size(&self) -> usize {
187        15
188    }
189}
190
191impl TlvDecode for Timestamp {
192    fn decode(bytes: &mut Bytes) -> ndn_tlv::Result<Self> {
193        if bytes.remaining() < 15 {
194            return Err(TlvError::UnexpectedEndOfStream);
195        }
196        let mut date = [0; 8];
197        let mut t = [0];
198        let mut time = [0; 6];
199
200        let mut reader = bytes.reader();
201        reader
202            .read_exact(&mut date)
203            .map_err(|_| TlvError::FormatError)?;
204        reader
205            .read_exact(&mut t)
206            .map_err(|_| TlvError::FormatError)?;
207        reader
208            .read_exact(&mut time)
209            .map_err(|_| TlvError::FormatError)?;
210
211        Ok(Self { date, time })
212    }
213}
214
215/// The start of a [`ValidityPeriod`].
216#[derive(Debug, Tlv, PartialEq, Eq, Clone, Hash, Constructor)]
217#[tlv(254)]
218pub struct NotBefore {
219    /// The earliest time the signature is considered valid.
220    pub not_before: Timestamp,
221}
222
223/// The end of a [`ValidityPeriod`].
224#[derive(Debug, Tlv, PartialEq, Eq, Clone, Hash, Constructor)]
225#[tlv(255)]
226pub struct NotAfter {
227    /// The latest time the signature is considered valid.
228    pub not_after: Timestamp,
229}
230
231/// The time range a certificate's signature is valid within -- see [`Data::sign_cert`](crate::Data::sign_cert).
232#[derive(Debug, Tlv, PartialEq, Eq, Clone, Hash, Constructor)]
233#[tlv(253)]
234pub struct ValidityPeriod {
235    /// The start of the validity period.
236    pub not_before: NotBefore,
237    /// The end of the validity period.
238    pub not_after: NotAfter,
239}
240
241/// Metadata attached to a signed [`Data`] packet describing how it was
242/// signed: the [`SignatureType`], the [`KeyLocator`] identifying the
243/// signing key, and, for certificates, a [`ValidityPeriod`].
244#[derive(Debug, Tlv, PartialEq, Eq, Clone, Hash, Constructor)]
245#[tlv(22)]
246pub struct SignatureInfo {
247    signature_type: SignatureType,
248    key_locator: Option<KeyLocator>,
249    validity_period: Option<ValidityPeriod>,
250}
251
252impl SignatureInfo {
253    /// The signature type number.
254    pub fn signature_type(&self) -> VarNum {
255        self.signature_type.signature_type
256    }
257
258    /// What the key locator points at, if set.
259    pub fn key_locator(&self) -> Option<&KeyLocatorData> {
260        self.key_locator.as_ref().map(|x| &x.locator)
261    }
262}
263
264/// The raw signature bytes produced by signing a [`Data`] packet.
265#[derive(Debug, Tlv, PartialEq, Eq, Clone, Hash, AsRef, AsMut, Constructor, From, Into)]
266#[tlv(23)]
267pub struct SignatureValue {
268    data: Bytes,
269}
270
271/// A random value included in an `InterestSignatureInfo` to make each
272/// signed Interest unique, guarding against replay.
273#[derive(Debug, Tlv, PartialEq, Eq, Clone, Hash, AsRef, AsMut, Constructor, From, Into)]
274#[tlv(38)]
275pub struct SignatureNonce {
276    data: Bytes,
277}
278
279/// A signing timestamp (Unix time in milliseconds) included in an
280/// `InterestSignatureInfo`, guarding against replay of old signed Interests.
281#[derive(
282    Debug,
283    Tlv,
284    PartialEq,
285    Eq,
286    Clone,
287    Hash,
288    AsRef,
289    AsMut,
290    Constructor,
291    From,
292    Into,
293    Display,
294    PartialOrd,
295    Ord,
296)]
297#[tlv(40)]
298pub struct SignatureTime {
299    data: NonNegativeInteger,
300}
301
302/// A signing sequence number included in an `InterestSignatureInfo`,
303/// guarding against replay: a verifier can reject a signature whose
304/// sequence number isn't greater than the last one seen from that signer.
305#[derive(
306    Debug,
307    Tlv,
308    PartialEq,
309    Eq,
310    Clone,
311    Hash,
312    From,
313    Into,
314    AsRef,
315    AsMut,
316    Constructor,
317    PartialOrd,
318    Ord,
319    Display,
320)]
321#[tlv(42)]
322pub struct SignatureSeqNum {
323    data: NonNegativeInteger,
324}
325
326/// Metadata attached to a signed [`Interest`](crate::Interest) describing
327/// how it was signed. Mirrors [`SignatureInfo`], but with the extra
328/// replay-protection fields ([`SignatureNonce`], [`SignatureTime`],
329/// [`SignatureSeqNum`]) signed Interests carry instead of a validity period.
330#[derive(Debug, Tlv, PartialEq, Eq, Clone, Hash, Constructor)]
331#[tlv(44)]
332pub struct InterestSignatureInfo {
333    pub(crate) signature_type: SignatureType,
334    pub(crate) key_locator: Option<KeyLocator>,
335    pub(crate) nonce: Option<SignatureNonce>,
336    pub(crate) time: Option<SignatureTime>,
337    pub(crate) seq_num: Option<SignatureSeqNum>,
338}
339
340impl InterestSignatureInfo {
341    /// The signature type number.
342    pub fn signature_type(&self) -> VarNum {
343        self.signature_type.signature_type
344    }
345
346    /// What the key locator points at, if set.
347    pub fn key_locator(&self) -> Option<&KeyLocatorData> {
348        self.key_locator.as_ref().map(|x| &x.locator)
349    }
350
351    /// The signing nonce, if included.
352    pub fn nonce(&self) -> Option<&Bytes> {
353        self.nonce.as_ref().map(|x| &x.data)
354    }
355
356    /// The signing timestamp (Unix time in milliseconds), if included.
357    pub fn time(&self) -> Option<NonNegativeInteger> {
358        self.time.as_ref().map(|x| x.data)
359    }
360
361    /// The signing sequence number, if included.
362    pub fn seq_num(&self) -> Option<NonNegativeInteger> {
363        self.seq_num.as_ref().map(|x| x.data)
364    }
365}
366
367/// The raw signature bytes produced by signing an
368/// [`Interest`](crate::Interest).
369#[derive(Debug, Tlv, PartialEq, Eq, Clone, Hash, From, Into, AsRef, AsMut, Constructor)]
370#[tlv(46)]
371pub struct InterestSignatureValue {
372    data: Bytes,
373}
374
375/// Something that can sign [`Interest`](crate::Interest)s and
376/// [`Data`] -- see [`DigestSha256`] and
377/// [`SignatureSha256WithRsa`] for the implementations this crate provides.
378pub trait SignMethod {
379    /// The signature type number this method produces (see [`signature_type`]).
380    fn signature_type(&self) -> u64;
381
382    /// Returns the next signing sequence number, advancing internal state
383    /// so each call returns a new value.
384    fn next_seq_num(&mut self) -> u64;
385
386    /// The certificate this method signs with, if any (e.g. `None` for
387    /// [`DigestSha256`], which signs without a key).
388    fn certificate(&self) -> Option<Certificate>;
389
390    /// Signs `data`, returning the raw signature bytes.
391    fn sign(&self, data: &[u8]) -> Bytes;
392
393    /// The current time, used as the default signing timestamp. Provided
394    /// so it doesn't need to be implemented by every `SignMethod`.
395    fn time(&self) -> SignatureTime {
396        SignatureTime {
397            data: NonNegativeInteger::from(
398                std::time::SystemTime::now()
399                    .duration_since(std::time::UNIX_EPOCH)
400                    .unwrap()
401                    .as_millis() as u64,
402            ),
403        }
404    }
405}
406
407/// Associates a [`SignMethod`] implementation with its fixed signature
408/// type number, so it can be checked against a certificate's declared type
409/// without needing an instance (see [`SignatureSha256WithRsaVerifier::from_data`]
410/// and similar).
411pub trait SignMethodType {
412    /// This signing scheme's signature type number (see [`signature_type`]).
413    const SIGNATURE_TYPE: u64;
414}
415
416impl<T: SignMethod> SignMethod for &mut T {
417    fn signature_type(&self) -> u64 {
418        (**self).signature_type()
419    }
420
421    fn next_seq_num(&mut self) -> u64 {
422        (**self).next_seq_num()
423    }
424
425    fn certificate(&self) -> Option<Certificate> {
426        (**self).certificate()
427    }
428
429    fn sign(&self, data: &[u8]) -> Bytes {
430        (**self).sign(data)
431    }
432}
433
434impl<T: SignMethod + ?Sized> SignMethod for Box<T> {
435    fn signature_type(&self) -> u64 {
436        (**self).signature_type()
437    }
438
439    fn next_seq_num(&mut self) -> u64 {
440        (**self).next_seq_num()
441    }
442
443    fn certificate(&self) -> Option<Certificate> {
444        (**self).certificate()
445    }
446
447    fn sign(&self, data: &[u8]) -> Bytes {
448        (**self).sign(data)
449    }
450}
451
452/// Builds a [`SignMethod`] for any signature type this crate implements,
453/// purely from a certificate's declared signature type -- see [`ToSigner`].
454#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
455pub struct KnownSigners;
456
457/// Implemented by types that can produce a [`SignMethod`] for a
458/// certificate, without the caller needing to know its signature type in
459/// advance.
460pub trait ToSigner {
461    /// Builds a signer for `data`'s declared signature type, or `None` if
462    /// it's not one this implementation recognizes.
463    fn from_data(&self, data: Data<Bytes>) -> Option<Box<dyn SignMethod + Send + Sync>>;
464}
465impl ToSigner for KnownSigners {
466    fn from_data(&self, data: Data<Bytes>) -> Option<Box<dyn SignMethod + Send + Sync>> {
467        match get_signature_type(&data)? {
468            signature_type::DIGEST_SHA256 => Some(Box::new(DigestSha256::from_data(data)?)),
469            signature_type::SIGNATURE_SHA256_WITH_RSA => {
470                Some(Box::new(SignatureSha256WithRsa::from_data(data)?))
471            }
472            _ => None,
473        }
474    }
475}
476
477/// Builds a [`SignatureVerifier`] for any signature type this crate
478/// implements, purely from a certificate's declared signature type -- see
479/// [`ToVerifier`].
480#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
481pub struct KnownVerifiers;
482
483/// Implemented by types that can produce a [`SignatureVerifier`] for a
484/// certificate, without the caller needing to know its signature type in
485/// advance. Mirrors [`ToSigner`] for the verifying side.
486pub trait ToVerifier {
487    /// Builds a verifier for `data`'s declared signature type, or `None`
488    /// if it's not one this implementation recognizes.
489    fn from_data(&self, data: Data<Bytes>) -> Option<Box<dyn SignatureVerifier + Send + Sync>>;
490}
491
492impl ToVerifier for KnownVerifiers {
493    fn from_data(&self, data: Data<Bytes>) -> Option<Box<dyn SignatureVerifier + Send + Sync>> {
494        match get_signature_type(&data)? {
495            signature_type::DIGEST_SHA256 => Some(Box::new(DigestSha256::from_data(data)?)),
496            signature_type::SIGNATURE_SHA256_WITH_RSA => {
497                Some(Box::new(SignatureSha256WithRsa::from_data(data)?))
498            }
499            _ => None,
500        }
501    }
502}
503
504/// Something that can verify signatures produced by a [`SignMethod`] -- see
505/// [`DigestSha256`] and [`SignatureSha256WithRsa`] for the implementations
506/// this crate provides.
507pub trait SignatureVerifier {
508    /// Returns whether `signature` is a valid signature of `data`.
509    fn verify(&self, data: &[u8], signature: &[u8]) -> bool;
510
511    /// The certificate this verifier checks against, if any (e.g. `None`
512    /// for [`DigestSha256`], which verifies without a key).
513    fn certificate(&self) -> Option<Certificate>;
514
515    /// Builds a verifier from a certificate [`Data`] packet, or `None` if
516    /// its signature type doesn't match this implementation.
517    fn from_data(data: Data<Bytes>) -> Option<Self>
518    where
519        Self: Sized;
520}
521
522impl<T> SignatureVerifier for &T
523where
524    T: SignatureVerifier,
525{
526    fn verify(&self, data: &[u8], signature: &[u8]) -> bool {
527        (**self).verify(data, signature)
528    }
529
530    fn certificate(&self) -> Option<Certificate> {
531        (**self).certificate()
532    }
533
534    fn from_data(_data: Data<Bytes>) -> Option<Self>
535    where
536        Self: Sized,
537    {
538        None
539    }
540}
541
542/// Signs and verifies with a plain SHA-256 digest -- no key involved, so it
543/// only proves data wasn't corrupted in transit, not who sent it. See
544/// [`SignatureSha256WithRsa`] for a scheme that actually authenticates.
545#[derive(Clone, Copy, Debug)]
546pub struct DigestSha256 {
547    seq_num: u64,
548}
549
550impl DigestSha256 {
551    /// Creates a new `DigestSha256` with its sequence number reset to `0`.
552    pub const fn new() -> Self {
553        DigestSha256 { seq_num: 0 }
554    }
555
556    /// A placeholder certificate declaring the digest signature type, for
557    /// code paths that need a [`Certificate`] but `DigestSha256` doesn't
558    /// actually have a key to certify.
559    pub fn certificate() -> Certificate {
560        let mut data = Data::new(Name::empty(), Bytes::new());
561        data.set_meta_info(Some(MetaInfo {
562            content_type: Some(ContentType {
563                content_type: NonNegativeInteger::new(signature_type::DIGEST_SHA256 as u64),
564            }),
565            freshness_period: None,
566            final_block_id: None,
567        }));
568        Certificate(data)
569    }
570}
571
572impl SignMethodType for DigestSha256 {
573    const SIGNATURE_TYPE: u64 = 0;
574}
575
576impl SignMethod for DigestSha256 {
577    fn signature_type(&self) -> u64 {
578        Self::SIGNATURE_TYPE
579    }
580
581    fn next_seq_num(&mut self) -> u64 {
582        let seq_num = self.seq_num;
583        self.seq_num += 1;
584        seq_num
585    }
586
587    fn sign(&self, data: &[u8]) -> Bytes {
588        let mut hasher = Sha256::new();
589        hasher.update(data);
590
591        Bytes::copy_from_slice(&hasher.finalize())
592    }
593
594    fn certificate(&self) -> Option<Certificate> {
595        None
596    }
597}
598
599impl SignatureVerifier for DigestSha256 {
600    fn verify(&self, data: &[u8], signature: &[u8]) -> bool {
601        let hashed = self.sign(data);
602        hashed == signature
603    }
604
605    fn certificate(&self) -> Option<Certificate> {
606        None
607    }
608
609    fn from_data(_data: Data<Bytes>) -> Option<Self>
610    where
611        Self: Sized,
612    {
613        Some(DigestSha256::new())
614    }
615}
616
617/// Verifies `SignatureSha256WithRsa` signatures against an
618/// [`RsaCertificate`]'s public key, without needing its private key.
619#[derive(Clone, Debug)]
620pub struct SignatureSha256WithRsaVerifier(pub RsaCertificate);
621
622/// Signs with RSA over a SHA-256 digest, and verifies the same way.
623#[derive(Clone, Debug)]
624pub struct SignatureSha256WithRsa {
625    cert: RsaCertificate,
626    seq_num: u64,
627}
628
629impl SignatureSha256WithRsa {
630    /// Creates a new `SignatureSha256WithRsa` signing/verifying with
631    /// `cert`, with its sequence number reset to `0`.
632    pub fn new(cert: RsaCertificate) -> Self {
633        Self { cert, seq_num: 0 }
634    }
635}
636
637impl SignMethodType for SignatureSha256WithRsa {
638    const SIGNATURE_TYPE: u64 = 1;
639}
640
641impl SignMethod for SignatureSha256WithRsa {
642    fn signature_type(&self) -> u64 {
643        Self::SIGNATURE_TYPE
644    }
645
646    fn next_seq_num(&mut self) -> u64 {
647        let seq_num = self.seq_num;
648        self.seq_num += 1;
649        seq_num
650    }
651
652    fn sign(&self, data: &[u8]) -> Bytes {
653        let private_key = self.cert.private_key().unwrap(); // TODO: Error handling
654        let signing_key = SigningKey::<Sha256>::new(private_key.clone());
655        let mut rng = rand::rngs::StdRng::from_entropy();
656
657        let output: Signature = signing_key.sign_with_rng(&mut rng, &data);
658        let outputvec = output.to_vec();
659        Bytes::from(outputvec)
660    }
661
662    fn certificate(&self) -> Option<Certificate> {
663        Some(self.cert.to_certificate())
664    }
665}
666
667impl SignatureVerifier for SignatureSha256WithRsa {
668    fn verify(&self, data: &[u8], signature: &[u8]) -> bool {
669        SignatureSha256WithRsaVerifier(self.cert.clone()).verify(data, signature)
670    }
671
672    fn certificate(&self) -> Option<Certificate> {
673        Some(self.cert.to_certificate())
674    }
675
676    fn from_data(data: Data<Bytes>) -> Option<Self>
677    where
678        Self: Sized,
679    {
680        signature_type::ensure_signature_type(&data, signature_type::SIGNATURE_SHA256_WITH_RSA)?;
681        Some(Self::new(RsaCertificate::new(Certificate(data))?))
682    }
683}
684
685impl SignatureVerifier for SignatureSha256WithRsaVerifier {
686    fn verify(&self, data: &[u8], signature: &[u8]) -> bool {
687        let mut hasher: Sha256 = Sha256::new();
688        hasher.update(data);
689        let hashed = hasher.finalize();
690
691        self.0
692            .public_key()
693            .verify(Pkcs1v15Sign::new::<Sha256>(), &hashed, &signature)
694            .is_ok()
695    }
696
697    fn certificate(&self) -> Option<Certificate> {
698        Some(self.0.to_certificate())
699    }
700
701    fn from_data(data: Data<Bytes>) -> Option<Self>
702    where
703        Self: Sized,
704    {
705        signature_type::ensure_signature_type(&data, signature_type::SIGNATURE_SHA256_WITH_RSA)?;
706        Some(Self(RsaCertificate::new(Certificate(data))?))
707    }
708}