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
#[macro_use]
extern crate nom;
mod parsers;
mod headers;
mod display;
use std::str;
use self::parsers::*;
pub use self::headers::{HeaderEntry, RFC1423Algorithm, ProcTypeType};
use self::headers::*;
use self::display::{write_base64, write_headers};
use std::fmt;
use nom::IResult::*;
#[cfg(test)]
mod test;
#[derive(Debug)]
pub struct Block<'a> {
pub block_type: &'a str,
pub headers: Vec<HeaderEntry<'a>>,
pub data: Vec<u8>
}
#[derive(Debug)]
pub enum PemParsingError {
NomError(nom::Err),
Incomplete(nom::Needed)
}
pub fn decode_block<'a>(input: &[u8]) -> Result<Block, PemParsingError> {
match pem_block(input) {
Error(e) => Err(PemParsingError::NomError(e)),
Incomplete(_i) => Err(PemParsingError::Incomplete(_i)),
Done(_rest, block) => Ok(block)
}
}
pub fn decode_blocks<'a>(input: &[u8]) -> Result<Vec<Block>, PemParsingError> {
match pem_blocks(input) {
Error(e) => Err(PemParsingError::NomError(e)),
Incomplete(_i) => Err(PemParsingError::Incomplete(_i)),
Done(_rest, block) => Ok(block)
}
}
impl<'a> fmt::Display for Block<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "-----BEGIN {}-----\n", &self.block_type)?;
write_headers(f, &self.headers)?;
write_base64(f, &self.data, 64)?;
write!(f, "-----END {}-----\n", &self.block_type)
}
}