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
//! Decoding functions for PEM-encoded data //! //! # Examples //! //! To parse a certificate in PEM format, first create the `Pem` object, then decode //! contents: //! //! ```rust,no_run //! # extern crate nom; //! # #[macro_use] extern crate x509_parser; //! use std::io::Cursor; //! use x509_parser::pem::{pem_to_der, Pem}; //! use x509_parser::parse_x509_der; //! //! static IGCA_PEM: &'static [u8] = include_bytes!("../assets/IGC_A.pem"); //! //! # fn main() { //! let res = pem_to_der(IGCA_PEM); //! 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, 2); //! # } //! ``` //! //! This is the most direct method to parse PEM data. //! //! Another method to parse the certificate is to use `pem_to_der`: //! //! ```rust,no_run //! # extern crate nom; //! # #[macro_use] extern crate x509_parser; //! use x509_parser::pem::pem_to_der; //! use x509_parser::parse_x509_der; //! //! static IGCA_PEM: &'static [u8] = include_bytes!("../assets/IGC_A.pem"); //! //! # fn main() { //! let res = pem_to_der(IGCA_PEM); //! match res { //! Ok((rem, pem)) => { //! assert!(rem.is_empty()); //! // //! assert_eq!(pem.label, String::from("CERTIFICATE")); //! // //! let res_x509 = parse_x509_der(&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::error::{PEMError, X509Error}; use crate::x509::X509Certificate; use crate::x509_parser::parse_x509_der; use base64; 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>, } /// Read a PEM-encoded structure, and decode the base64 data /// /// Allocates a new buffer for the decoded data. pub fn pem_to_der<'a>(i: &'a [u8]) -> IResult<&'a [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 first_line = String::new(); r.read_line(&mut first_line)?; let mut iter = first_line.split_whitespace(); if iter.next() != Some("-----BEGIN") { return Err(PEMError::MissingHeader); } let label = iter.next().ok_or(PEMError::InvalidHeader)?; let label = label.split('-').next().ok_or(PEMError::InvalidHeader)?; let mut s = String::new(); loop { let mut l = String::new(); r.read_line(&mut l)?; 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<'pem>(&'pem self) -> Result<X509Certificate<'pem>, ::nom::Err<X509Error>> { parse_x509_der(&self.contents) .map(|(_,x509)| x509) } } #[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"); }