use crate::{
BASE64_WRAP_WIDTH, Base64Decoder, Error, POST_ENCAPSULATION_BOUNDARY,
PRE_ENCAPSULATION_BOUNDARY, Result, grammar,
};
use core::str;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
#[cfg(feature = "std")]
use std::io;
pub fn decode<'i, 'o>(pem: &'i [u8], buf: &'o mut [u8]) -> Result<(&'i str, &'o [u8])> {
let mut decoder = Decoder::new(pem).map_err(|e| check_for_headers(pem, e))?;
let type_label = decoder.type_label();
let buf = buf
.get_mut(..decoder.remaining_len())
.ok_or(Error::Length)?;
let decoded = decoder.decode(buf).map_err(|e| check_for_headers(pem, e))?;
if decoder.base64.is_finished() {
Ok((type_label, decoded))
} else {
Err(Error::Length)
}
}
#[cfg(feature = "alloc")]
pub fn decode_vec(pem: &[u8]) -> Result<(&str, Vec<u8>)> {
let mut decoder = Decoder::new(pem).map_err(|e| check_for_headers(pem, e))?;
let type_label = decoder.type_label();
let mut buf = Vec::new();
decoder
.decode_to_end(&mut buf)
.map_err(|e| check_for_headers(pem, e))?;
Ok((type_label, buf))
}
pub fn decode_label(pem: &[u8]) -> Result<&str> {
Ok(Encapsulation::try_from(pem)?.label())
}
pub fn detect_base64_line_width(pem: &[u8]) -> Result<usize> {
Ok(Encapsulation::try_from(pem)?.encapsulated_text_line_width())
}
#[derive(Clone)]
pub struct Decoder<'i> {
type_label: &'i str,
base64: Base64Decoder<'i>,
}
impl<'i> Decoder<'i> {
pub fn new(pem: &'i [u8]) -> Result<Self> {
Self::new_wrapped(pem, BASE64_WRAP_WIDTH)
}
pub fn new_wrapped(pem: &'i [u8], line_width: usize) -> Result<Self> {
let encapsulation = Encapsulation::try_from(pem)?;
let type_label = encapsulation.label();
let base64 = Base64Decoder::new_wrapped(encapsulation.encapsulated_text, line_width)?;
Ok(Self { type_label, base64 })
}
pub fn new_detect_wrap(pem: &'i [u8]) -> Result<Self> {
let line_width = detect_base64_line_width(pem)?;
Self::new_wrapped(pem, line_width)
}
pub fn type_label(&self) -> &'i str {
self.type_label
}
pub fn decode<'o>(&mut self, buf: &'o mut [u8]) -> Result<&'o [u8]> {
Ok(self.base64.decode(buf)?)
}
#[cfg(feature = "alloc")]
pub fn decode_to_end<'o>(&mut self, buf: &'o mut Vec<u8>) -> Result<&'o [u8]> {
Ok(self.base64.decode_to_end(buf)?)
}
pub fn remaining_len(&self) -> usize {
self.base64.remaining_len()
}
pub fn is_finished(&self) -> bool {
self.base64.is_finished()
}
}
impl<'i> From<Decoder<'i>> for Base64Decoder<'i> {
fn from(decoder: Decoder<'i>) -> Base64Decoder<'i> {
decoder.base64
}
}
#[cfg(feature = "std")]
impl io::Read for Decoder<'_> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.base64.read(buf)
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
self.base64.read_to_end(buf)
}
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
self.base64.read_exact(buf)
}
}
#[derive(Copy, Clone, Debug)]
struct Encapsulation<'a> {
label: &'a str,
encapsulated_text: &'a [u8],
}
impl<'a> Encapsulation<'a> {
pub fn parse(data: &'a [u8]) -> Result<Self> {
let data = grammar::strip_preamble(data)?;
let data = data
.strip_prefix(PRE_ENCAPSULATION_BOUNDARY)
.ok_or(Error::PreEncapsulationBoundary)?;
let (label, body) = grammar::split_label(data).ok_or(Error::Label)?;
let mut body = match grammar::strip_trailing_eol(body).unwrap_or(body) {
[head @ .., b'-', b'-', b'-', b'-', b'-'] => head,
_ => return Err(Error::PreEncapsulationBoundary),
};
for &slice in [POST_ENCAPSULATION_BOUNDARY, label.as_bytes()].iter().rev() {
if !body.ends_with(slice) {
return Err(Error::PostEncapsulationBoundary);
}
let len = body.len().checked_sub(slice.len()).ok_or(Error::Length)?;
body = body.get(..len).ok_or(Error::PostEncapsulationBoundary)?;
}
let encapsulated_text =
grammar::strip_trailing_eol(body).ok_or(Error::PostEncapsulationBoundary)?;
Ok(Self {
label,
encapsulated_text,
})
}
pub fn label(self) -> &'a str {
self.label
}
pub fn encapsulated_text_line_width(self) -> usize {
self.encapsulated_text
.iter()
.copied()
.position(|c| matches!(c, grammar::CHAR_CR | grammar::CHAR_LF))
.unwrap_or(self.encapsulated_text.len())
}
}
impl<'a> TryFrom<&'a [u8]> for Encapsulation<'a> {
type Error = Error;
fn try_from(bytes: &'a [u8]) -> Result<Self> {
Self::parse(bytes)
}
}
fn check_for_headers(pem: &[u8], err: Error) -> Error {
if err == Error::Base64(base64ct::Error::InvalidEncoding) && pem.contains(&grammar::CHAR_COLON)
{
Error::HeaderDisallowed
} else {
err
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::Encapsulation;
#[test]
fn pkcs8_example() {
let pem = include_bytes!("../tests/examples/pkcs8.pem");
let encapsulation = Encapsulation::parse(pem).unwrap();
assert_eq!(encapsulation.label, "PRIVATE KEY");
assert_eq!(
encapsulation.encapsulated_text,
&[
77, 67, 52, 67, 65, 81, 65, 119, 66, 81, 89, 68, 75, 50, 86, 119, 66, 67, 73, 69,
73, 66, 102, 116, 110, 72, 80, 112, 50, 50, 83, 101, 119, 89, 109, 109, 69, 111,
77, 99, 88, 56, 86, 119, 73, 52, 73, 72, 119, 97, 113, 100, 43, 57, 76, 70, 80,
106, 47, 49, 53, 101, 113, 70
]
);
}
}