pem_rfc7468/
encoder.rs

1//! PEM encoder.
2
3use crate::{
4    grammar, Base64Encoder, Error, LineEnding, Result, BASE64_WRAP_WIDTH,
5    ENCAPSULATION_BOUNDARY_DELIMITER, POST_ENCAPSULATION_BOUNDARY, PRE_ENCAPSULATION_BOUNDARY,
6};
7use base64ct::{Base64, Encoding};
8use core::str;
9
10#[cfg(feature = "alloc")]
11use alloc::string::String;
12
13#[cfg(feature = "std")]
14use std::io;
15
16/// Compute the length of a PEM encoded document which encapsulates a
17/// Base64-encoded body including line endings every 64 characters.
18///
19/// The `input_len` parameter specifies the length of the raw input
20/// bytes prior to Base64 encoding.
21///
22/// Note that the current implementation of this function computes an upper
23/// bound of the length and the actual encoded document may be slightly shorter
24/// (typically 1-byte). Downstream consumers of this function should check the
25/// actual encoded length and potentially truncate buffers allocated using this
26/// function to estimate the encapsulated size.
27///
28/// Use [`encoded_len`] (when possible) to obtain a precise length.
29///
30/// ## Returns
31/// - `Ok(len)` on success
32/// - `Err(Error::Length)` on length overflow
33pub fn encapsulated_len(label: &str, line_ending: LineEnding, input_len: usize) -> Result<usize> {
34    encapsulated_len_wrapped(label, BASE64_WRAP_WIDTH, line_ending, input_len)
35}
36
37/// Compute the length of a PEM encoded document with the Base64 body
38/// line wrapped at the specified `width`.
39///
40/// This is the same as [`encapsulated_len`], which defaults to a width of 64.
41///
42/// Note that per [RFC7468 § 2] encoding PEM with any other wrap width besides
43/// 64 is technically non-compliant:
44///
45/// > Generators MUST wrap the base64-encoded lines so that each line
46/// > consists of exactly 64 characters except for the final line, which
47/// > will encode the remainder of the data (within the 64-character line
48/// > boundary)
49///
50/// [RFC7468 § 2]: https://datatracker.ietf.org/doc/html/rfc7468#section-2
51pub fn encapsulated_len_wrapped(
52    label: &str,
53    line_width: usize,
54    line_ending: LineEnding,
55    input_len: usize,
56) -> Result<usize> {
57    if line_width < 4 {
58        return Err(Error::Length);
59    }
60
61    let base64_len = input_len
62        .checked_mul(4)
63        .and_then(|n| n.checked_div(3))
64        .and_then(|n| n.checked_add(3))
65        .ok_or(Error::Length)?
66        & !3;
67
68    let base64_len_wrapped = base64_len_wrapped(base64_len, line_width, line_ending)?;
69    encapsulated_len_inner(label, line_ending, base64_len_wrapped)
70}
71
72/// Get the length of a PEM encoded document with the given bytes and label.
73///
74/// This function computes a precise length of the PEM encoding of the given
75/// `input` data.
76///
77/// ## Returns
78/// - `Ok(len)` on success
79/// - `Err(Error::Length)` on length overflow
80pub fn encoded_len(label: &str, line_ending: LineEnding, input: &[u8]) -> Result<usize> {
81    let base64_len = Base64::encoded_len(input);
82    let base64_len_wrapped = base64_len_wrapped(base64_len, BASE64_WRAP_WIDTH, line_ending)?;
83    encapsulated_len_inner(label, line_ending, base64_len_wrapped)
84}
85
86/// Encode a PEM document according to RFC 7468's "Strict" grammar.
87pub fn encode<'o>(
88    type_label: &str,
89    line_ending: LineEnding,
90    input: &[u8],
91    buf: &'o mut [u8],
92) -> Result<&'o str> {
93    let mut encoder = Encoder::new(type_label, line_ending, buf)?;
94    encoder.encode(input)?;
95    let encoded_len = encoder.finish()?;
96    let output = &buf[..encoded_len];
97
98    // Sanity check
99    debug_assert!(str::from_utf8(output).is_ok());
100
101    // Ensure `output` contains characters from the lower 7-bit ASCII set
102    if output.iter().fold(0u8, |acc, &byte| acc | (byte & 0x80)) == 0 {
103        // Use unchecked conversion to avoid applying UTF-8 checks to potentially
104        // secret PEM documents (and therefore introducing a potential timing
105        // sidechannel)
106        //
107        // SAFETY: contents of this buffer are controlled entirely by the encoder,
108        // which ensures the contents are always a valid (ASCII) subset of UTF-8.
109        // It's also additionally sanity checked by two assertions above to ensure
110        // the validity (with the always-on runtime check implemented in a
111        // constant time-ish manner.
112        #[allow(unsafe_code)]
113        Ok(unsafe { str::from_utf8_unchecked(output) })
114    } else {
115        Err(Error::CharacterEncoding)
116    }
117}
118
119/// Encode a PEM document according to RFC 7468's "Strict" grammar, returning
120/// the result as a [`String`].
121#[cfg(feature = "alloc")]
122pub fn encode_string(label: &str, line_ending: LineEnding, input: &[u8]) -> Result<String> {
123    let expected_len = encoded_len(label, line_ending, input)?;
124    let mut buf = vec![0u8; expected_len];
125    let actual_len = encode(label, line_ending, input, &mut buf)?.len();
126    debug_assert_eq!(expected_len, actual_len);
127    String::from_utf8(buf).map_err(|_| Error::CharacterEncoding)
128}
129
130/// Compute the encapsulated length of Base64 data of the given length.
131fn encapsulated_len_inner(
132    label: &str,
133    line_ending: LineEnding,
134    base64_len: usize,
135) -> Result<usize> {
136    [
137        PRE_ENCAPSULATION_BOUNDARY.len(),
138        label.as_bytes().len(),
139        ENCAPSULATION_BOUNDARY_DELIMITER.len(),
140        line_ending.len(),
141        base64_len,
142        line_ending.len(),
143        POST_ENCAPSULATION_BOUNDARY.len(),
144        label.as_bytes().len(),
145        ENCAPSULATION_BOUNDARY_DELIMITER.len(),
146        line_ending.len(),
147    ]
148    .into_iter()
149    .try_fold(0usize, |acc, len| acc.checked_add(len))
150    .ok_or(Error::Length)
151}
152
153/// Compute Base64 length line-wrapped at the specified width with the given
154/// line ending.
155fn base64_len_wrapped(
156    base64_len: usize,
157    line_width: usize,
158    line_ending: LineEnding,
159) -> Result<usize> {
160    base64_len
161        .saturating_sub(1)
162        .checked_div(line_width)
163        .and_then(|lines| lines.checked_mul(line_ending.len()))
164        .and_then(|len| len.checked_add(base64_len))
165        .ok_or(Error::Length)
166}
167
168/// Buffered PEM encoder.
169///
170/// Stateful buffered encoder type which encodes an input PEM document according
171/// to RFC 7468's "Strict" grammar.
172pub struct Encoder<'l, 'o> {
173    /// PEM type label.
174    type_label: &'l str,
175
176    /// Line ending used to wrap Base64.
177    line_ending: LineEnding,
178
179    /// Buffered Base64 encoder.
180    base64: Base64Encoder<'o>,
181}
182
183impl<'l, 'o> Encoder<'l, 'o> {
184    /// Create a new PEM [`Encoder`] with the default options which
185    /// writes output into the provided buffer.
186    ///
187    /// Uses the default 64-character line wrapping.
188    pub fn new(type_label: &'l str, line_ending: LineEnding, out: &'o mut [u8]) -> Result<Self> {
189        Self::new_wrapped(type_label, BASE64_WRAP_WIDTH, line_ending, out)
190    }
191
192    /// Create a new PEM [`Encoder`] which wraps at the given line width.
193    ///
194    /// Note that per [RFC7468 § 2] encoding PEM with any other wrap width besides
195    /// 64 is technically non-compliant:
196    ///
197    /// > Generators MUST wrap the base64-encoded lines so that each line
198    /// > consists of exactly 64 characters except for the final line, which
199    /// > will encode the remainder of the data (within the 64-character line
200    /// > boundary)
201    ///
202    /// This method is provided with the intended purpose of implementing the
203    /// OpenSSH private key format, which uses a non-standard wrap width of 70.
204    ///
205    /// [RFC7468 § 2]: https://datatracker.ietf.org/doc/html/rfc7468#section-2
206    pub fn new_wrapped(
207        type_label: &'l str,
208        line_width: usize,
209        line_ending: LineEnding,
210        mut out: &'o mut [u8],
211    ) -> Result<Self> {
212        grammar::validate_label(type_label.as_bytes())?;
213
214        for boundary_part in [
215            PRE_ENCAPSULATION_BOUNDARY,
216            type_label.as_bytes(),
217            ENCAPSULATION_BOUNDARY_DELIMITER,
218            line_ending.as_bytes(),
219        ] {
220            if out.len() < boundary_part.len() {
221                return Err(Error::Length);
222            }
223
224            let (part, rest) = out.split_at_mut(boundary_part.len());
225            out = rest;
226
227            part.copy_from_slice(boundary_part);
228        }
229
230        let base64 = Base64Encoder::new_wrapped(out, line_width, line_ending)?;
231
232        Ok(Self {
233            type_label,
234            line_ending,
235            base64,
236        })
237    }
238
239    /// Get the PEM type label used for this document.
240    pub fn type_label(&self) -> &'l str {
241        self.type_label
242    }
243
244    /// Encode the provided input data.
245    ///
246    /// This method can be called as many times as needed with any sized input
247    /// to write data encoded data into the output buffer, so long as there is
248    /// sufficient space in the buffer to handle the resulting Base64 encoded
249    /// data.
250    pub fn encode(&mut self, input: &[u8]) -> Result<()> {
251        self.base64.encode(input)?;
252        Ok(())
253    }
254
255    /// Borrow the inner [`Base64Encoder`].
256    pub fn base64_encoder(&mut self) -> &mut Base64Encoder<'o> {
257        &mut self.base64
258    }
259
260    /// Finish encoding PEM, writing the post-encapsulation boundary.
261    ///
262    /// On success, returns the total number of bytes written to the output
263    /// buffer.
264    pub fn finish(self) -> Result<usize> {
265        let (base64, mut out) = self.base64.finish_with_remaining()?;
266
267        for boundary_part in [
268            self.line_ending.as_bytes(),
269            POST_ENCAPSULATION_BOUNDARY,
270            self.type_label.as_bytes(),
271            ENCAPSULATION_BOUNDARY_DELIMITER,
272            self.line_ending.as_bytes(),
273        ] {
274            if out.len() < boundary_part.len() {
275                return Err(Error::Length);
276            }
277
278            let (part, rest) = out.split_at_mut(boundary_part.len());
279            out = rest;
280
281            part.copy_from_slice(boundary_part);
282        }
283
284        encapsulated_len_inner(self.type_label, self.line_ending, base64.len())
285    }
286}
287
288#[cfg(feature = "std")]
289impl<'l, 'o> io::Write for Encoder<'l, 'o> {
290    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
291        self.encode(buf)?;
292        Ok(buf.len())
293    }
294
295    fn flush(&mut self) -> io::Result<()> {
296        // TODO(tarcieri): return an error if there's still data remaining in the buffer?
297        Ok(())
298    }
299}