pub struct AlgorithmIdentifier {
    pub algorithm: Oid,
    pub parameters: Option<AlgorithmParameter>,
}
Expand description

Algorithm identifier.

AlgorithmIdentifier  ::=  SEQUENCE  {
  algorithm               OBJECT IDENTIFIER,
  parameters              ANY DEFINED BY algorithm OPTIONAL  }

Fields§

§algorithm: Oid§parameters: Option<AlgorithmParameter>

Implementations§

Examples found in repository?
src/rfc3447.rs (line 40)
38
39
40
41
42
43
44
45
    pub fn take_from<S: Source>(cons: &mut Constructed<S>) -> Result<Self, DecodeError<S::Error>> {
        cons.take_sequence(|cons| {
            let algorithm = AlgorithmIdentifier::take_from(cons)?;
            let digest = OctetString::take_from(cons)?;

            Ok(Self { algorithm, digest })
        })
    }
More examples
Hide additional examples
src/rfc5280.rs (line 195)
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
    pub fn from_sequence<S: Source>(
        cons: &mut Constructed<S>,
    ) -> Result<Self, DecodeError<S::Error>> {
        let tbs_certificate = TbsCertificate::take_from(cons)?;
        let signature_algorithm = AlgorithmIdentifier::take_from(cons)?;
        let signature = BitString::take_from(cons)?;

        Ok(Self {
            tbs_certificate,
            signature_algorithm,
            signature,
        })
    }

    pub fn encode_ref(&self) -> impl Values + '_ {
        encode::sequence((
            self.tbs_certificate.encode_ref(),
            &self.signature_algorithm,
            self.signature.encode_ref(),
        ))
    }

    /// Iterate over extensions defined on this certificate.
    pub fn iter_extensions(&self) -> impl Iterator<Item = &Extension> {
        self.tbs_certificate
            .extensions
            .iter()
            .flat_map(|x| x.iter())
    }
}

/// TBS Certificate.
///
/// This holds most of the metadata within an X.509 certificate.
///
/// ```ASN.1
/// TBSCertificate  ::=  SEQUENCE  {
///      version         [0]  Version DEFAULT v1,
///      serialNumber         CertificateSerialNumber,
///      signature            AlgorithmIdentifier,
///      issuer               Name,
///      validity             Validity,
///      subject              Name,
///      subjectPublicKeyInfo SubjectPublicKeyInfo,
///      issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,
///                           -- If present, version MUST be v2 or v3
///      subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL,
///                           -- If present, version MUST be v2 or v3
///      extensions      [3]  Extensions OPTIONAL
///                           -- If present, version MUST be v3 --  }
/// ```
#[derive(Clone, Eq, PartialEq)]
pub struct TbsCertificate {
    pub version: Option<Version>,
    pub serial_number: CertificateSerialNumber,
    pub signature: AlgorithmIdentifier,
    pub issuer: Name,
    pub validity: Validity,
    pub subject: Name,
    pub subject_public_key_info: SubjectPublicKeyInfo,
    pub issuer_unique_id: Option<UniqueIdentifier>,
    pub subject_unique_id: Option<UniqueIdentifier>,
    pub extensions: Option<Extensions>,

    /// Raw bytes this instance was constructed from.
    ///
    /// This is what signature verification should be performed against.
    pub raw_data: Option<Vec<u8>>,
}

impl Debug for TbsCertificate {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("TbsCertificate");
        s.field("version", &self.version);
        s.field("serial_number", &self.serial_number);
        s.field("signature", &self.signature);
        s.field("issuer", &self.issuer);
        s.field("validity", &self.validity);
        s.field("subject", &self.subject);
        s.field("subject_public_key_info", &self.subject_public_key_info);
        s.field("issuer_unique_id", &self.issuer_unique_id);
        s.field("subject_unique_id", &self.subject_unique_id);
        s.field("extensions", &self.extensions);
        s.field(
            "raw_data",
            &format_args!("{:?}", self.raw_data.as_ref().map(hex::encode)),
        );
        s.finish()
    }
}

impl TbsCertificate {
    pub fn take_from<S: Source>(cons: &mut Constructed<S>) -> Result<Self, DecodeError<S::Error>> {
        // The TbsCertificate data is what's signed by the issuing certificate. To
        // facilitate signature verification, we stash away the raw data so they
        // can be accessed later.
        let mut res = None;

        let captured = cons.capture(|cons| {
            cons.take_sequence(|cons| {
                let version = cons.take_opt_constructed_if(Tag::CTX_0, Version::take_from)?;
                let serial_number = CertificateSerialNumber::take_from(cons)?;
                let signature = AlgorithmIdentifier::take_from(cons)?;
                let issuer = Name::take_from(cons)?;
                let validity = Validity::take_from(cons)?;
                let subject = Name::take_from(cons)?;
                let subject_public_key_info = SubjectPublicKeyInfo::take_from(cons)?;
                let issuer_unique_id = cons.take_opt_constructed_if(Tag::CTX_1, |cons| {
                    UniqueIdentifier::take_from(cons)
                })?;
                let subject_unique_id = cons.take_opt_constructed_if(Tag::CTX_2, |cons| {
                    UniqueIdentifier::take_from(cons)
                })?;
                let extensions =
                    cons.take_opt_constructed_if(Tag::CTX_3, |cons| Extensions::take_from(cons))?;

                res = Some(Self {
                    version,
                    serial_number,
                    signature,
                    issuer,
                    validity,
                    subject,
                    subject_public_key_info,
                    issuer_unique_id,
                    subject_unique_id,
                    extensions,
                    raw_data: None,
                });

                Ok(())
            })
        })?;

        let mut res = res.unwrap();
        res.raw_data = Some(captured.to_vec());

        Ok(res)
    }

    pub fn encode_ref(&self) -> impl Values + '_ {
        encode::sequence((
            self.version
                .as_ref()
                .map(|v| encode::Constructed::new(Tag::CTX_0, u8::from(*v).encode())),
            (&self.serial_number).encode(),
            &self.signature,
            self.issuer.encode_ref(),
            self.validity.encode_ref(),
            self.subject.encode_ref(),
            self.subject_public_key_info.encode_ref(),
            self.issuer_unique_id
                .as_ref()
                .map(|id| id.encode_ref_as(Tag::CTX_1)),
            self.subject_unique_id
                .as_ref()
                .map(|id| id.encode_ref_as(Tag::CTX_2)),
            self.extensions
                .as_ref()
                .map(|extensions| encode::Constructed::new(Tag::CTX_3, extensions.encode_ref())),
        ))
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Version {
    V1 = 0,
    V2 = 1,
    V3 = 2,
}

impl Version {
    pub fn take_from<S: Source>(cons: &mut Constructed<S>) -> Result<Self, DecodeError<S::Error>> {
        match cons.take_primitive_if(Tag::INTEGER, Integer::i8_from_primitive)? {
            0 => Ok(Self::V1),
            1 => Ok(Self::V2),
            2 => Ok(Self::V3),
            _ => Err(cons.content_err("unexpected Version value")),
        }
    }

    pub fn encode(self) -> impl Values {
        u8::from(self).encode()
    }
}

impl From<Version> for u8 {
    fn from(v: Version) -> Self {
        match v {
            Version::V1 => 0,
            Version::V2 => 1,
            Version::V3 => 2,
        }
    }
}

pub type CertificateSerialNumber = Integer;

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Validity {
    pub not_before: Time,
    pub not_after: Time,
}

impl Validity {
    pub fn take_from<S: Source>(cons: &mut Constructed<S>) -> Result<Self, DecodeError<S::Error>> {
        cons.take_sequence(|cons| {
            let not_before = Time::take_from(cons)?;
            let not_after = Time::take_from(cons)?;

            Ok(Self {
                not_before,
                not_after,
            })
        })
    }

    pub fn encode_ref(&self) -> impl Values + '_ {
        encode::sequence((self.not_before.encode_ref(), self.not_after.encode_ref()))
    }
}

pub type UniqueIdentifier = BitString;

/// Subject public key info.
///
/// ```ASN.1
/// SubjectPublicKeyInfo  ::=  SEQUENCE  {
///   algorithm            AlgorithmIdentifier,
///   subjectPublicKey     BIT STRING  }
/// ```
#[derive(Clone, Eq, PartialEq)]
pub struct SubjectPublicKeyInfo {
    pub algorithm: AlgorithmIdentifier,
    pub subject_public_key: BitString,
}

impl Debug for SubjectPublicKeyInfo {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("SubjectPublicKeyInfo");
        s.field("algorithm", &self.algorithm);
        s.field(
            "subject_public_key",
            &format_args!(
                "{} (unused {})",
                hex::encode(self.subject_public_key.octet_bytes().as_ref()),
                self.subject_public_key.unused()
            ),
        );
        s.finish()
    }
}

impl SubjectPublicKeyInfo {
    pub fn take_from<S: Source>(cons: &mut Constructed<S>) -> Result<Self, DecodeError<S::Error>> {
        cons.take_sequence(|cons| {
            let algorithm = AlgorithmIdentifier::take_from(cons)?;
            let subject_public_key = BitString::take_from(cons)?;

            Ok(Self {
                algorithm,
                subject_public_key,
            })
        })
    }

    pub fn encode_ref(&self) -> impl Values + '_ {
        encode::sequence((&self.algorithm, self.subject_public_key.encode_ref()))
    }
}

/// Extensions
///
/// ```ASN.1
/// Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension
/// ```
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Extensions(Vec<Extension>);

impl Extensions {
    pub fn take_opt_from<S: Source>(
        cons: &mut Constructed<S>,
    ) -> Result<Option<Self>, DecodeError<S::Error>> {
        cons.take_opt_sequence(|cons| Self::from_sequence(cons))
    }

    pub fn take_from<S: Source>(cons: &mut Constructed<S>) -> Result<Self, DecodeError<S::Error>> {
        cons.take_sequence(|cons| Self::from_sequence(cons))
    }

    pub fn from_sequence<S: Source>(
        cons: &mut Constructed<S>,
    ) -> Result<Self, DecodeError<S::Error>> {
        let mut extensions = Vec::new();

        while let Some(extension) = Extension::take_opt_from(cons)? {
            extensions.push(extension);
        }

        Ok(Self(extensions))
    }

    pub fn encode_ref(&self) -> impl Values + '_ {
        encode::sequence(&self.0)
    }

    pub fn encode_ref_as(&self, tag: Tag) -> impl Values + '_ {
        encode::sequence_as(tag, &self.0)
    }
}

impl Deref for Extensions {
    type Target = Vec<Extension>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Extensions {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Extension.
///
/// ```ASN.1
/// Extension  ::=  SEQUENCE  {
///      extnID      OBJECT IDENTIFIER,
///      critical    BOOLEAN DEFAULT FALSE,
///      extnValue   OCTET STRING
///                  -- contains the DER encoding of an ASN.1 value
///                  -- corresponding to the extension type identified
///                  -- by extnID
///      }
/// ```
#[derive(Clone, Eq, PartialEq)]
pub struct Extension {
    pub id: Oid,
    pub critical: Option<bool>,
    pub value: OctetString,
}

impl Debug for Extension {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("Extension");
        s.field("id", &format_args!("{}", self.id));
        s.field("critical", &self.critical);
        s.field(
            "value",
            &format_args!("{}", hex::encode(self.value.clone().into_bytes().as_ref())),
        );
        s.finish()
    }
}

impl Extension {
    pub fn take_opt_from<S: Source>(
        cons: &mut Constructed<S>,
    ) -> Result<Option<Self>, DecodeError<S::Error>> {
        cons.take_opt_sequence(|cons| Self::from_sequence(cons))
    }

    pub fn take_from<S: Source>(cons: &mut Constructed<S>) -> Result<Self, DecodeError<S::Error>> {
        cons.take_sequence(|cons| Self::from_sequence(cons))
    }

    fn from_sequence<S: Source>(cons: &mut Constructed<S>) -> Result<Self, DecodeError<S::Error>> {
        let id = Oid::take_from(cons)?;
        let critical = cons.take_opt_bool()?;
        let value = OctetString::take_from(cons)?;

        Ok(Self {
            id,
            critical,
            value,
        })
    }

    pub fn encode_ref(&self) -> impl Values + '_ {
        encode::sequence((
            self.id.encode_ref(),
            if self.critical == Some(true) {
                Some(true.encode())
            } else {
                None
            },
            self.value.encode_ref(),
        ))
    }

    /// Attempt to decode a single OID present in an outer sequence.
    ///
    /// If this works, we return Some. Else None.
    pub fn try_decode_sequence_single_oid(&self) -> Option<Oid> {
        Constructed::decode(self.value.clone().into_source(), Mode::Der, |cons| {
            cons.take_sequence(|cons| Oid::take_from(cons))
        })
        .ok()
    }
}

impl Values for Extension {
    fn encoded_len(&self, mode: Mode) -> usize {
        self.encode_ref().encoded_len(mode)
    }

    fn write_encoded<W: Write>(&self, mode: Mode, target: &mut W) -> Result<(), std::io::Error> {
        self.encode_ref().write_encoded(mode, target)
    }
}

/// Certificate list.
///
/// ```ASN.1
/// CertificateList  ::=  SEQUENCE  {
///      tbsCertList          TBSCertList,
///      signatureAlgorithm   AlgorithmIdentifier,
///      signature            BIT STRING  }
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CertificateList {
    pub tbs_cert_list: TbsCertList,
    pub signature_algorithm: AlgorithmIdentifier,
    pub signature: BitString,
}

impl CertificateList {
    pub fn take_from<S: Source>(cons: &mut Constructed<S>) -> Result<Self, DecodeError<S::Error>> {
        let tbs_cert_list = TbsCertList::take_from(cons)?;
        let signature_algorithm = AlgorithmIdentifier::take_from(cons)?;
        let signature = BitString::take_from(cons)?;

        Ok(Self {
            tbs_cert_list,
            signature_algorithm,
            signature,
        })
    }
src/rfc2986.rs (line 140)
136
137
138
139
140
141
142
143
144
145
146
147
148
    pub fn from_sequence<S: Source>(
        cons: &mut Constructed<S>,
    ) -> Result<Self, DecodeError<S::Error>> {
        let certificate_request_info = CertificationRequestInfo::take_from(cons)?;
        let signature_algorithm = AlgorithmIdentifier::take_from(cons)?;
        let signature = BitString::take_from(cons)?;

        Ok(Self {
            certificate_request_info,
            signature_algorithm,
            signature,
        })
    }
src/rfc5958.rs (line 43)
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
    pub fn take_from<S: Source>(cons: &mut Constructed<S>) -> Result<Self, DecodeError<S::Error>> {
        cons.take_sequence(|cons| {
            let version = Version::take_from(cons)?;
            let private_key_algorithm = PrivateKeyAlgorithmIdentifier::take_from(cons)?;
            let private_key = PrivateKey::take_from(cons)?;
            let attributes = cons.take_opt_constructed_if(Tag::CTX_0, |cons| {
                let mut attributes = Attributes::default();

                while let Some(attribute) = Attribute::take_opt_from(cons)? {
                    attributes.push(attribute);
                }

                Ok(attributes)
            })?;
            let public_key =
                cons.take_opt_constructed_if(Tag::CTX_1, |cons| BitString::take_from(cons))?;

            Ok(Self {
                version,
                private_key_algorithm,
                private_key,
                attributes,
                public_key,
            })
        })
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Returns the length of the encoded values for the given mode.
Encodes the values in the given mode and writes them to target.
Converts the encoder into one with an explicit tag.
Captures the encoded values in the given mode.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.