Module x509_parser::pem

source ·
Expand description

Decoding functions for PEM-encoded data

A PEM object is a container, which can store (amongst other formats) a public X.509 Certificate, or a CRL, etc. It contains only printable characters. PEM-encoded binary data is essentially a beginning and matching end tag that encloses base64-encoded binary data (see: https://en.wikipedia.org/wiki/Privacy-enhanced_Electronic_Mail).

§Examples

To parse a certificate in PEM format, first create the Pem object, then decode contents:

use x509_parser::pem::Pem;
use x509_parser::x509::X509Version;

static IGCA_PEM: &str = "../assets/IGC_A.pem";

let data = std::fs::read(IGCA_PEM).expect("Could not read file");
for pem in Pem::iter_from_buffer(&data) {
    let pem = pem.expect("Reading next PEM block failed");
    let x509 = pem.parse_x509().expect("X.509: decoding DER failed");
    assert_eq!(x509.tbs_certificate.version, X509Version::V3);
}

This is the most direct method to parse PEM data.

Another method to parse the certificate is to use parse_x509_pem:

use x509_parser::pem::parse_x509_pem;
use x509_parser::parse_x509_certificate;

static IGCA_PEM: &[u8] = include_bytes!("../assets/IGC_A.pem");

let res = parse_x509_pem(IGCA_PEM);
match res {
    Ok((rem, pem)) => {
        assert!(rem.is_empty());
        //
        assert_eq!(pem.label, String::from("CERTIFICATE"));
        //
        let res_x509 = parse_x509_certificate(&pem.contents);
        assert!(res_x509.is_ok());
    },
    _ => panic!("PEM parsing failed: {:?}", res),
}

Note that all methods require to store the Pem object in a variable, mainly because decoding the PEM object requires allocation of buffers, and that the lifetime of X.509 certificates will be bound to these buffers.

Structs§

  • Representation of PEM data
  • Iterator over PEM-encapsulated blocks

Functions§