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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
use crate::{
grammar, Base64Decoder, Error, Result, BASE64_WRAP_WIDTH, POST_ENCAPSULATION_BOUNDARY,
PRE_ENCAPSULATION_BOUNDARY,
};
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")]
#[cfg_attr(docsrs, doc(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())
}
#[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 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")]
#[cfg_attr(docsrs, doc(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")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl<'i> io::Read for Decoder<'i> {
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
}
}
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.iter().any(|&b| b == grammar::CHAR_COLON)
{
Error::HeaderDisallowed
} else {
err
}
}
#[cfg(test)]
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
]
);
}
}