### Creating a Scraped Example in Rust Source: https://docs.rs/x509-parser/latest/scrape-examples-help.html This example demonstrates how to create a usage example for a documented item in Rust. The example should call the documented item from an external crate. ```rust // examples/ex.rs fn main() { a_crate::a_func(); } ``` -------------------------------- ### Example Implementation of X509CertificateVisitor Source: https://docs.rs/x509-parser/latest/x509_parser/visitor/trait.X509CertificateVisitor.html This example demonstrates how to implement the X509CertificateVisitor trait to extract specific information like issuer, subject, and basic constraints from an X.509 certificate. ```APIDOC ## §Example ```rust use x509_parser::prelude::*; use x509_parser::visitor::X509CertificateVisitor; #[derive(Debug, Default)] struct SubjectIssuerVisitor { issuer: String, subject: String, is_ca: bool, } impl X509CertificateVisitor for SubjectIssuerVisitor { fn visit_issuer(&mut self, name: &X509Name<'_>) { self.issuer = name.to_string(); } fn visit_subject(&mut self, name: &X509Name<'_>) { self.subject = name.to_string(); } fn visit_extension_basic_constraints(&mut self, bc: &BasicConstraints) { self.is_ca = bc.ca; } } ``` ``` -------------------------------- ### Vector Capacity Example Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Demonstrates how to check the capacity of a vector. This is useful for pre-allocating memory to avoid reallocations. ```rust let mut vec: Vec = Vec::with_capacity(10); vec.push(42); assert!(vec.capacity() >= 10); ``` -------------------------------- ### Get Certificate Version Source: https://docs.rs/x509-parser/latest/x509_parser/certificate/struct.TbsCertificate.html Retrieves the version of the encoded X.509 certificate. This example shows how to access the version and conditionally print it based on its value. ```rust let version = x509.version(); if version.0 < 3 { println!(" Version: {version}"); } else { println!(" Version: INVALID({})", version.0); } ``` -------------------------------- ### Example Usage of CertificateRevocationListVisitor Source: https://docs.rs/x509-parser/latest/src/x509_parser/visitor/crl_visitor.rs.html This example demonstrates how to implement the CertificateRevocationListVisitor trait to collect revoked certificate serial numbers. ```APIDOC use der_parser::num_bigint::BigUint; use x509_parser::prelude::*; use x509_parser::visitor::CertificateRevocationListVisitor; #[derive(Debug, Default)] struct RevokedCertsVisitor { certificates: Vec, } impl CertificateRevocationListVisitor for RevokedCertsVisitor { fn visit_revoked_certificate(&mut self, certificate: &RevokedCertificate<'_>) { self.certificates.push(certificate.user_certificate.clone()); } } ``` -------------------------------- ### Example Usage of Validator Source: https://docs.rs/x509-parser/latest/x509_parser/validate/trait.Validator.html This example demonstrates how to use the `Validator` trait with `X509StructureValidator` and a `VecLogger` to validate an X.509 certificate and collect warnings/errors. ```APIDOC ## Examples Collecting warnings and errors to `Vec`: ```rust use x509_parser::certificate::X509Certificate; use x509_parser::validate::*; #[cfg(feature = "validate")] fn validate_certificate(x509: &X509Certificate<'_>) -> Result<(), &'static str> { let mut logger = VecLogger::default(); println!(" Subject: {}", x509.subject()); // validate and print warnings and errors to stderr let ok = X509StructureValidator.validate(&x509, &mut logger); print!("Structure validation status: "); if ok { println!("Ok"); } else { println!("FAIL"); } for warning in logger.warnings() { eprintln!(" [W] {}", warning); } for error in logger.errors() { eprintln!(" [E] {}", error); } println!(); if !logger.errors().is_empty() { return Err("validation failed"); } Ok(()) } ``` ``` -------------------------------- ### Create a new TbsCertificateParser Source: https://docs.rs/x509-parser/latest/x509_parser/certificate/struct.TbsCertificateParser.html Instantiates a new TbsCertificateParser with default settings. This is the starting point for building a certificate parser. ```rust pub const fn new() -> Self ``` -------------------------------- ### X509Certificate Usage Example Source: https://docs.rs/x509-parser/latest/x509_parser/certificate/struct.X509Certificate.html Demonstrates how to access common fields like subject and issuer, and raw serial number from an X509Certificate. ```APIDOC ```rust fn display_x509_info(x509: &X509Certificate<'_>) { let subject = x509.subject(); let issuer = x509.issuer(); println!("X.509 Subject: {}", subject); println!("X.509 Issuer: {}", issuer); println!("X.509 serial: {}", x509.tbs_certificate.raw_serial_as_string()); } ``` ``` -------------------------------- ### Example Usage of FromDer Source: https://docs.rs/x509-parser/latest/x509_parser/prelude/trait.FromDer.html Demonstrates how to implement and use the FromDer trait for a custom type, showing the parsing process. ```APIDOC ## §Examples ``` use asn1_rs::{Any, CheckDerConstraints, DerAutoDerive, Result, Tag}; use std::convert::TryFrom; // The type to be decoded #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct MyType(pub u32); impl<'a> TryFrom> for MyType { type Error = asn1_rs::Error; fn try_from(any: Any<'a>) -> Result { any.tag().assert_eq(Tag::Integer)?; // for this fictive example, the type contains the number of characters let n = any.data.len() as u32; Ok(MyType(n)) } } impl CheckDerConstraints for MyType { fn check_constraints(any: &Any) -> Result<()> { any.header.assert_primitive()?; Ok(()) } } impl DerAutoDerive for MyType {} // The above code provides a `FromDer` implementation for free. // Example of parsing code: use asn1_rs::FromDer; let input = &[2, 1, 2]; // Objects can be parsed using `from_der`, which returns the remaining bytes // and the parsed object: let (rem, my_type) = MyType::from_der(input).expect("parsing failed"); ``` ``` -------------------------------- ### Example Usage of X509CertificateVisitor Source: https://docs.rs/x509-parser/latest/src/x509_parser/visitor/certificate_visitor.rs.html Demonstrates how to implement the `X509CertificateVisitor` trait to extract specific information like issuer, subject, and CA status from an X.509 certificate. ```APIDOC ## Example: SubjectIssuerVisitor This example shows a concrete implementation of `X509CertificateVisitor` to collect the issuer and subject names, and to check if the certificate is a Certificate Authority (CA). ```rust use x509_parser::prelude::* use x509_parser::visitor::X509CertificateVisitor; #[derive(Debug, Default)] struct SubjectIssuerVisitor { issuer: String, subject: String, is_ca: bool, } impl X509CertificateVisitor for SubjectIssuerVisitor { fn visit_issuer(&mut self, name: &X509Name<'_>) { self.issuer = name.to_string(); } fn visit_subject(&mut self, name: &X509Name<'_>) { self.subject = name.to_string(); } fn visit_extension_basic_constraints(&mut self, bc: &BasicConstraints) { self.is_ca = bc.ca; } } // To use this visitor: // let mut visitor = SubjectIssuerVisitor::default(); // certificate.walk(&mut visitor); // println!("Issuer: {}, Subject: {}, Is CA: {}", visitor.issuer, visitor.subject, visitor.is_ca); ``` ``` -------------------------------- ### X509StructureValidator Usage Example Source: https://docs.rs/x509-parser/latest/x509_parser/validate/struct.X509StructureValidator.html This example demonstrates how to use X509StructureValidator to validate an X509Certificate, collecting warnings and errors. ```APIDOC ## Validate Certificate Structure ### Description Validates the structure of an `X509Certificate` using `X509StructureValidator`. It collects any warnings or errors encountered during validation into a `VecLogger` and prints them to standard output and standard error. ### Method `validate` method of `X509StructureValidator` ### Parameters - `x509`: A reference to the `X509Certificate` to be validated. - `logger`: A mutable reference to a `Logger` implementation (e.g., `VecLogger`) to store validation results. ### Request Example ```rust use x509_parser::certificate::X509Certificate; use x509_parser::validate::* #[cfg(feature = "validate")] fn validate_certificate(x509: &X509Certificate<'_>) -> Result<(), &'static str> { let mut logger = VecLogger::default(); println!(" Subject: {}", x509.subject()); // validate and print warnings and errors to stderr let ok = X509StructureValidator.validate(&x509, &mut logger); print!("Structure validation status: "); if ok { println!("Ok"); } else { println!("FAIL"); } for warning in logger.warnings() { eprintln!(" [W] {}", warning); } for error in logger.errors() { eprintln!(" [E] {}", error); } println!(); if !logger.errors().is_empty() { return Err("validation failed"); } Ok(()) } ``` ### Response - Returns `Ok(())` if validation is successful and no errors are found. - Returns `Err("validation failed")` if any errors are detected during validation. ### Notes - This functionality is only available when the `validate` crate feature is enabled. ``` -------------------------------- ### Example Usage of X509Extension Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.X509Extension.html Demonstrates how to parse a DER-encoded X.509 extension and access its properties, including the OID, criticality, and parsed content. ```APIDOC # §Example ```rust use x509_parser::prelude::FromDer; use x509_parser::extensions::{X509Extension, ParsedExtension}; static DER: &[u8] = &[ 0x30, 0x1D, 0x06, 0x03, 0x55, 0x1D, 0x0E, 0x04, 0x16, 0x04, 0x14, 0xA3, 0x05, 0x2F, 0x18, 0x60, 0x50, 0xC2, 0x89, 0x0A, 0xDD, 0x2B, 0x21, 0x4F, 0xFF, 0x8E, 0x4E, 0xA8, 0x30, 0x31, 0x36 ]; let res = X509Extension::from_der(DER); match res { Ok((_rem, ext)) => { println!("Extension OID: {}", ext.oid); println!(" Critical: {}", ext.critical); let parsed_ext = ext.parsed_extension(); assert!(!parsed_ext.unsupported()); assert!(parsed_ext.error().is_none()); if let ParsedExtension::SubjectKeyIdentifier(key_id) = parsed_ext { assert!(key_id.0.len() > 0); } else { panic!("Extension has wrong type"); } }, _ => panic!("x509 extension parsing failed: {:?}", res), } ``` ``` -------------------------------- ### X509CertificateParser Usage Example Source: https://docs.rs/x509-parser/latest/x509_parser/certificate/struct.X509CertificateParser.html Demonstrates how to create an X509CertificateParser instance and use it to parse a DER-encoded certificate, with an option to disable deep parsing of extensions. ```APIDOC ## Example To parse a certificate without parsing extensions: ```rust use x509_parser::certificate::X509CertificateParser; use x509_parser::nom::Parser; // create a parser that will not parse extensions let mut parser = X509CertificateParser::new() .with_deep_parse_extensions(false); let res = parser.parse(DER); match res { Ok((_rem, x509)) => { let subject = x509.subject(); let issuer = x509.issuer(); println!("X.509 Subject: {}", subject); println!("X.509 Issuer: {}", issuer); }, _ => panic!("x509 parsing failed: {:?}", res), } ``` ``` -------------------------------- ### Zero-Sized Elements Capacity Example Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Illustrates that a vector with zero-sized elements has a capacity of usize::MAX. ```rust #[derive(Clone)] struct ZeroSized; fn main() { assert_eq!(std::mem::size_of::(), 0); let v = vec![ZeroSized; 0]; assert_eq!(v.capacity(), usize::MAX); } ``` -------------------------------- ### Documenting a Function in Rust Source: https://docs.rs/x509-parser/latest/scrape-examples-help.html This example shows how to document a public function in your Rust library. Ensure the function is public to be accessible by external crates. ```rust // src/lib.rs pub fn a_func() {} ``` -------------------------------- ### Example CRL Visitor Implementation Source: https://docs.rs/x509-parser/latest/src/x509_parser/visitor/crl_visitor.rs.html A sample implementation of the `CertificateRevocationListVisitor` trait to collect revoked certificate serial numbers. ```rust #[derive(Debug, Default)] struct RevokedCertsVisitor { certificates: Vec, } impl CertificateRevocationListVisitor for RevokedCertsVisitor { fn visit_revoked_certificate(&mut self, certificate: &RevokedCertificate) { self.certificates.push(certificate.user_certificate.clone()); } } let mut visitor = RevokedCertsVisitor::default(); ``` -------------------------------- ### CertificateRevocationList Parsing Example Source: https://docs.rs/x509-parser/latest/x509_parser/revocation_list/struct.CertificateRevocationList.html Demonstrates how to parse a DER-encoded Certificate Revocation List and iterate over revoked certificates. ```APIDOC ## Example To parse a CRL and print information about revoked certificates: ```rust use x509_parser::prelude::FromDer; use x509_parser::revocation_list::CertificateRevocationList; let res = CertificateRevocationList::from_der(DER); match res { Ok((_rem, crl)) => { for revoked in crl.iter_revoked_certificates() { println!("Revoked certificate serial: {}", revoked.raw_serial_as_string()); println!(" Reason: {}", revoked.reason_code().unwrap_or_default().1); } }, _ => panic!("CRL parsing failed: {:?}", res), } ``` ``` -------------------------------- ### Get Element Index by Reference Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Use `element_offset` to find the index of an element given a reference to it. This method relies on pointer arithmetic and does not compare element values. It returns `None` if the reference is not aligned with the start of an element. ```rust let nums: &[u32] = &[1, 7, 1, 1]; let num = &nums[2]; assert_eq!(num, &1); assert_eq!(nums.element_offset(num), Some(2)); ``` ```rust let arr: &[[u32; 2]] = &[[0, 1], [2, 3]]; let flat_arr: &[u32] = arr.as_flattened(); let ok_elm: &[u32; 2] = flat_arr[0..2].try_into().unwrap(); let weird_elm: &[u32; 2] = flat_arr[1..3].try_into().unwrap(); assert_eq!(ok_elm, &[0, 1]); assert_eq!(weird_elm, &[1, 2]); assert_eq!(arr.element_offset(ok_elm), Some(0)); // Points to element 0 assert_eq!(arr.element_offset(weird_elm), None); // Points between element 0 and 1 ``` -------------------------------- ### BasicExtension::new Constructor Source: https://docs.rs/x509-parser/latest/x509_parser/certificate/struct.BasicExtension.html Creates a new BasicExtension instance. ```APIDOC ### impl BasicExtension #### pub const fn new(critical: bool, value: T) -> Self Creates a new `BasicExtension` with the specified critical flag and value. ``` -------------------------------- ### Implementing FromDer via TryFrom and CheckDerConstraints Source: https://docs.rs/x509-parser/latest/x509_parser/prelude/trait.FromDer.html Shows how to implement `TryFrom` and `CheckDerConstraints` to automatically gain a `FromDer` implementation. This is the recommended approach for library authors. ```rust use asn1_rs::{Any, CheckDerConstraints, DerAutoDerive, Result, Tag}; use std::convert::TryFrom; // The type to be decoded #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct MyType(pub u32); impl<'a> TryFrom> for MyType { type Error = asn1_rs::Error; fn try_from(any: Any<'a>) -> Result { any.tag().assert_eq(Tag::Integer)?; // for this fictive example, the type contains the number of characters let n = any.data.len() as u32; Ok(MyType(n)) } } impl CheckDerConstraints for MyType { fn check_constraints(any: &Any) -> Result<()> { any.header.assert_primitive()?; Ok(()) } } impl DerAutoDerive for MyType {} ``` ```rust use asn1_rs::FromDer; let input = &[2, 1, 2]; // Objects can be parsed using `from_der`, which returns the remaining bytes // and the parsed object: let (rem, my_type) = MyType::from_der(input).expect("parsing failed"); ``` -------------------------------- ### TbsCertList Implementations Source: https://docs.rs/x509-parser/latest/x509_parser/revocation_list/struct.TbsCertList.html Provides methods for interacting with TbsCertList, including accessing extensions and walking visitors. ```APIDOC ## impl TbsCertList<'_> ### pub fn extensions(&self) -> &[X509Extension<'_>] Returns the certificate extensions. ### pub fn iter_extensions(&self) -> impl Iterator> Returns an iterator over the certificate extensions. ### pub fn find_extension(&self, oid: &Oid<'_>) -> Option<&X509Extension<'_>> Searches for an extension with the given `Oid`. Note: if there are several extensions with the same `Oid`, the first one is returned. ### pub fn extensions_map(&self) -> Result, &X509Extension<'_>>, X509Error> Builds and returns a map of extensions. If an extension is present twice, this will fail and return `DuplicateExtensions`. ## impl TbsCertList<'_> ### pub fn walk(&self, visitor: &mut V) Run the provided `visitor` over the `TbsCertList` object. ``` -------------------------------- ### Get Last Chunk Mutably Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Safely get a mutable reference to the last N elements of a slice. Returns None if the slice is shorter than N. ```rust let x = &mut [0, 1, 2]; if let Some(last) = x.last_chunk_mut::<2>() { last[0] = 10; last[1] = 20; } assert_eq!(x, &[0, 10, 20]); assert_eq!(None, x.last_chunk_mut::<4>()); ``` -------------------------------- ### X509CertificateParser Methods Source: https://docs.rs/x509-parser/latest/x509_parser/certificate/struct.X509CertificateParser.html Provides documentation for the constructor and configuration method of the X509CertificateParser. ```APIDOC ## X509CertificateParser ### impl X509CertificateParser #### pub const fn new() -> Self Creates a new `X509CertificateParser` with default settings. #### pub const fn with_deep_parse_extensions( self, deep_parse_extensions: bool, ) -> Self Configures the parser to either perform deep parsing of X.509v3 extensions or skip it for performance. `true` enables deep parsing, `false` disables it. ``` -------------------------------- ### Get Last Chunk of a Slice Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Use `last_chunk` to get an immutable reference to the last `N` elements of a slice as an array. Returns `None` if the slice is shorter than `N`. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[40, 30]), u.last_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.last_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.last_chunk::<0>()); ``` -------------------------------- ### From Source: https://docs.rs/x509-parser/latest/x509_parser/pem/struct.Pem.html Provides functionality to create an instance from another type. ```APIDOC ## fn from(t: T) -> T ### Description Returns the argument unchanged. ### Method `from` ``` -------------------------------- ### Get First Chunk of a Slice Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Use `first_chunk` to get an immutable reference to the first `N` elements of a slice as an array. Returns `None` if the slice is shorter than `N`. ```rust let u = [10, 40, 30]; assert_eq!(Some(&[10, 40]), u.first_chunk::<2>()); let v: &[i32] = &[10]; assert_eq!(None, v.first_chunk::<2>()); let w: &[i32] = &[]; assert_eq!(Some(&[]), w.first_chunk::<0>()); ``` -------------------------------- ### X509Extension::new Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.X509Extension.html Creates a new X509Extension instance with the provided OID, criticality flag, raw value, and parsed extension content. ```APIDOC ### impl<'a> X509Extension<'a> #### pub const fn new(oid: Oid<'a>, critical: bool, value: &'a [u8], parsed_extension: ParsedExtension<'a>) -> X509Extension<'a> Creates a new extension with the provided values. ``` -------------------------------- ### Get Mutable First Chunk of a Slice Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Use `first_chunk_mut` to get a mutable reference to the first `N` elements of a slice as a mutable array. Returns `None` if the slice is shorter than `N`. ```rust let x = &mut [0, 1, 2]; if let Some(first) = x.first_chunk_mut::<2>() { first[0] = 5; first[1] = 4; } assert_eq!(x, &[5, 4, 2]); assert_eq!(None, x.first_chunk_mut::<4>()); ``` -------------------------------- ### Get Mutable Reference to Last Element of a Slice Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Use `last_mut` to safely get a mutable reference to the last element of a slice. Returns `None` if the slice is empty. Useful for in-place updates. ```rust let x = &mut [0, 1, 2]; if let Some(last) = x.last_mut() { *last = 10; } assert_eq!(x, &[0, 1, 10]); let y: &mut [i32] = &mut []; assert_eq!(None, y.last_mut()); ``` -------------------------------- ### AccessDescription::new Constructor Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.AccessDescription.html Creates a new AccessDescription instance with the specified access method and access location. ```APIDOC ## impl<'a> AccessDescription<'a> ### pub const fn new( access_method: Oid<'a>, access_location: GeneralName<'a>, ) -> Self Creates a new AccessDescription. ``` -------------------------------- ### Split Off Slice Starting from Third Element Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Use `split_off` with a range starting from an index to remove and return the latter part of a slice. The original slice is updated to contain only the elements before the split point. ```rust let mut slice: &[_] = &['a', 'b', 'c', 'd']; let mut tail = slice.split_off(2..).unwrap(); assert_eq!(slice, &['a', 'b']); assert_eq!(tail, &['c', 'd']); ``` -------------------------------- ### TbsCertificateParser::new Source: https://docs.rs/x509-parser/latest/x509_parser/certificate/struct.TbsCertificateParser.html Creates a new instance of TbsCertificateParser with default settings. ```APIDOC ## `TbsCertificateParser::new()` ### Description Creates a new instance of `TbsCertificateParser` with default settings. ### Method `new()` ### Returns A new `TbsCertificateParser` instance. ``` -------------------------------- ### Getting Slice Length Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Returns the number of elements in a slice. ```rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### X509Extension Equality Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.X509Extension.html Details how to compare X509Extension instances for equality. ```APIDOC ## `impl<'a> PartialEq for X509Extension<'a>` ### Description Allows for equality comparison between X509Extension instances. #### `fn eq(&self, other: &X509Extension<'a>) -> bool` Tests for `self` and `other` values to be equal, and is used by `==`. #### `fn ne(&self, other: &Rhs) -> bool` Tests for `!=`. ``` -------------------------------- ### Getting the Tag Source: https://docs.rs/x509-parser/latest/x509_parser/signature_value/struct.EcdsaSigValue.html Returns the ASN.1 tag associated with the type. ```rust fn tag(&self) -> Tag ``` -------------------------------- ### Getting Vector Length Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Returns the number of elements currently in the vector. ```rust let a = vec![1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Type ID Source: https://docs.rs/x509-parser/latest/x509_parser/pem/struct.PemIterator.html Gets the `TypeId` of `self`. This is part of the `Any` trait implementation. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Returns The `TypeId` of the object. ``` -------------------------------- ### iter Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Returns an iterator over the slice, yielding elements from start to end. ```APIDOC ## pub fn iter(&self) -> Iter<'_, T> ### Description Returns an iterator over the slice. The iterator yields all items from start to end. ### Examples ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` ``` -------------------------------- ### Type Conversions and Borrowing Source: https://docs.rs/x509-parser/latest/x509_parser/certificate/struct.Validity.html Demonstrates various type conversion and borrowing implementations available for types that implement `Any`, `AsTaggedExplicit`, `AsTaggedImplicit`, `Borrow`, `BorrowMut`, `CloneToUninit`, `From`, `Into`, `ToOwned`, `TryFrom`, and `TryInto`. ```APIDOC ## Blanket Implementations ### impl Any for T where T: 'static + ?Sized, Source§ #### fn type_id(&self) -> TypeId Gets the `TypeId` of `self`. Read more Source§ ### impl<'a, T, E> AsTaggedExplicit<'a, E> for T where T: 'a, Source§ #### fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E> Source§ ### impl<'a, T, E> AsTaggedImplicit<'a, E> for T where T: 'a, Source§ #### fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E> Source§ ### impl Borrow for T where T: ?Sized, Source§ #### fn borrow(&self) -> &T Immutably borrows from an owned value. Read more Source§ ### impl BorrowMut for T where T: ?Sized, Source§ #### fn borrow_mut(&mut self) -> &mut T Mutably borrows from an owned value. Read more Source§ ### impl CloneToUninit for T where T: Clone, Source§ #### unsafe fn clone_to_uninit(&self, dest: *mut u8) 🔬This is a nightly-only experimental API. (`clone_to_uninit`) Performs copy-assignment from `self` to `dest`. Read more Source§ ### impl From for T Source§ #### fn from(t: T) -> T Returns the argument unchanged. Source§ ### impl Into for T where U: From, Source§ #### fn into(self) -> U Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From for U` chooses to do. Source§ ### impl ToOwned for T where T: Clone, Source§ #### type Owned = T The resulting type after obtaining ownership. Source§ #### fn to_owned(&self) -> T Creates owned data from borrowed data, usually by cloning. Read more Source§ #### fn clone_into(&self, target: &mut T) Uses borrowed data to replace owned data, usually by cloning. Read more Source§ ### impl TryFrom for T where U: Into, Source§ #### type Error = Infallible The type returned in the event of a conversion error. Source§ #### fn try_from(value: U) -> Result>::Error> Performs the conversion. Source§ ### impl TryInto for T where U: TryFrom, Source§ #### type Error = >::Error The type returned in the event of a conversion error. Source§ #### fn try_into(self) -> Result>::Error> Performs the conversion. Source§ ``` -------------------------------- ### Get AlgorithmIdentifier parameters Source: https://docs.rs/x509-parser/latest/src/x509_parser/x509.rs.html Returns an optional reference to the algorithm's parameters. ```rust pub const fn parameters(&'a self) -> Option<&'a Any<'a>> { self.parameters.as_ref() } ``` -------------------------------- ### X509Error::provide Method (Experimental) Source: https://docs.rs/x509-parser/latest/x509_parser/error/enum.X509Error.html An experimental, nightly-only API for providing type-based access to error context, intended for error reporting. ```rust fn provide<'a>(&'a self, request: &mut Request<'a>) ``` -------------------------------- ### Get AlgorithmIdentifier OID Source: https://docs.rs/x509-parser/latest/src/x509_parser/x509.rs.html Returns a constant reference to the algorithm's OID. ```rust pub const fn oid(&'a self) -> &'a Oid<'a> { &self.algorithm } ``` -------------------------------- ### Get CRL Entry Extensions Source: https://docs.rs/x509-parser/latest/x509_parser/certification_request/struct.X509CertificationRequestInfo.html Retrieves all CRL entry extensions from the X509CertificationRequestInfo. ```rust pub fn attributes(&self) -> &[X509CriAttribute<'_>] ``` -------------------------------- ### Get CRL Entry Extensions Source: https://docs.rs/x509-parser/latest/src/x509_parser/revocation_list.rs.html Returns a slice of the CRL entry extensions. ```rust pub fn extensions(&self) -> &[X509Extension<'_>] { &self.extensions } ``` -------------------------------- ### CloneToUninit Source: https://docs.rs/x509-parser/latest/x509_parser/pem/struct.Pem.html Provides experimental functionality for cloning data into uninitialized memory. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description 🔬This is a nightly-only experimental API. (`clone_to_uninit`) Performs copy-assignment from `self` to `dest`. ### Method `clone_to_uninit` ``` -------------------------------- ### X509ExtensionParser Constructors Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.X509ExtensionParser.html Provides methods to create new instances of X509ExtensionParser, with options for deep parsing of extensions. ```APIDOC ## `new()` ### Description Creates a new instance of `X509ExtensionParser` with default settings. ### Signature ```rust pub const fn new() -> Self ``` ## `with_deep_parse_extensions(deep_parse_extensions: bool)` ### Description Creates a new instance of `X509ExtensionParser` and configures whether to perform deep parsing of extensions. ### Signature ```rust pub const fn with_deep_parse_extensions(self, deep_parse_extensions: bool) -> Self ``` ### Parameters - `deep_parse_extensions` (bool) - If true, enables deep parsing of extensions. ``` -------------------------------- ### Iterating over RelativeDistinguishedName components Source: https://docs.rs/x509-parser/latest/x509_parser/x509/struct.RelativeDistinguishedName.html Shows how to get an iterator over the AttributeTypeAndValue components within a RelativeDistinguishedName. ```APIDOC ## `RelativeDistinguishedName::iter` ### Description Return an iterator over the components of this object. ### Signature ```rust pub fn iter(&self) -> impl Iterator> ``` ### Returns An iterator yielding references to `AttributeTypeAndValue`. ``` -------------------------------- ### visit_version Source: https://docs.rs/x509-parser/latest/x509_parser/visitor/trait.CertificateRevocationListVisitor.html Invoked for the 'version' field of the TBSCertList. ```APIDOC ## visit_version ### Description Invoked for the "version" field of the TBSCertList ### Signature ```rust fn visit_version(&mut self, _version: Option<&X509Version>) ``` ``` -------------------------------- ### PemIterator::step_by Source: https://docs.rs/x509-parser/latest/x509_parser/pem/struct.PemIterator.html Creates an iterator starting at the same point, but stepping by the given amount at each iteration. ```APIDOC ## PemIterator::step_by ### Description Creates an iterator starting at the same point, but stepping by the given amount at each iteration. Read more ### Method `step_by(self, step: usize) -> StepBy` ### Constraints `where Self: Sized` ``` -------------------------------- ### Implement X509CertificateVisitor for Custom Visitor Source: https://docs.rs/x509-parser/latest/x509_parser/visitor/trait.X509CertificateVisitor.html Example of implementing the X509CertificateVisitor trait to extract issuer, subject, and CA status from a certificate. This demonstrates how to use specific visitor methods for different certificate components. ```rust use x509_parser::prelude::*; use x509_parser::visitor::X509CertificateVisitor; #[derive(Debug, Default)] struct SubjectIssuerVisitor { issuer: String, subject: String, is_ca: bool, } impl X509CertificateVisitor for SubjectIssuerVisitor { fn visit_issuer(&mut self, name: &X509Name<'_>) { self.issuer = name.to_string(); } fn visit_subject(&mut self, name: &X509Name<'_>) { self.subject = name.to_string(); } fn visit_extension_basic_constraints(&mut self, bc: &BasicConstraints) { self.is_ca = bc.ca; } } ``` -------------------------------- ### CloneToUninit Implementation (Nightly) Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.PolicyConstraints.html An experimental nightly-only API for performing copy-assignment from self to an uninitialized destination. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) where T: Clone, { // ... implementation details ... } ``` -------------------------------- ### Get Attribute Value Source: https://docs.rs/x509-parser/latest/x509_parser/x509/struct.AttributeTypeAndValue.html Retrieves a reference to the Any type representing the attribute value from an AttributeTypeAndValue instance. ```rust pub const fn attr_value(&self) -> &Any<'a> ``` -------------------------------- ### Default Implementation for X509ExtensionParser Source: https://docs.rs/x509-parser/latest/src/x509_parser/extensions/mod.rs.html Provides a default implementation for `X509ExtensionParser`, allowing it to be created using `X509ExtensionParser::default()`. ```rust impl Default for X509ExtensionParser { fn default() -> Self { X509ExtensionParser::new() } } ``` -------------------------------- ### Get Attribute Type Source: https://docs.rs/x509-parser/latest/x509_parser/x509/struct.AttributeTypeAndValue.html Retrieves a reference to the Oid representing the attribute type from an AttributeTypeAndValue instance. ```rust pub const fn attr_type(&self) -> &Oid<'a> ``` -------------------------------- ### Basic SIMD Slice Splitting Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Demonstrates splitting a slice into mutable prefix, middle SIMD types, and suffix using `as_simd_mut`. This is an experimental API and requires the `portable_simd` feature. ```rust #![feature(portable_simd)] use core::simd::prelude::*; let short = &[1, 2, 3]; let (prefix, middle, suffix) = short.as_simd::<4>(); assert_eq!(middle, []); // Not enough elements for anything in the middle // They might be split in any possible way between prefix and suffix let it = prefix.iter().chain(suffix).copied(); assert_eq!(it.collect::>(), vec![1, 2, 3]); fn basic_simd_sum(x: &[f32]) -> f32 { use std::ops::Add; let (prefix, middle, suffix) = x.as_simd(); let sums = f32x4::from_array([ prefix.iter().copied().sum(), 0.0, 0.0, suffix.iter().copied().sum(), ]); let sums = middle.iter().copied().fold(sums, f32x4::add); sums.reduce_sum() } let numbers: Vec = (1..101).map(|x| x as _).collect(); assert_eq!(basic_simd_sum(&numbers[1..99]), 4949.0); ``` -------------------------------- ### Get Revoked Certificate Serial Number Source: https://docs.rs/x509-parser/latest/src/x509_parser/revocation_list.rs.html Returns a reference to the serial number of the revoked certificate. ```rust pub fn serial(&self) -> &BigUint { &self.user_certificate } ``` -------------------------------- ### Into Source: https://docs.rs/x509-parser/latest/x509_parser/pem/struct.Pem.html Provides functionality to convert an instance into another type. ```APIDOC ## fn into(self) -> U ### Description Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From for U` chooses to do. ### Method `into` ``` -------------------------------- ### Get current time as ASN1Time Source: https://docs.rs/x509-parser/latest/src/x509_parser/time.rs.html Creates an `ASN1Time` object representing the current UTC time. ```rust pub fn now() -> Self { ASN1Time::new(OffsetDateTime::now_utc()) } ``` -------------------------------- ### iter_mut Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Returns an iterator that allows modifying each value in the slice, yielding elements from start to end. ```APIDOC ## pub fn iter_mut(&mut self) -> IterMut<'_, T> ### Description Returns an iterator that allows modifying each value. The iterator yields all items from start to end. ### Examples ```rust let x = &mut [1, 2, 4]; for elem in x.iter_mut() { *elem += 2; } assert_eq!(x, &[3, 4, 6]); ``` ``` -------------------------------- ### Parse RSAAES-OAEP Signature Algorithm Source: https://docs.rs/x509-parser/latest/x509_parser/signature_algorithm/struct.RsaAesOaepParams.html This example demonstrates how to parse and extract information from an RSAAES-OAEP signature algorithm identifier. It shows how to retrieve the hash algorithm, mask generation function, and pSource algorithm. ```rust 230fn print_x509_signature_algorithm(signature_algorithm: &AlgorithmIdentifier, indent: usize) { 231 match SignatureAlgorithm::try_from(signature_algorithm) { 232 Ok(sig_alg) => { 233 print!(" Signature Algorithm: "); 234 match sig_alg { 235 SignatureAlgorithm::DSA => println!("DSA"), 236 SignatureAlgorithm::ECDSA => println!("ECDSA"), 237 SignatureAlgorithm::ED25519 => println!("ED25519"), 238 SignatureAlgorithm::RSA => println!("RSA"), 239 SignatureAlgorithm::RSASSA_PSS(params) => { 240 println!("RSASSA-PSS"); 241 let indent_s = format!("{:indent$}", "", indent = indent + 2); 242 println!( 243 "{}Hash Algorithm: {}", 244 indent_s, 245 format_oid(params.hash_algorithm_oid()), 246 ); 247 print!("{indent_s}Mask Generation Function: "); 248 if let Ok(mask_gen) = params.mask_gen_algorithm() { 249 println!( 250 "{}/{}", 251 format_oid(&mask_gen.mgf), 252 format_oid(&mask_gen.hash), 253 ); 254 } else { 255 println!("INVALID"); 256 } 257 println!("{}Salt Length: {}", indent_s, params.salt_length()); 258 } 259 SignatureAlgorithm::RSAAES_OAEP(params) => { 260 println!("RSAAES-OAEP"); 261 let indent_s = format!("{:indent$}", "", indent = indent + 2); 262 println!( 263 "{}Hash Algorithm: {}", 264 indent_s, 265 format_oid(params.hash_algorithm_oid()), 266 ); 267 print!("{indent_s}Mask Generation Function: "); 268 if let Ok(mask_gen) = params.mask_gen_algorithm() { 269 println!( 270 "{}/{}", 271 format_oid(&mask_gen.mgf), 272 format_oid(&mask_gen.hash), 273 ); 274 } else { 275 println!("INVALID"); 276 } 277 println!( 278 "{}pSourceFunc: {}", 279 indent_s, 280 format_oid(¶ms.p_source_alg().algorithm), 281 ); 282 } 283 } 284 } 285 Err(e) => { 286 eprintln!("Could not parse signature algorithm: {e}"); 287 println!(" Signature Algorithm:"); 288 print_x509_digest_algorithm(signature_algorithm, indent); 289 } 290 } 291} ``` -------------------------------- ### Filling a vector using a closure Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Shows how to use `fill_with` to populate a vector by repeatedly calling a closure. This example uses `Default::default` to fill the vector with default values. ```rust let mut buf = vec![1; 10]; buf.fill_with(Default::default); assert_eq!(buf, vec![0; 10]); ``` -------------------------------- ### X509Extension PartialEq Implementation Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.X509Extension.html Provides methods for comparing two X509Extension instances for equality. ```rust fn eq(&self, other: &X509Extension<'a>) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### X509Extension Cloning Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.X509Extension.html Provides information on cloning X509Extension instances. ```APIDOC ## `impl<'a> Clone for X509Extension<'a>` ### Description Provides methods for cloning X509Extension objects. #### `fn clone(&self) -> X509Extension<'a>` Returns a duplicate of the value. #### `fn clone_from(&mut self, source: &Self)` Performs copy-assignment from `source`. ``` -------------------------------- ### Get Certificate Extensions Source: https://docs.rs/x509-parser/latest/x509_parser/revocation_list/struct.TbsCertList.html Retrieves all certificate extensions from the TbsCertList. This method returns a slice of X509Extension objects. ```rust pub fn extensions(&self) -> &[X509Extension<'_>] ``` -------------------------------- ### Get Raw Serial Number Bytes Source: https://docs.rs/x509-parser/latest/src/x509_parser/revocation_list.rs.html Retrieves the raw byte slice of the certificate serial number. ```rust pub fn raw_serial(&self) -> &[u8] { self.raw_serial } ``` -------------------------------- ### PolicyMapping::new Constructor Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.PolicyMapping.html Creates a new PolicyMapping instance with the specified issuer and subject domain policies. ```APIDOC ## impl<'a> PolicyMapping<'a> ### `new` Constructor ```rust pub const fn new(issuer_domain_policy: Oid<'a>, subject_domain_policy: Oid<'a>) -> Self ``` Creates a new `PolicyMapping`. ``` -------------------------------- ### Validity Struct Source: https://docs.rs/x509-parser/latest/x509_parser/certificate/struct.Validity.html The Validity struct holds the start and end times for a certificate's validity period. ```APIDOC ## Struct Validity ### Summary ``` pub struct Validity { pub not_before: ASN1Time, pub not_after: ASN1Time, } ``` ### Fields - `not_before`: ASN1Time - The time before which the certificate is not valid. - `not_after`: ASN1Time - The time after which the certificate is not valid. ``` -------------------------------- ### X509Version PartialEq and Eq Implementations Source: https://docs.rs/x509-parser/latest/x509_parser/x509/struct.X509Version.html Implements PartialEq and Eq for X509Version, allowing direct comparison of version values using equality operators. This is essential for checking certificate versions. ```rust fn eq(&self, other: &X509Version) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### Extract and Format EC Public Key Data Source: https://docs.rs/x509-parser/latest/x509_parser/public_key/struct.ECPoint.html This example shows how to access the raw data of an EC public key from a certificate and format it as a hexadecimal string with colons. It is part of a larger function that prints various details of an X.509 certificate's public key. ```rust fn print_x509_ski(public_key: &SubjectPublicKeyInfo) { println!(" Public Key Algorithm:"); print_x509_digest_algorithm(&public_key.algorithm, 6); match public_key.parsed() { Ok(PublicKey::RSA(rsa)) => { println!(" RSA Public Key: ({} bit)", rsa.key_size()); // print_hex_dump(rsa.modulus, 1024); for l in format_number_to_hex_with_colon(rsa.modulus, 16) { println!(" {l}"); } if let Ok(e) = rsa.try_exponent() { println!(" exponent: 0x{e:x} ({e})"); } else { println!(" exponent: :"); print_hex_dump(rsa.exponent, 32); } } Ok(PublicKey::EC(ec)) => { println!(" EC Public Key: ({} bit)", ec.key_size()); for l in format_number_to_hex_with_colon(ec.data(), 16) { println!(" {l}"); } // // identify curve // if let Some(params) = &public_key.algorithm.parameters { // let curve_oid = params.as_oid(); // let curve = curve_oid // .map(|oid| { // oid_registry() // .get(oid) // .map(|entry| entry.sn()) // .unwrap_or("") // }) // .unwrap_or(""); // println!(" Curve: {}", curve); // } } Ok(PublicKey::DSA(y)) => { println!(" DSA Public Key: ({} bit)", 8 * y.len()); for l in format_number_to_hex_with_colon(y, 16) { println!(" {l}"); } } Ok(PublicKey::GostR3410(y)) => { println!(" GOST R 34.10-94 Public Key: ({} bit)", 8 * y.len()); for l in format_number_to_hex_with_colon(y, 16) { println!(" {l}"); } } Ok(PublicKey::GostR3410_2012(y)) => { println!(" GOST R 34.10-2012 Public Key: ({} bit)", 8 * y.len()); for l in format_number_to_hex_with_colon(y, 16) { println!(" {l}"); } } Ok(PublicKey::Unknown(b)) => { println!(" Unknown key type"); print_hex_dump(b, 256); if let Ok((rem, res)) = der_parser::parse_der(b) { eprintln!("rem: {} bytes", rem.len()); eprintln!("{res:?}"); } else { eprintln!(" "); } } Err(_) => { println!(" INVALID PUBLIC KEY"); } } // dbg!(&public_key); // todo!(); } ``` -------------------------------- ### Print RSA-OAEP Signature Algorithm Parameters Source: https://docs.rs/x509-parser/latest/src/print_cert/print-cert.rs.html Prints the hash algorithm, mask generation function, and pSourceFunc for RSA-OAEP signature parameters. Handles potential errors during mask generation. ```rust println!("{}/{}", format_oid(&mask_gen.mgf), format_oid(&mask_gen.hash)); ``` ```rust println!("INVALID"); ``` ```rust println!("{}pSourceFunc: {}", indent_s, format_oid(¶ms.p_source_alg().algorithm)); ``` -------------------------------- ### starts_with Source: https://docs.rs/x509-parser/latest/x509_parser/extensions/struct.CRLDistributionPoints.html Determines if a slice begins with a specified prefix slice. ```APIDOC ## pub fn starts_with(&self, needle: &[T]) -> bool ### Description Returns `true` if `needle` is a prefix of the slice or equal to the slice. ### Examples ```rust let v = [10, 40, 30]; assert!(v.starts_with(&[10])); assert!(v.starts_with(&[10, 40])); assert!(v.starts_with(&v)); assert!(!v.starts_with(&[50])); assert!(!v.starts_with(&[10, 50])); ``` Always returns `true` if `needle` is an empty slice: ```rust let v = &[10, 40, 30]; assert!(v.starts_with(&[])); let v: &[u8] = &[]; assert!(v.starts_with(&[])); ``` ```