Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ jobs:
toolchain: stable
profile: minimal

- name: check formatting
uses: actions-rs/cargo@v1
with:
command: fmt
args: --check
- name: Test with a feature subset
uses: actions-rs/cargo@v1
with:
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name = "flexiber"
version = "0.1.1"
authors = ["Nicolas Stalder <n@stalder.io>", "RustCrypto Developers"]
license = "Apache-2.0 OR MIT"
edition = "2018"
edition = "2021"
description = "Encoding and decoding of BER-TLV as described in ISO 7816-4, without allocations."
repository = "https://github.com/trussed-dev/flexiber"
categories = ["cryptography", "data-structures", "encoding", "no-std"]
Expand Down
6 changes: 3 additions & 3 deletions derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name = "flexiber_derive"
version = "0.1.0"
authors = ["Nicolas Stalder <n@stalder.io>", "RustCrypto Developers"]
license = "Apache-2.0 OR MIT"
edition = "2018"
edition = "2021"
description = "Procedural macros to derive `Decodable` and `Encodable` from `flexiber`."
repository = "https://github.com/nickray/flexiber/tree/main/derive"
categories = ["cryptography", "data-structures", "encoding", "no-std"]
Expand All @@ -15,5 +15,5 @@ proc-macro = true
[dependencies]
proc-macro2 = "1"
quote = "1"
syn = "1"
synstructure = "0.12"
syn = "2"
synstructure = "0.13"
347 changes: 238 additions & 109 deletions derive/src/lib.rs

Large diffs are not rendered by default.

9 changes: 6 additions & 3 deletions src/decoder.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use core::convert::TryInto;
use crate::{Decodable, ErrorKind, Length, Result, TagLike};
use core::convert::TryInto;

/// BER-TLV decoder.
#[derive(Debug)]
Expand Down Expand Up @@ -36,7 +36,10 @@ impl<'a> Decoder<'a> {
}

/// Decode a TaggedValue with tag checked to be as expected, returning the value
pub fn decode_tagged_value<T: Decodable<'a> + TagLike, V: Decodable<'a>>(&mut self, tag: T) -> Result<V> {
pub fn decode_tagged_value<T: Decodable<'a> + TagLike, V: Decodable<'a>>(
&mut self,
tag: T,
) -> Result<V> {
let tagged: crate::TaggedSlice<T> = self.decode()?;
tagged.tag().assert_eq(tag)?;
Self::new(tagged.as_bytes()).decode()
Expand Down Expand Up @@ -117,7 +120,7 @@ impl<'a> Decoder<'a> {
pub(crate) fn peek(&self) -> Option<u8> {
self.remaining()
.ok()
.and_then(|bytes| bytes.get(0).cloned())
.and_then(|bytes| bytes.first().cloned())
}

/// Obtain the remaining bytes in this decoder from the current cursor
Expand Down
13 changes: 10 additions & 3 deletions src/encoder.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{header::Header, Encodable, ErrorKind, Length, Result, Tag};
use core::convert::{TryFrom, TryInto};
use crate::{Encodable, ErrorKind, header::Header, Length, Result, Tag};

/// BER-TLV encoder.
#[derive(Debug)]
Expand Down Expand Up @@ -58,7 +58,11 @@ impl<'a> Encoder<'a> {
}

/// Encode a collection of values which impl the [`Encodable`] trait under a given tag.
pub fn encode_tagged_collection(&mut self, tag: Tag, encodables: &[&dyn Encodable]) -> Result<()> {
pub fn encode_tagged_collection(
&mut self,
tag: Tag,
encodables: &[&dyn Encodable],
) -> Result<()> {
let expected_len = Length::try_from(encodables)?;
Header::new(tag, expected_len).and_then(|header| header.encode(self))?;

Expand Down Expand Up @@ -163,7 +167,10 @@ mod tests {

let tv = TaggedSlice::from(Tag::application(5).constructed(), &[]).unwrap();
let mut buf = [0u8; 4];
assert_eq!(tv.encode_to_slice(&mut buf).unwrap(), &[(0b01 << 6) | (1 << 5) | 5, 0x00]);
assert_eq!(
tv.encode_to_slice(&mut buf).unwrap(),
&[(0b01 << 6) | (1 << 5) | 5, 0x00]
);
}

// use super::Encoder;
Expand Down
7 changes: 3 additions & 4 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,6 @@ pub enum ErrorKind {

// /// Malformed OID
// Oid,

/// Integer overflow occurred (library bug!)
Overflow,

Expand Down Expand Up @@ -184,10 +183,8 @@ pub enum ErrorKind {
// /// Tag of the unexpected value
// tag: Tag,
// },

/// Tag does not fit in 3 bytes
UnsupportedTagSize,

}

impl ErrorKind {
Expand Down Expand Up @@ -239,7 +236,9 @@ impl fmt::Display for ErrorKind {
// }
// ErrorKind::Utf8(e) => write!(f, "{}", e),
// ErrorKind::Value { tag } => write!(f, "malformed ASN.1 DER value for {}", tag),
ErrorKind::UnsupportedTagSize => write!(f, "tags occupying more than 3 octets not supported"),
ErrorKind::UnsupportedTagSize => {
write!(f, "tags occupying more than 3 octets not supported")
}
}
}
}
7 changes: 5 additions & 2 deletions src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,10 @@ where

let length = Length::decode(decoder).map_err(|e| {
if e.kind() == ErrorKind::Overlength {
ErrorKind::Length { tag: tag.embedding() }.into()
ErrorKind::Length {
tag: tag.embedding(),
}
.into()
} else {
e
}
Expand All @@ -44,7 +47,7 @@ where

impl<T> Encodable for Header<T>
where
T: Encodable
T: Encodable,
{
fn encoded_length(&self) -> Result<Length> {
self.tag.encoded_length()? + self.length.encoded_length()?
Expand Down
3 changes: 1 addition & 2 deletions src/length.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ impl<'a> TryFrom<&'a [&'a dyn Encodable]> for Length {
fn try_from(encodables: &[&dyn Encodable]) -> Result<Length> {
encodables
.iter()
.fold(Ok(Length::zero()), |sum, encodable| {
.try_fold(Length::zero(), |sum, encodable| {
sum + encodable.encoded_length()?
})
}
Expand Down Expand Up @@ -172,7 +172,6 @@ impl Encodable for Length {
}
}


impl fmt::Display for Length {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
Expand Down
3 changes: 1 addition & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,12 @@ pub use simpletag::SimpleTag;
pub use slice::Slice;
pub use tag::{Class, Tag, TagLike};
pub use tagged::{TaggedSlice, TaggedValue};
pub use traits::{Container, Decodable, Encodable, Tagged};
#[cfg(feature = "heapless")]
pub use traits::EncodableHeapless;
pub use traits::{Container, Decodable, Encodable, Tagged};

// #[derive(Clone, Copy, Debug, Decodable, Encodable, Eq, PartialEq)]
// struct T2<'a> {
// #[tlv(simple = "0x55", slice)]
// a: &'a [u8],
// }

15 changes: 10 additions & 5 deletions src/simpletag.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use crate::{
Decodable, Decoder, Encodable, Encoder, Error, ErrorKind, Length, Result, Tag, TagLike,
};
use core::convert::TryFrom;
use crate::{Decodable, Decoder, Encodable, Encoder, Error, ErrorKind, Length, Result, Tag, TagLike};

/// These are tags like in SIMPLE-TLV.
///
Expand All @@ -24,7 +26,11 @@ impl TryFrom<u8> for SimpleTag {
impl TagLike for SimpleTag {
fn embedding(self) -> Tag {
use crate::Class::*;
Tag { class: Universal, constructed: false, number: self.0 as u16 }
Tag {
class: Universal,
constructed: false,
number: self.0 as u16,
}
}
}

Expand All @@ -44,18 +50,17 @@ impl Encodable for SimpleTag {
}
}


#[cfg(test)]
mod tests {
use core::convert::TryFrom;
use crate::{Encodable, SimpleTag, TaggedSlice};
use core::convert::TryFrom;

#[test]
fn simple_tag() {
let mut buf = [0u8; 384];

let tag = SimpleTag::try_from(37).unwrap();
let slice = &[1u8,2,3];
let slice = &[1u8, 2, 3];
let short = TaggedSlice::from(tag, slice).unwrap();

assert_eq!(
Expand Down
3 changes: 1 addition & 2 deletions src/slice.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use core::convert::TryFrom;
use crate::{Length, Result};
use core::convert::TryFrom;

/// Slice of at most `Length::max()` bytes.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Expand Down Expand Up @@ -42,4 +42,3 @@ impl AsRef<[u8]> for Slice<'_> {
self.as_bytes()
}
}

78 changes: 56 additions & 22 deletions src/tag.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
use core::{convert::{TryFrom, TryInto}, fmt};
use crate::{Decodable, Decoder, Encodable, Encoder, Error, ErrorKind, Length, Result, TaggedValue};
use crate::{
Decodable, Decoder, Encodable, Encoder, Error, ErrorKind, Length, Result, TaggedValue,
};
use core::{
convert::{TryFrom, TryInto},
fmt,
};

const CLASS_OFFSET: usize = 6;
const CONSTRUCTED_OFFSET: usize = 5;
Expand Down Expand Up @@ -42,7 +47,6 @@ pub struct Tag {
pub number: u16,
}


impl Tag {
pub const BOOLEAN: Self = Self::universal(0x1);
pub const INTEGER: Self = Self::universal(0x1);
Expand All @@ -58,27 +62,55 @@ impl Tag {
pub const SET: Self = Self::universal(0x11).constructed();

pub fn from(class: Class, constructed: bool, number: u16) -> Self {
Self { class, constructed, number }
Self {
class,
constructed,
number,
}
}
pub const fn universal(number: u16) -> Self {
Self { class: Class::Universal, constructed: false, number }
Self {
class: Class::Universal,
constructed: false,
number,
}
}

pub const fn application(number: u16) -> Self {
Self { class: Class::Application, constructed: false, number }
Self {
class: Class::Application,
constructed: false,
number,
}
}

pub const fn context(number: u16) -> Self {
Self { class: Class::Context, constructed: false, number }
Self {
class: Class::Context,
constructed: false,
number,
}
}

pub const fn private(number: u16) -> Self {
Self { class: Class::Private, constructed: false, number }
Self {
class: Class::Private,
constructed: false,
number,
}
}

pub const fn constructed(self) -> Self {
let Self { class, constructed: _, number } = self;
Self { class, constructed: true, number }
let Self {
class,
constructed: _,
number,
} = self;
Self {
class,
constructed: true,
number,
}
}
}

Expand Down Expand Up @@ -144,7 +176,11 @@ impl fmt::Debug for Tag {
let mut buf = [0u8; 3];
let mut encoder = Encoder::new(&mut buf);
encoder.encode(self).unwrap();
write!(f, "Tag(class = {:?}, constructed = {}, number = {})", self.class, self.constructed, self.number)
write!(
f,
"Tag(class = {:?}, constructed = {}, number = {})",
self.class, self.constructed, self.number
)
}
}

Expand All @@ -159,8 +195,8 @@ impl Encodable for Tag {
}

fn encode(&self, encoder: &mut Encoder<'_>) -> Result<()> {

let first_byte = ((self.class as u8) << CLASS_OFFSET) | ((self.constructed as u8) << CONSTRUCTED_OFFSET);
let first_byte =
((self.class as u8) << CLASS_OFFSET) | ((self.constructed as u8) << CONSTRUCTED_OFFSET);

match self.number {
0..=0x1E => encoder.byte(first_byte | (self.number as u8)),
Expand All @@ -173,10 +209,7 @@ impl Encodable for Tag {
encoder.byte(NOT_LAST_TAG_OCTET_FLAG | (self.number >> 7) as u8)?;
encoder.byte((self.number & 0x7F) as u8)
}
0x4000..=0xFFFF => {
// todo()
return Err(Error::from(ErrorKind::UnsupportedTagSize));
}
0x4000..=0xFFFF => Err(Error::from(ErrorKind::UnsupportedTagSize)),
}
}
}
Expand All @@ -190,9 +223,7 @@ impl Decodable<'_> for Tag {
let first_byte_masked = first_byte & ((1 << 5) - 1);

let number = match first_byte_masked {
number @ 0..=0x1E => {
number as u16
}
number @ 0..=0x1E => number as u16,
_ => {
let second_byte = decoder.byte()?;
if second_byte & NOT_LAST_TAG_OCTET_FLAG == 0 {
Expand All @@ -210,11 +241,14 @@ impl Decodable<'_> for Tag {
}
}
};
Ok(Self { class, constructed, number })
Ok(Self {
class,
constructed,
number,
})
}
}


#[cfg(test)]
mod tests {
use crate::{Decodable, Encodable, Tag};
Expand Down
Loading
Loading