Skip to content

Instantly share code, notes, and snippets.

@andreanidouglas
Last active September 16, 2022 23:21
Show Gist options
  • Save andreanidouglas/f3cc1084d393359feaa11433d67b3771 to your computer and use it in GitHub Desktop.
Save andreanidouglas/f3cc1084d393359feaa11433d67b3771 to your computer and use it in GitHub Desktop.
Rust snippet on x509-parser treating lifetimes
use x509_parser::prelude::*;
fn main() -> anyhow::Result<()> {
print_cert()?;
print_cert_static()?;
Ok(())
}
// 'a defines a lifetime. tbs and raw members cannot live less than MyCert
struct MyCert<'a> {
tbs: TbsCertificate<'a>,
_raw: X509Certificate<'a>,
}
// 'static defines set the member in the static memory location.
// it is almost like C "static int a = 0;" will live "forever".
struct MyCertStatic {
tbs: TbsCertificate<'static>,
_raw: X509Certificate<'static>,
}
#[derive(Clone)]
struct Certificate {
native: native_tls::Certificate,
}
impl Certificate {
fn from_pem(pem: &[u8]) -> anyhow::Result<Certificate> {
Ok(Certificate {
native: native_tls::Certificate::from_pem(pem)?
})
}
}
fn print_cert() -> anyhow::Result<()> {
let my_pen = std::fs::read("cert.pem")?;
let cert = Certificate::from_pem(&my_pen)?;
let cert_native_der = &cert.native.to_der()?;
let (_, info) = X509Certificate::from_der(&cert_native_der)?;
let my_cert = MyCert { tbs: info.tbs_certificate.clone(), _raw: info.clone() };
println!("My Cert details:\nSubject: {}\nIssuer: {}", my_cert.tbs.subject, my_cert.tbs.issuer);
Ok(())
}
fn print_cert_static() -> anyhow::Result<()> {
let my_pen = std::fs::read("cert.pem")?;
let cert = Certificate::from_pem(&my_pen)?;
// Box is a pointer type used for heap allocation. Box::new(T)
let cert_native_der = Box::new(cert.native.to_der()?);
// Leak will consume the Box and release T it as a static mutable reference
let (_, info) = X509Certificate::from_der(cert_native_der.leak())?;
let my_cert = MyCertStatic { tbs: info.tbs_certificate.clone(), _raw: info.clone() };
println!("My Cert details:\nSubject: {}\nIssuer: {}", my_cert.tbs.subject, my_cert.tbs.issuer);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment