git clone https://garage44.eu/jeroen/pinnacle.git.. /tls/src/der.rs
//! DER, as certificates are encoded: tag, length, value, nested.
/// One element: its tag, its value, and all of it as it was encoded.
#[derive(Clone, Copy, Debug)]
pub struct Tlv<'a> {
pub tag: u8,
pub value: &'a [u8],
pub whole: &'a [u8],
}
pub const BOOLEAN: u8 = 0x01;
pub const INTEGER: u8 = 0x02;
pub const BIT_STRING: u8 = 0x03;
pub const OCTET_STRING: u8 = 0x04;
pub const OID: u8 = 0x06;
pub const UTC_TIME: u8 = 0x17;
pub const GENERALIZED_TIME: u8 = 0x18;
pub const SEQUENCE: u8 = 0x30;
/// Reads the elements of a value one after another.
#[derive(Clone, Copy)]
pub struct Reader<'a> {
data: &'a [u8],
}
impl<'a> Reader<'a> {
pub fn new(data: &'a [u8]) -> Reader<'a> {
Reader { data }
}
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// The next element, if a whole one is there.
pub fn read(&mut self) -> Option<Tlv<'a>> {
let (&tag, rest) = self.data.split_first()?;
let (&first, rest) = rest.split_first()?;
let (len, rest) = if first < 0x80 {
(usize::from(first), rest)
} else {
// Long form: one to three bytes of length, no indefinite form.
let n = usize::from(first & 0x7f);
if n == 0 || n > 3 || rest.len() < n {
return None;
}
let len = rest[..n].iter().fold(0usize, |l, &b| (l << 8) | usize::from(b));
(len, &rest[n..])
};
if rest.len() < len {
return None;
}
let header = self.data.len() - rest.len();
let whole = &self.data[..header + len];
let value = &rest[..len];
self.data = &rest[len..];
Some(Tlv { tag, value, whole })
}
/// The next element's value, if it has `tag`.
pub fn expect(&mut self, tag: u8) -> Option<&'a [u8]> {
let tlv = self.read()?;
(tlv.tag == tag).then_some(tlv.value)
}
/// The next element, when it has `tag`; else nothing is read.
pub fn optional(&mut self, tag: u8) -> Option<Tlv<'a>> {
let mut ahead = *self;
let tlv = ahead.read()?;
if tlv.tag == tag {
*self = ahead;
Some(tlv)
} else {
None
}
}
}