Skip to content

Commit 0b79ef6

Browse files
committed
der: add indefinite length demo
cargo fmt
1 parent d5ab6e8 commit 0b79ef6

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

der/src/length.rs

+17-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
//! Length calculations for encoded ASN.1 DER values
22
3-
use crate::{Decode, DerOrd, Encode, Error, ErrorKind, Reader, Result, SliceWriter, Tag, Writer};
3+
use crate::{
4+
Decode, DerOrd, Encode, EncodingRules, Error, ErrorKind, Reader, Result, SliceWriter, Tag,
5+
Writer,
6+
};
47
use core::{
58
cmp::Ordering,
69
fmt,
@@ -25,8 +28,8 @@ impl Length {
2528
/// Length of `1`
2629
pub const ONE: Self = Self(1);
2730

28-
/// Maximum length (`u32::MAX`).
29-
pub const MAX: Self = Self(u32::MAX);
31+
/// Maximum length (`u32::MAX` - 1).
32+
pub const MAX: Self = Self(u32::MAX - 1);
3033

3134
/// Maximum number of octets in a DER encoding of a [`Length`] using the
3235
/// rules implemented by this crate.
@@ -44,7 +47,7 @@ impl Length {
4447
/// This function is const-safe and therefore useful for [`Length`] constants.
4548
#[allow(clippy::cast_possible_truncation)]
4649
pub(crate) const fn new_usize(len: usize) -> Result<Self> {
47-
if len > (u32::MAX as usize) {
50+
if len > (u32::MAX as usize) - 1 {
4851
Err(Error::from_kind(ErrorKind::Overflow))
4952
} else {
5053
Ok(Length(len as u32))
@@ -57,6 +60,12 @@ impl Length {
5760
value == 0
5861
}
5962

63+
/// Is this length indefinite?
64+
pub const fn is_indefinite(self) -> bool {
65+
let value = self.0;
66+
value == u32::MAX
67+
}
68+
6069
/// Get the length of DER Tag-Length-Value (TLV) encoded data if `self`
6170
/// is the length of the inner "value" portion of the message.
6271
pub fn for_tlv(self, tag: Tag) -> Result<Self> {
@@ -90,7 +99,7 @@ impl Length {
9099
0x80..=0xFF => Some(0x81),
91100
0x100..=0xFFFF => Some(0x82),
92101
0x10000..=0xFFFFFF => Some(0x83),
93-
0x1000000..=0xFFFFFFFF => Some(0x84),
102+
0x1000000..=0xFFFFFFFE => Some(0x84),
94103
_ => None,
95104
}
96105
}
@@ -214,6 +223,9 @@ impl<'a> Decode<'a> for Length {
214223
// Note: per X.690 Section 8.1.3.6.1 the byte 0x80 encodes indefinite
215224
// lengths, which are not allowed in DER, so disallow that byte.
216225
len if len < INDEFINITE_LENGTH_OCTET => Ok(len.into()),
226+
INDEFINITE_LENGTH_OCTET if reader.encoding_rules() == EncodingRules::Ber => {
227+
Ok(Self(u32::MAX))
228+
}
217229
INDEFINITE_LENGTH_OCTET => Err(ErrorKind::IndefiniteLength.into()),
218230
// 1-4 byte variable-sized length prefix
219231
tag @ 0x81..=0x84 => {

0 commit comments

Comments
 (0)