1
1
//! Length calculations for encoded ASN.1 DER values
2
2
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
+ } ;
4
7
use core:: {
5
8
cmp:: Ordering ,
6
9
fmt,
@@ -25,8 +28,8 @@ impl Length {
25
28
/// Length of `1`
26
29
pub const ONE : Self = Self ( 1 ) ;
27
30
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 ) ;
30
33
31
34
/// Maximum number of octets in a DER encoding of a [`Length`] using the
32
35
/// rules implemented by this crate.
@@ -44,7 +47,7 @@ impl Length {
44
47
/// This function is const-safe and therefore useful for [`Length`] constants.
45
48
#[ allow( clippy:: cast_possible_truncation) ]
46
49
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 {
48
51
Err ( Error :: from_kind ( ErrorKind :: Overflow ) )
49
52
} else {
50
53
Ok ( Length ( len as u32 ) )
@@ -57,6 +60,12 @@ impl Length {
57
60
value == 0
58
61
}
59
62
63
+ /// Is this length indefinite?
64
+ pub const fn is_indefinite ( self ) -> bool {
65
+ let value = self . 0 ;
66
+ value == u32:: MAX
67
+ }
68
+
60
69
/// Get the length of DER Tag-Length-Value (TLV) encoded data if `self`
61
70
/// is the length of the inner "value" portion of the message.
62
71
pub fn for_tlv ( self , tag : Tag ) -> Result < Self > {
@@ -90,7 +99,7 @@ impl Length {
90
99
0x80 ..=0xFF => Some ( 0x81 ) ,
91
100
0x100 ..=0xFFFF => Some ( 0x82 ) ,
92
101
0x10000 ..=0xFFFFFF => Some ( 0x83 ) ,
93
- 0x1000000 ..=0xFFFFFFFF => Some ( 0x84 ) ,
102
+ 0x1000000 ..=0xFFFFFFFE => Some ( 0x84 ) ,
94
103
_ => None ,
95
104
}
96
105
}
@@ -214,6 +223,9 @@ impl<'a> Decode<'a> for Length {
214
223
// Note: per X.690 Section 8.1.3.6.1 the byte 0x80 encodes indefinite
215
224
// lengths, which are not allowed in DER, so disallow that byte.
216
225
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
+ }
217
229
INDEFINITE_LENGTH_OCTET => Err ( ErrorKind :: IndefiniteLength . into ( ) ) ,
218
230
// 1-4 byte variable-sized length prefix
219
231
tag @ 0x81 ..=0x84 => {
0 commit comments