/rust/registry/src/index.crates.io-1949cf8c6b5b557f/pem-rfc7468-0.7.0/src/encoder.rs
Line | Count | Source |
1 | | //! PEM encoder. |
2 | | |
3 | | use crate::{ |
4 | | grammar, Base64Encoder, Error, LineEnding, Result, BASE64_WRAP_WIDTH, |
5 | | ENCAPSULATION_BOUNDARY_DELIMITER, POST_ENCAPSULATION_BOUNDARY, PRE_ENCAPSULATION_BOUNDARY, |
6 | | }; |
7 | | use base64ct::{Base64, Encoding}; |
8 | | use core::str; |
9 | | |
10 | | #[cfg(feature = "alloc")] |
11 | | use alloc::string::String; |
12 | | |
13 | | #[cfg(feature = "std")] |
14 | | use 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 |
33 | 0 | pub fn encapsulated_len(label: &str, line_ending: LineEnding, input_len: usize) -> Result<usize> { |
34 | 0 | encapsulated_len_wrapped(label, BASE64_WRAP_WIDTH, line_ending, input_len) |
35 | 0 | } |
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 |
51 | 0 | pub fn encapsulated_len_wrapped( |
52 | 0 | label: &str, |
53 | 0 | line_width: usize, |
54 | 0 | line_ending: LineEnding, |
55 | 0 | input_len: usize, |
56 | 0 | ) -> Result<usize> { |
57 | 0 | if line_width < 4 { |
58 | 0 | return Err(Error::Length); |
59 | 0 | } |
60 | | |
61 | 0 | let base64_len = input_len |
62 | 0 | .checked_mul(4) |
63 | 0 | .and_then(|n| n.checked_div(3)) |
64 | 0 | .and_then(|n| n.checked_add(3)) |
65 | 0 | .ok_or(Error::Length)? |
66 | 0 | & !3; |
67 | | |
68 | 0 | let base64_len_wrapped = base64_len_wrapped(base64_len, line_width, line_ending)?; |
69 | 0 | encapsulated_len_inner(label, line_ending, base64_len_wrapped) |
70 | 0 | } |
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 |
80 | 0 | pub fn encoded_len(label: &str, line_ending: LineEnding, input: &[u8]) -> Result<usize> { |
81 | 0 | let base64_len = Base64::encoded_len(input); |
82 | 0 | let base64_len_wrapped = base64_len_wrapped(base64_len, BASE64_WRAP_WIDTH, line_ending)?; |
83 | 0 | encapsulated_len_inner(label, line_ending, base64_len_wrapped) |
84 | 0 | } |
85 | | |
86 | | /// Encode a PEM document according to RFC 7468's "Strict" grammar. |
87 | 0 | pub fn encode<'o>( |
88 | 0 | type_label: &str, |
89 | 0 | line_ending: LineEnding, |
90 | 0 | input: &[u8], |
91 | 0 | buf: &'o mut [u8], |
92 | 0 | ) -> Result<&'o str> { |
93 | 0 | let mut encoder = Encoder::new(type_label, line_ending, buf)?; |
94 | 0 | encoder.encode(input)?; |
95 | 0 | let encoded_len = encoder.finish()?; |
96 | 0 | let output = &buf[..encoded_len]; |
97 | | |
98 | | // Sanity check |
99 | 0 | debug_assert!(str::from_utf8(output).is_ok()); |
100 | | |
101 | | // Ensure `output` contains characters from the lower 7-bit ASCII set |
102 | 0 | 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 | 0 | Ok(unsafe { str::from_utf8_unchecked(output) }) |
114 | | } else { |
115 | 0 | Err(Error::CharacterEncoding) |
116 | | } |
117 | 0 | } |
118 | | |
119 | | /// Encode a PEM document according to RFC 7468's "Strict" grammar, returning |
120 | | /// the result as a [`String`]. |
121 | | #[cfg(feature = "alloc")] |
122 | 0 | pub fn encode_string(label: &str, line_ending: LineEnding, input: &[u8]) -> Result<String> { |
123 | 0 | let expected_len = encoded_len(label, line_ending, input)?; |
124 | 0 | let mut buf = vec![0u8; expected_len]; |
125 | 0 | let actual_len = encode(label, line_ending, input, &mut buf)?.len(); |
126 | 0 | debug_assert_eq!(expected_len, actual_len); |
127 | 0 | String::from_utf8(buf).map_err(|_| Error::CharacterEncoding) |
128 | 0 | } |
129 | | |
130 | | /// Compute the encapsulated length of Base64 data of the given length. |
131 | 0 | fn encapsulated_len_inner( |
132 | 0 | label: &str, |
133 | 0 | line_ending: LineEnding, |
134 | 0 | base64_len: usize, |
135 | 0 | ) -> Result<usize> { |
136 | 0 | [ |
137 | 0 | PRE_ENCAPSULATION_BOUNDARY.len(), |
138 | 0 | label.as_bytes().len(), |
139 | 0 | ENCAPSULATION_BOUNDARY_DELIMITER.len(), |
140 | 0 | line_ending.len(), |
141 | 0 | base64_len, |
142 | 0 | line_ending.len(), |
143 | 0 | POST_ENCAPSULATION_BOUNDARY.len(), |
144 | 0 | label.as_bytes().len(), |
145 | 0 | ENCAPSULATION_BOUNDARY_DELIMITER.len(), |
146 | 0 | line_ending.len(), |
147 | 0 | ] |
148 | 0 | .into_iter() |
149 | 0 | .try_fold(0usize, |acc, len| acc.checked_add(len)) |
150 | 0 | .ok_or(Error::Length) |
151 | 0 | } |
152 | | |
153 | | /// Compute Base64 length line-wrapped at the specified width with the given |
154 | | /// line ending. |
155 | 0 | fn base64_len_wrapped( |
156 | 0 | base64_len: usize, |
157 | 0 | line_width: usize, |
158 | 0 | line_ending: LineEnding, |
159 | 0 | ) -> Result<usize> { |
160 | 0 | base64_len |
161 | 0 | .saturating_sub(1) |
162 | 0 | .checked_div(line_width) |
163 | 0 | .and_then(|lines| lines.checked_mul(line_ending.len())) |
164 | 0 | .and_then(|len| len.checked_add(base64_len)) |
165 | 0 | .ok_or(Error::Length) |
166 | 0 | } |
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. |
172 | | pub 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 | | |
183 | | impl<'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 | 0 | pub fn new(type_label: &'l str, line_ending: LineEnding, out: &'o mut [u8]) -> Result<Self> { |
189 | 0 | Self::new_wrapped(type_label, BASE64_WRAP_WIDTH, line_ending, out) |
190 | 0 | } |
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 | 0 | pub fn new_wrapped( |
207 | 0 | type_label: &'l str, |
208 | 0 | line_width: usize, |
209 | 0 | line_ending: LineEnding, |
210 | 0 | mut out: &'o mut [u8], |
211 | 0 | ) -> Result<Self> { |
212 | 0 | grammar::validate_label(type_label.as_bytes())?; |
213 | | |
214 | 0 | for boundary_part in [ |
215 | | PRE_ENCAPSULATION_BOUNDARY, |
216 | 0 | type_label.as_bytes(), |
217 | 0 | ENCAPSULATION_BOUNDARY_DELIMITER, |
218 | 0 | line_ending.as_bytes(), |
219 | | ] { |
220 | 0 | if out.len() < boundary_part.len() { |
221 | 0 | return Err(Error::Length); |
222 | 0 | } |
223 | | |
224 | 0 | let (part, rest) = out.split_at_mut(boundary_part.len()); |
225 | 0 | out = rest; |
226 | | |
227 | 0 | part.copy_from_slice(boundary_part); |
228 | | } |
229 | | |
230 | 0 | let base64 = Base64Encoder::new_wrapped(out, line_width, line_ending)?; |
231 | | |
232 | 0 | Ok(Self { |
233 | 0 | type_label, |
234 | 0 | line_ending, |
235 | 0 | base64, |
236 | 0 | }) |
237 | 0 | } |
238 | | |
239 | | /// Get the PEM type label used for this document. |
240 | 0 | pub fn type_label(&self) -> &'l str { |
241 | 0 | self.type_label |
242 | 0 | } |
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 | 0 | pub fn encode(&mut self, input: &[u8]) -> Result<()> { |
251 | 0 | self.base64.encode(input)?; |
252 | 0 | Ok(()) |
253 | 0 | } |
254 | | |
255 | | /// Borrow the inner [`Base64Encoder`]. |
256 | 0 | pub fn base64_encoder(&mut self) -> &mut Base64Encoder<'o> { |
257 | 0 | &mut self.base64 |
258 | 0 | } |
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 | 0 | pub fn finish(self) -> Result<usize> { |
265 | 0 | let (base64, mut out) = self.base64.finish_with_remaining()?; |
266 | | |
267 | 0 | for boundary_part in [ |
268 | 0 | self.line_ending.as_bytes(), |
269 | 0 | POST_ENCAPSULATION_BOUNDARY, |
270 | 0 | self.type_label.as_bytes(), |
271 | 0 | ENCAPSULATION_BOUNDARY_DELIMITER, |
272 | 0 | self.line_ending.as_bytes(), |
273 | | ] { |
274 | 0 | if out.len() < boundary_part.len() { |
275 | 0 | return Err(Error::Length); |
276 | 0 | } |
277 | | |
278 | 0 | let (part, rest) = out.split_at_mut(boundary_part.len()); |
279 | 0 | out = rest; |
280 | | |
281 | 0 | part.copy_from_slice(boundary_part); |
282 | | } |
283 | | |
284 | 0 | encapsulated_len_inner(self.type_label, self.line_ending, base64.len()) |
285 | 0 | } |
286 | | } |
287 | | |
288 | | #[cfg(feature = "std")] |
289 | | impl<'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 | | } |