1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
//! 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: //! //! ```rust,no_run //! use std::io::Cursor; //! use x509_parser::pem::Pem; //! use x509_parser::x509::X509Version; //! //! static IGCA_PEM: &[u8] = include_bytes!("../assets/IGC_A.pem"); //! //! # fn main() { //! let reader = Cursor::new(IGCA_PEM); //! let (pem,bytes_read) = Pem::read(reader).expect("Reading PEM 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`: //! //! ```rust,no_run //! use x509_parser::pem::parse_x509_pem; //! use x509_parser::parse_x509_certificate; //! //! static IGCA_PEM: &[u8] = include_bytes!("../assets/IGC_A.pem"); //! //! # fn main() { //! 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. use crate::certificate::X509Certificate; use crate::error::{PEMError, X509Error}; use crate::parse_x509_certificate; use nom::{Err, IResult}; use std::io::{BufRead, Cursor, Seek}; /// Representation of PEM data #[derive(PartialEq, Debug)] pub struct Pem { /// The PEM label pub label: String, /// The PEM decoded data pub contents: Vec<u8>, } #[deprecated(since = "0.8.3", note = "please use `parse_x509_pem` instead")] pub fn pem_to_der(i: &[u8]) -> IResult<&[u8], Pem, PEMError> { parse_x509_pem(i) } /// Read a PEM-encoded structure, and decode the base64 data /// /// Return a structure describing the PEM object: the enclosing tag, and the data. /// Allocates a new buffer for the decoded data. /// /// For X.509 (`CERTIFICATE` tag), the data is a certificate, encoded in DER. To parse the /// certificate content, use `Pem::parse_x509` or `parse_x509_certificate`. pub fn parse_x509_pem(i: &[u8]) -> IResult<&'_ [u8], Pem, PEMError> { let reader = Cursor::new(i); let res = Pem::read(reader); match res { Ok((pem, bytes_read)) => Ok((&i[bytes_read..], pem)), Err(e) => Err(Err::Error(e)), } } impl Pem { /// Read a PEM-encoded structure, and decode the base64 data /// /// Returns the certificate (encoded in DER) and the number of bytes read. /// Allocates a new buffer for the decoded data. /// /// # Examples /// ``` /// let file = std::fs::File::open("assets/certificate.pem").unwrap(); /// let subject = x509_parser::pem::Pem::read(std::io::BufReader::new(file)) /// .unwrap().0 /// .parse_x509().unwrap() /// .tbs_certificate.subject.to_string(); /// assert_eq!(subject, "CN=lists.for-our.info"); /// ``` pub fn read(mut r: impl BufRead + Seek) -> Result<(Pem, usize), PEMError> { let mut line = String::new(); let label = loop { let num_bytes = r.read_line(&mut line).or(Err(PEMError::MissingHeader))?; if num_bytes == 0 { // EOF return Err(PEMError::MissingHeader); } if !line.starts_with("-----BEGIN ") { line.clear(); continue; } let mut iter = line.split_whitespace(); let label = iter.nth(1).ok_or(PEMError::InvalidHeader)?; break label; }; let label = label.split('-').next().ok_or(PEMError::InvalidHeader)?; let mut s = String::new(); loop { let mut l = String::new(); let num_bytes = r.read_line(&mut l)?; if num_bytes == 0 { return Err(PEMError::IncompletePEM); } if l.starts_with("-----END ") { // finished reading break; } s.push_str(l.trim_end()); } let contents = base64::decode(&s).or(Err(PEMError::Base64DecodeError))?; let pem = Pem { label: label.to_string(), contents, }; Ok((pem, r.seek(std::io::SeekFrom::Current(0))? as usize)) } /// Decode the PEM contents into a X.509 object pub fn parse_x509(&self) -> Result<X509Certificate, ::nom::Err<X509Error>> { parse_x509_certificate(&self.contents).map(|(_, x509)| x509) } } #[cfg(test)] mod tests { use super::*; #[test] fn read_pem_from_file() { let file = std::io::BufReader::new(std::fs::File::open("assets/certificate.pem").unwrap()); let subject = Pem::read(file) .unwrap() .0 .parse_x509() .unwrap() .tbs_certificate .subject .to_string(); assert_eq!(subject, "CN=lists.for-our.info"); } }