1mod config;
4pub(super) mod parser;
5
6use super::identifier::Identifier;
7use crate::{
8 types::{
9 self,
10 oid::{MAX_OID_FIRST_OCTET, MAX_OID_SECOND_OCTET},
11 Constraints, Enumerated, Tag,
12 },
13 Decode,
14};
15use alloc::{borrow::Cow, borrow::ToOwned, string::ToString, vec::Vec};
16use chrono::{DateTime, NaiveDate, NaiveDateTime};
17use parser::ParseNumberError;
18
19pub use self::config::DecoderOptions;
20
21pub use crate::error::DecodeError;
22pub use crate::error::{BerDecodeErrorKind, CodecDecodeError, DecodeErrorKind, DerDecodeErrorKind};
23type Result<T, E = DecodeError> = core::result::Result<T, E>;
24
25const EOC: &[u8] = &[0, 0];
26
27pub struct Decoder<'input> {
29 input: &'input [u8],
30 config: DecoderOptions,
31 initial_len: usize,
32}
33
34impl<'input> Decoder<'input> {
35 #[must_use]
37 pub fn codec(&self) -> crate::Codec {
38 self.config.current_codec()
39 }
40 #[must_use]
42 pub fn remaining(&self) -> &'input [u8] {
43 self.input
44 }
45 #[must_use]
47 pub fn new(input: &'input [u8], config: DecoderOptions) -> Self {
48 Self {
49 input,
50 config,
51 initial_len: input.len(),
52 }
53 }
54
55 #[must_use]
57 pub fn decoded_len(&self) -> usize {
58 self.initial_len - self.input.len()
59 }
60
61 fn parse_eoc(&mut self) -> Result<()> {
62 let (i, _) = nom::bytes::streaming::tag(EOC)(self.input)
63 .map_err(|e| DecodeError::map_nom_err(e, self.codec()))?;
64 self.input = i;
65 Ok(())
66 }
67
68 pub(crate) fn parse_value(&mut self, tag: Tag) -> Result<(Identifier, Option<&'input [u8]>)> {
69 let (input, (identifier, contents)) =
70 self::parser::parse_value(&self.config, self.input, Some(tag))?;
71 self.input = input;
72 Ok((identifier, contents))
73 }
74
75 pub(crate) fn parse_primitive_value(&mut self, tag: Tag) -> Result<(Identifier, &'input [u8])> {
76 let (input, (identifier, contents)) =
77 self::parser::parse_value(&self.config, self.input, Some(tag))?;
78 self.input = input;
79 match contents {
80 Some(contents) => Ok((identifier, contents)),
81 None => Err(BerDecodeErrorKind::IndefiniteLengthNotAllowed.into()),
82 }
83 }
84
85 fn parse_constructed_contents<D, F>(
89 &mut self,
90 tag: Tag,
91 check_identifier: bool,
92 decode_fn: F,
93 ) -> Result<D>
94 where
95 F: FnOnce(&mut Self) -> Result<D>,
96 {
97 let (identifier, contents) = self.parse_value(tag)?;
98
99 BerDecodeErrorKind::assert_tag(tag, identifier.tag)?;
100
101 if check_identifier && identifier.is_primitive() {
102 return Err(BerDecodeErrorKind::InvalidConstructedIdentifier.into());
103 }
104
105 let (streaming, contents) = match contents {
106 Some(contents) => (false, contents),
107 None => (true, self.input),
108 };
109
110 let mut inner = Self::new(contents, self.config);
111
112 let result = (decode_fn)(&mut inner)?;
113
114 if streaming {
115 self.input = inner.input;
116 self.parse_eoc()?;
117 } else if !inner.input.is_empty() {
118 return Err(DecodeError::unexpected_extra_data(
119 inner.input.len(),
120 self.codec(),
121 ));
122 }
123
124 Ok(result)
125 }
126 pub fn decode_object_identifier_from_bytes(
129 &self,
130 data: &[u8],
131 ) -> Result<crate::types::ObjectIdentifier, DecodeError> {
132 let (mut contents, root_octets) =
133 parser::parse_base128_number(data).map_err(|e| match e {
134 ParseNumberError::Nom(e) => DecodeError::map_nom_err(e, self.codec()),
135 ParseNumberError::Overflow => DecodeError::integer_overflow(32u32, self.codec()),
136 })?;
137 let first: u32;
138 let second: u32;
139 const MAX_OID_THRESHOLD: u32 = MAX_OID_SECOND_OCTET + 1;
140 if root_octets > MAX_OID_FIRST_OCTET * MAX_OID_THRESHOLD + MAX_OID_SECOND_OCTET {
141 first = MAX_OID_FIRST_OCTET;
142 second = root_octets - MAX_OID_FIRST_OCTET * MAX_OID_THRESHOLD;
143 } else {
144 second = root_octets % MAX_OID_THRESHOLD;
145 first = (root_octets - second) / MAX_OID_THRESHOLD;
146 }
147
148 let mut buffer = alloc::vec::Vec::with_capacity(core::cmp::min(contents.len() + 2, 16));
152 buffer.push(first);
153 buffer.push(second);
154
155 while !contents.is_empty() {
156 let (c, number) = parser::parse_base128_number(contents).map_err(|e| match e {
157 ParseNumberError::Nom(e) => DecodeError::map_nom_err(e, self.codec()),
158 ParseNumberError::Overflow => DecodeError::integer_overflow(32u32, self.codec()),
159 })?;
160 contents = c;
161 buffer.push(number);
162 }
163 crate::types::ObjectIdentifier::new(buffer)
164 .ok_or_else(|| BerDecodeErrorKind::InvalidObjectIdentifier.into())
165 }
166 pub fn parse_any_generalized_time_string(
169 string: alloc::string::String,
170 ) -> Result<types::GeneralizedTime, DecodeError> {
171 let mut s = if string.contains(',') {
178 string.replace(',', ".")
179 } else {
180 string
181 };
182 if s.ends_with("Z") {
183 s.pop(); }
185 let has_offset = s.len() >= 5 && {
187 let bytes = s.as_bytes();
188 bytes[s.len() - 5] == b'+' || bytes[s.len() - 5] == b'-'
189 };
190 let format_candidates: &[&str] = if s.contains('.') {
191 if has_offset {
192 &["%Y%m%d%H%M%S%.f%z", "%Y%m%d%H%M%.f%z", "%Y%m%d%H%.f%z"] } else {
194 &["%Y%m%d%H%M%S%.f", "%Y%m%d%H%M%.f", "%Y%m%d%H%.f"] }
196 } else if has_offset {
197 match s.len() {
198 19 => &["%Y%m%d%H%M%S%z"],
200 17 => &["%Y%m%d%H%M%z"],
201 15 => &["%Y%m%d%H%z"],
202 _ => &["%Y%m%d%H%M%S%z", "%Y%m%d%H%M%z", "%Y%m%d%H%z"],
203 }
204 } else {
205 match s.len() {
207 8 => &["%Y%m%d"],
208 10 => &["%Y%m%d%H"],
209 12 => &["%Y%m%d%H%M"],
210 14 => &["%Y%m%d%H%M%S"],
211 _ => &[],
212 }
213 };
214 for fmt in format_candidates {
215 if has_offset {
216 if let Ok(dt) = DateTime::parse_from_str(&s, fmt) {
217 return Ok(dt);
218 }
219 } else if let Ok(dt) = NaiveDateTime::parse_from_str(&s, fmt) {
220 return Ok(dt.and_utc().into());
221 }
222 }
223 Err(BerDecodeErrorKind::invalid_date(s).into())
224 }
225 pub fn parse_canonical_generalized_time_string(
227 string: alloc::string::String,
228 ) -> Result<types::GeneralizedTime, DecodeError> {
229 let len = string.len();
230 let parse_without_timezone =
232 |string: &str| -> core::result::Result<NaiveDateTime, DecodeError> {
233 let len = string.len();
234 if string.contains('.') {
235 NaiveDateTime::parse_from_str(string, "%Y%m%d%H%M%S%.f")
237 .map_err(|_| BerDecodeErrorKind::invalid_date(string.to_string()).into())
238 } else if len == 14 {
239 NaiveDateTime::parse_from_str(string, "%Y%m%d%H%M%S")
240 .map_err(|_| BerDecodeErrorKind::invalid_date(string.to_string()).into())
241 } else {
242 Err(BerDecodeErrorKind::invalid_date(string.to_string()).into())
247 }
248 };
249 if string.ends_with('Z') {
250 let naive = parse_without_timezone(&string[..len - 1])?;
251 Ok(naive.and_utc().into())
252 } else {
253 Err(BerDecodeErrorKind::invalid_date(string.to_string()).into())
254 }
255 }
256 pub fn parse_any_utc_time_string(
259 string: alloc::string::String,
260 ) -> Result<types::UtcTime, DecodeError> {
261 let len = string.len();
263 if len > 17 {
265 return Err(BerDecodeErrorKind::invalid_date(string.to_string()).into());
266 }
267 let format = if string.contains('Z') {
268 if len == 11 {
269 "%y%m%d%H%MZ"
270 } else {
271 "%y%m%d%H%M%SZ"
272 }
273 } else if len == 15 {
274 "%y%m%d%H%M%z"
275 } else {
276 "%y%m%d%H%M%S%z"
277 };
278 match len {
279 11 | 13 => {
280 let naive = NaiveDateTime::parse_from_str(&string, format)
281 .map_err(|_| BerDecodeErrorKind::invalid_date(string.to_string()))?;
282 Ok(naive.and_utc())
283 }
284 15 | 17 => Ok(DateTime::parse_from_str(&string, format)
285 .map_err(|_| BerDecodeErrorKind::invalid_date(string.to_string()))?
286 .into()),
287 _ => Err(BerDecodeErrorKind::invalid_date(string.to_string()).into()),
288 }
289 }
290
291 pub fn parse_canonical_utc_time_string(string: &str) -> Result<types::UtcTime, DecodeError> {
293 let len = string.len();
294 if string.ends_with('Z') {
295 let naive = match len {
296 13 => NaiveDateTime::parse_from_str(string, "%y%m%d%H%M%SZ")
297 .map_err(|_| BerDecodeErrorKind::invalid_date(string.to_string()))?,
298 _ => Err(BerDecodeErrorKind::invalid_date(string.to_string()))?,
299 };
300 Ok(naive.and_utc())
301 } else {
302 Err(BerDecodeErrorKind::invalid_date(string.to_string()).into())
303 }
304 }
305
306 pub fn parse_date_string(string: &str) -> Result<types::Date, DecodeError> {
308 let date = NaiveDate::parse_from_str(string, "%Y%m%d")
309 .map_err(|_| BerDecodeErrorKind::invalid_date(string.to_string()))?;
310
311 Ok(date)
312 }
313}
314
315impl<'input> crate::Decoder for Decoder<'input> {
316 type Ok = ();
317 type Error = DecodeError;
318 type AnyDecoder<const R: usize, const E: usize> = Decoder<'input>;
319
320 fn codec(&self) -> crate::Codec {
321 Self::codec(self)
322 }
323 fn decode_any(&mut self) -> Result<types::Any> {
324 let (mut input, (identifier, contents)) =
325 self::parser::parse_value(&self.config, self.input, None)?;
326
327 if contents.is_none() {
328 let (i, _) = self::parser::parse_encoded_value(
329 &self.config,
330 self.input,
331 identifier.tag,
332 |input, _| Ok(alloc::vec::Vec::from(input)),
333 )?;
334 input = i;
335 }
336 let diff = self.input.len() - input.len();
337 let contents = &self.input[..diff];
338 self.input = input;
339
340 Ok(types::Any {
341 contents: contents.to_vec(),
342 })
343 }
344
345 fn decode_bool(&mut self, tag: Tag) -> Result<bool> {
346 let (_, contents) = self.parse_primitive_value(tag)?;
347 DecodeError::assert_length(1, contents.len(), self.codec())?;
348 Ok(match contents[0] {
349 0 => false,
350 0xFF => true,
351 _ if self.config.encoding_rules.is_ber() => true,
352 _ => {
353 return Err(DecodeError::from_kind(
354 DecodeErrorKind::InvalidBool { value: contents[0] },
355 self.codec(),
356 ))
357 }
358 })
359 }
360
361 fn decode_enumerated<E: Enumerated>(&mut self, tag: Tag) -> Result<E> {
362 let discriminant = self.decode_integer::<isize>(tag, Constraints::default())?;
363
364 E::from_discriminant(discriminant)
365 .ok_or_else(|| DecodeError::discriminant_value_not_found(discriminant, self.codec()))
366 }
367
368 fn decode_integer<I: types::IntegerType>(&mut self, tag: Tag, _: Constraints) -> Result<I> {
369 let primitive_bytes = self.parse_primitive_value(tag)?.1;
370 let integer_width = I::WIDTH as usize / 8;
371 if primitive_bytes.len() > integer_width {
372 let leading_byte = if primitive_bytes[0] & 0x80 == 0x80 {
376 0xFF
377 } else {
378 0x00
379 };
380 let input_iter = primitive_bytes
381 .iter()
382 .copied()
383 .skip_while(|n| *n == leading_byte);
384 let data_length = input_iter.clone().count();
385 I::try_from_bytes(
386 &primitive_bytes[primitive_bytes.len() - data_length..primitive_bytes.len()],
387 self.codec(),
388 )
389 } else {
390 I::try_from_bytes(primitive_bytes, self.codec())
391 }
392 }
393
394 fn decode_real<R: types::RealType>(
395 &mut self,
396 _: Tag,
397 _: Constraints,
398 ) -> Result<R, Self::Error> {
399 Err(DecodeError::real_not_supported(self.codec()))
400 }
401
402 fn decode_octet_string<'b, T: From<&'b [u8]> + From<Vec<u8>>>(
403 &'b mut self,
404 tag: Tag,
405 _: Constraints,
406 ) -> Result<T> {
407 let (identifier, contents) = self.parse_value(tag)?;
408
409 if identifier.is_primitive() {
410 match contents {
411 Some(c) => Ok(T::from(c)),
412 None => Err(BerDecodeErrorKind::IndefiniteLengthNotAllowed.into()),
413 }
414 } else if identifier.is_constructed() && self.config.encoding_rules.is_der() {
415 Err(DerDecodeErrorKind::ConstructedEncodingNotAllowed.into())
416 } else {
417 let mut buffer = Vec::new();
418
419 if let Some(mut contents) = contents {
420 while !contents.is_empty() {
421 let (c, mut vec) = self::parser::parse_encoded_value(
422 &self.config,
423 contents,
424 Tag::OCTET_STRING,
425 |input, _| Ok(alloc::vec::Vec::from(input)),
426 )?;
427 contents = c;
428
429 buffer.append(&mut vec);
430 }
431 } else {
432 while !self.input.starts_with(EOC) {
433 let (c, mut vec) = self::parser::parse_encoded_value(
434 &self.config,
435 self.input,
436 Tag::OCTET_STRING,
437 |input, _| Ok(alloc::vec::Vec::from(input)),
438 )?;
439 self.input = c;
440
441 buffer.append(&mut vec);
442 }
443
444 self.parse_eoc()?;
445 }
446 Ok(T::from(buffer))
447 }
448 }
449
450 fn decode_null(&mut self, tag: Tag) -> Result<()> {
451 let (_, contents) = self.parse_primitive_value(tag)?;
452 DecodeError::assert_length(0, contents.len(), self.codec())?;
453 Ok(())
454 }
455
456 fn decode_object_identifier(&mut self, tag: Tag) -> Result<crate::types::ObjectIdentifier> {
457 let contents = self.parse_primitive_value(tag)?.1;
458 self.decode_object_identifier_from_bytes(contents)
459 }
460
461 fn decode_bit_string(&mut self, tag: Tag, _: Constraints) -> Result<types::BitString> {
462 let (input, bs) =
463 self::parser::parse_encoded_value(&self.config, self.input, tag, |input, codec| {
464 let unused_bits = input
465 .first()
466 .copied()
467 .ok_or(DecodeError::unexpected_empty_input(codec))?;
468
469 match unused_bits {
470 bits @ 0..=7 => {
472 let mut buffer = input[1..].to_owned();
473 if let Some(last) = buffer.last_mut() {
474 *last &= !((1 << bits) - 1);
475 }
476
477 let mut string = types::BitString::from_vec(buffer);
478 let bit_length = string
479 .len()
480 .checked_sub(bits as usize)
481 .ok_or_else(|| DecodeError::invalid_bit_string(unused_bits, codec))?;
482 string.truncate(bit_length);
483
484 Ok(string)
485 }
486 _ => Err(DecodeError::invalid_bit_string(unused_bits, codec)),
487 }
488 })?;
489
490 self.input = input;
491 Ok(bs)
492 }
493
494 fn decode_visible_string(
495 &mut self,
496 tag: Tag,
497 constraints: Constraints,
498 ) -> Result<types::VisibleString, Self::Error> {
499 types::VisibleString::try_from(
500 self.decode_octet_string::<Cow<[u8]>>(tag, constraints)?
501 .as_ref(),
502 )
503 .map_err(|e| DecodeError::permitted_alphabet_error(e, self.codec()))
504 }
505
506 fn decode_ia5_string(
507 &mut self,
508 tag: Tag,
509 constraints: Constraints,
510 ) -> Result<types::Ia5String> {
511 types::Ia5String::try_from(
512 self.decode_octet_string::<Cow<[u8]>>(tag, constraints)?
513 .as_ref(),
514 )
515 .map_err(|e| DecodeError::permitted_alphabet_error(e, self.codec()))
516 }
517
518 fn decode_printable_string(
519 &mut self,
520 tag: Tag,
521 constraints: Constraints,
522 ) -> Result<types::PrintableString> {
523 types::PrintableString::try_from(
524 self.decode_octet_string::<Cow<[u8]>>(tag, constraints)?
525 .as_ref(),
526 )
527 .map_err(|e| DecodeError::permitted_alphabet_error(e, self.codec()))
528 }
529
530 fn decode_numeric_string(
531 &mut self,
532 tag: Tag,
533 constraints: Constraints,
534 ) -> Result<types::NumericString> {
535 types::NumericString::try_from(
536 self.decode_octet_string::<Cow<[u8]>>(tag, constraints)?
537 .as_ref(),
538 )
539 .map_err(|e| DecodeError::permitted_alphabet_error(e, self.codec()))
540 }
541
542 fn decode_teletex_string(
543 &mut self,
544 tag: Tag,
545 constraints: Constraints,
546 ) -> Result<types::TeletexString> {
547 types::TeletexString::try_from(
548 self.decode_octet_string::<Cow<[u8]>>(tag, constraints)?
549 .as_ref(),
550 )
551 .map_err(|e| DecodeError::permitted_alphabet_error(e, self.codec()))
552 }
553
554 fn decode_bmp_string(
555 &mut self,
556 tag: Tag,
557 constraints: Constraints,
558 ) -> Result<types::BmpString> {
559 types::BmpString::try_from(
560 self.decode_octet_string::<Cow<[u8]>>(tag, constraints)?
561 .as_ref(),
562 )
563 .map_err(|e| DecodeError::permitted_alphabet_error(e, self.codec()))
564 }
565
566 fn decode_utf8_string(
567 &mut self,
568 tag: Tag,
569 constraints: Constraints,
570 ) -> Result<types::Utf8String> {
571 let vec = self.decode_octet_string(tag, constraints)?;
572 types::Utf8String::from_utf8(vec).map_err(|e| {
573 DecodeError::string_conversion_failed(
574 types::Tag::UTF8_STRING,
575 e.to_string(),
576 self.codec(),
577 )
578 })
579 }
580
581 fn decode_general_string(
582 &mut self,
583 tag: Tag,
584 constraints: Constraints,
585 ) -> Result<types::GeneralString> {
586 <types::GeneralString>::try_from(
587 self.decode_octet_string::<Cow<[u8]>>(tag, constraints)?
588 .as_ref(),
589 )
590 .map_err(|e| DecodeError::permitted_alphabet_error(e, self.codec()))
591 }
592
593 fn decode_graphic_string(
594 &mut self,
595 tag: Tag,
596 constraints: Constraints,
597 ) -> Result<types::GraphicString> {
598 <types::GraphicString>::try_from(
599 self.decode_octet_string::<Cow<[u8]>>(tag, constraints)?
600 .as_ref(),
601 )
602 .map_err(|e| DecodeError::permitted_alphabet_error(e, self.codec()))
603 }
604
605 fn decode_generalized_time(&mut self, tag: Tag) -> Result<types::GeneralizedTime> {
606 let string = self.decode_utf8_string(tag, Constraints::default())?;
607 if self.config.encoding_rules.is_ber() {
608 Self::parse_any_generalized_time_string(string)
609 } else {
610 Self::parse_canonical_generalized_time_string(string)
611 }
612 }
613
614 fn decode_utc_time(&mut self, tag: Tag) -> Result<types::UtcTime> {
615 let string = self.decode_utf8_string(tag, Constraints::default())?;
617 if self.config.encoding_rules.is_ber() {
618 Self::parse_any_utc_time_string(string)
619 } else {
620 Self::parse_canonical_utc_time_string(&string)
621 }
622 }
623
624 fn decode_date(&mut self, tag: Tag) -> core::result::Result<types::Date, Self::Error> {
625 let string = self.decode_utf8_string(tag, Constraints::default())?;
626 Self::parse_date_string(&string)
627 }
628
629 fn decode_sequence_of<D: Decode>(
630 &mut self,
631 tag: Tag,
632 _: Constraints,
633 ) -> Result<Vec<D>, Self::Error> {
634 self.parse_constructed_contents(tag, true, |decoder| {
635 let mut items = Vec::new();
636
637 if decoder.input.is_empty() {
638 return Ok(items);
639 }
640
641 while let Ok(item) = D::decode(decoder) {
642 items.push(item);
643
644 if decoder.input.is_empty() {
645 return Ok(items);
646 }
647 }
648
649 Ok(items)
650 })
651 }
652
653 fn decode_set_of<D: Decode + Eq + core::hash::Hash>(
654 &mut self,
655 tag: Tag,
656 _: Constraints,
657 ) -> Result<types::SetOf<D>, Self::Error> {
658 self.parse_constructed_contents(tag, true, |decoder| {
659 let mut items = types::SetOf::new();
660
661 while let Ok(item) = D::decode(decoder) {
662 items.insert(item);
663 }
664
665 Ok(items)
666 })
667 }
668
669 fn decode_sequence<
670 const RC: usize,
671 const EC: usize,
672 D: crate::types::Constructed<RC, EC>,
673 DF: FnOnce() -> D,
674 F: FnOnce(&mut Self) -> Result<D>,
675 >(
676 &mut self,
677 tag: Tag,
678 default_initializer_fn: Option<DF>,
679 decode_fn: F,
680 ) -> Result<D> {
681 self.parse_constructed_contents(tag, true, |decoder| {
682 if D::FIELDS.is_empty() && D::EXTENDED_FIELDS.is_none()
686 || (D::FIELDS.len() == D::FIELDS.number_of_optional_and_default_fields()
687 && decoder.input.is_empty())
688 {
689 if let Some(default_initializer_fn) = default_initializer_fn {
690 return Ok((default_initializer_fn)());
691 }
692 return Err(DecodeError::from_kind(
693 DecodeErrorKind::UnexpectedEmptyInput,
694 decoder.codec(),
695 ));
696 }
697 (decode_fn)(decoder)
698 })
699 }
700
701 fn decode_explicit_prefix<D: Decode>(&mut self, tag: Tag) -> Result<D> {
702 self.parse_constructed_contents(tag, false, D::decode)
703 }
704 fn decode_optional_with_explicit_prefix<D: Decode>(
705 &mut self,
706 tag: Tag,
707 ) -> Result<Option<D>, Self::Error> {
708 self.decode_explicit_prefix(tag)
709 .map(Some)
710 .or_else(|_| Ok(None))
711 }
712
713 fn decode_set<const RL: usize, const EL: usize, FIELDS, SET, D, F>(
714 &mut self,
715 tag: Tag,
716 _decode_fn: D,
717 field_fn: F,
718 ) -> Result<SET, Self::Error>
719 where
720 SET: Decode + crate::types::Constructed<RL, EL>,
721 FIELDS: Decode,
722 D: Fn(&mut Self, usize, Tag) -> Result<FIELDS, Self::Error>,
723 F: FnOnce(Vec<FIELDS>) -> Result<SET, Self::Error>,
724 {
725 self.parse_constructed_contents(tag, true, |decoder| {
726 let mut fields = Vec::new();
727
728 while let Ok(value) = FIELDS::decode(decoder) {
729 fields.push(value);
730 }
731
732 (field_fn)(fields)
733 })
734 }
735
736 fn decode_optional<D: Decode>(&mut self) -> Result<Option<D>, Self::Error> {
737 if D::TAG == Tag::EOC {
738 Ok(D::decode(self).ok())
739 } else {
740 self.decode_optional_with_tag(D::TAG)
741 }
742 }
743
744 fn decode_optional_with_tag<D: Decode>(&mut self, tag: Tag) -> Result<Option<D>, Self::Error> {
748 Ok(D::decode_with_tag(self, tag).ok())
749 }
750
751 fn decode_optional_with_constraints<D: Decode>(
752 &mut self,
753 constraints: Constraints,
754 ) -> Result<Option<D>, Self::Error> {
755 Ok(D::decode_with_constraints(self, constraints).ok())
756 }
757
758 fn decode_optional_with_tag_and_constraints<D: Decode>(
759 &mut self,
760 tag: Tag,
761 constraints: Constraints,
762 ) -> Result<Option<D>, Self::Error> {
763 Ok(D::decode_with_tag_and_constraints(self, tag, constraints).ok())
764 }
765
766 fn decode_choice<D>(&mut self, _: Constraints) -> Result<D, Self::Error>
767 where
768 D: crate::types::DecodeChoice,
769 {
770 let (_, identifier) = parser::parse_identifier_octet(self.input).map_err(|e| match e {
771 ParseNumberError::Nom(e) => DecodeError::map_nom_err(e, self.codec()),
772 ParseNumberError::Overflow => DecodeError::integer_overflow(32u32, self.codec()),
773 })?;
774 D::from_tag(self, identifier.tag)
775 }
776
777 fn decode_extension_addition_with_explicit_tag_and_constraints<D>(
778 &mut self,
779 tag: Tag,
780 _constraints: Constraints,
781 ) -> core::result::Result<Option<D>, Self::Error>
782 where
783 D: Decode,
784 {
785 self.decode_explicit_prefix(tag).map(Some)
786 }
787
788 fn decode_extension_addition_with_tag_and_constraints<D>(
789 &mut self,
790 tag: Tag,
791 _: Constraints,
793 ) -> core::result::Result<Option<D>, Self::Error>
794 where
795 D: Decode,
796 {
797 <Option<D>>::decode_with_tag(self, tag)
798 }
799
800 fn decode_extension_addition_group<
801 const RL: usize,
802 const EL: usize,
803 D: Decode + crate::types::Constructed<RL, EL>,
804 >(
805 &mut self,
806 ) -> Result<Option<D>, Self::Error> {
807 <Option<D>>::decode(self)
808 }
809}
810
811#[cfg(test)]
812mod tests {
813 use alloc::string::String;
814
815 #[derive(Clone, Copy, Hash, Debug, PartialEq)]
816 struct C2;
817 impl AsnType for C2 {
818 const TAG: Tag = Tag::new(Class::Context, 2);
819 }
820
821 #[derive(Clone, Copy, Hash, Debug, PartialEq)]
822 struct A3;
823 impl AsnType for A3 {
824 const TAG: Tag = Tag::new(Class::Application, 3);
825 }
826
827 #[derive(Clone, Copy, Hash, Debug, PartialEq)]
828 struct A7;
829 impl AsnType for A7 {
830 const TAG: Tag = Tag::new(Class::Application, 7);
831 }
832
833 use super::*;
834 use crate::types::*;
835
836 fn decode<T: crate::Decode>(input: &[u8]) -> Result<T, DecodeError> {
837 let mut decoder = self::Decoder::new(input, self::DecoderOptions::ber());
838 match T::decode(&mut decoder) {
839 Ok(result) => {
840 assert_eq!(decoder.decoded_len(), input.len());
841 Ok(result)
842 }
843 Err(e) => Err(e),
844 }
845 }
846
847 #[test]
848 fn boolean() {
849 assert!(decode::<bool>(&[0x01, 0x01, 0xff]).unwrap());
850 assert!(!decode::<bool>(&[0x01, 0x01, 0x00]).unwrap());
851 }
852
853 #[test]
854 fn tagged_boolean() {
855 assert_eq!(
856 Explicit::<C2, _>::new(true),
857 decode(&[0xa2, 0x03, 0x01, 0x01, 0xff]).unwrap()
858 );
859 }
860
861 #[test]
862 fn integer() {
863 assert_eq!(
864 32768,
865 decode::<i32>(&[0x02, 0x03, 0x00, 0x80, 0x00,]).unwrap()
866 );
867 assert_eq!(32767, decode::<i32>(&[0x02, 0x02, 0x7f, 0xff]).unwrap());
868 assert_eq!(256, decode::<i16>(&[0x02, 0x02, 0x01, 0x00]).unwrap());
869 assert_eq!(255, decode::<i16>(&[0x02, 0x02, 0x00, 0xff]).unwrap());
870 assert_eq!(128, decode::<i16>(&[0x02, 0x02, 0x00, 0x80]).unwrap());
871 assert_eq!(127, decode::<i8>(&[0x02, 0x01, 0x7f]).unwrap());
872 assert_eq!(1, decode::<i8>(&[0x02, 0x01, 0x01]).unwrap());
873 assert_eq!(0, decode::<i8>(&[0x02, 0x01, 0x00]).unwrap());
874 assert_eq!(-1, decode::<i8>(&[0x02, 0x01, 0xff]).unwrap());
875 assert_eq!(-128, decode::<i16>(&[0x02, 0x01, 0x80]).unwrap());
876 assert_eq!(-129i16, decode::<i16>(&[0x02, 0x02, 0xff, 0x7f]).unwrap());
877 assert_eq!(-256i16, decode::<i16>(&[0x02, 0x02, 0xff, 0x00]).unwrap());
878 assert_eq!(-32768i32, decode::<i32>(&[0x02, 0x02, 0x80, 0x00]).unwrap());
879 assert_eq!(
880 -32769i32,
881 decode::<i32>(&[0x02, 0x03, 0xff, 0x7f, 0xff]).unwrap()
882 );
883
884 let mut data = [0u8; 261];
885 data[0] = 0x02;
886 data[1] = 0x82;
887 data[2] = 0x01;
888 data[3] = 0x01;
889 data[4] = 0x01;
890 let mut bigint = num_bigint::BigInt::from(1);
891 bigint <<= 2048;
892 assert_eq!(bigint, decode::<num_bigint::BigInt>(&data).unwrap());
893 }
894
895 #[test]
896 fn octet_string() {
897 let octet_string = types::OctetString::from(alloc::vec![1, 2, 3, 4, 5, 6]);
898 let primitive_encoded = &[0x4, 0x6, 1, 2, 3, 4, 5, 6];
899 let constructed_encoded = &[0x24, 0x80, 0x4, 0x4, 1, 2, 3, 4, 0x4, 0x2, 5, 6, 0x0, 0x0];
900
901 assert_eq!(
902 octet_string,
903 decode::<types::OctetString>(primitive_encoded).unwrap()
904 );
905 assert_eq!(
906 octet_string,
907 decode::<types::OctetString>(constructed_encoded).unwrap()
908 );
909 }
910
911 #[test]
912 fn bit_string() {
913 let mut bitstring =
914 types::BitString::from_vec([0x0A, 0x3B, 0x5F, 0x29, 0x1C, 0xD0][..].to_owned());
915 bitstring.truncate(bitstring.len() - 4);
916
917 let primitive_encoded: types::BitString =
918 decode(&[0x03, 0x07, 0x04, 0x0A, 0x3B, 0x5F, 0x29, 0x1C, 0xD0][..]).unwrap();
919
920 let constructed_encoded: types::BitString = decode(
921 &[
922 0x23, 0x80, 0x03, 0x03, 0x00, 0x0A, 0x3B, 0x03, 0x05, 0x04, 0x5F, 0x29, 0x1C, 0xD0, 0x00, 0x00, ][..],
927 )
928 .unwrap();
929
930 assert_eq!(bitstring, primitive_encoded);
931 assert_eq!(bitstring, constructed_encoded);
932
933 let empty_bitstring_primitive_encoded: types::BitString =
934 decode(&[0x03, 0x01, 0x00][..]).unwrap();
935 assert_eq!(
936 types::BitString::from_vec(vec![]),
937 empty_bitstring_primitive_encoded
938 );
939
940 assert!(decode::<types::BitString>(&[0x03, 0x00][..]).is_err());
941 }
942
943 #[test]
944 fn utf8_string() {
945 let name = String::from("Jones");
946 let primitive = &[0x0C, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73];
947 let definite_constructed = &[
948 0x2C, 0x09, 0x04, 0x03, 0x4A, 0x6F, 0x6E, 0x04, 0x02, 0x65, 0x73,
952 ];
953 let indefinite_constructed = &[
954 0x2C, 0x80, 0x04, 0x03, 0x4A, 0x6F, 0x6E, 0x04, 0x02, 0x65, 0x73, 0x00, 0x00,
958 ];
959
960 assert_eq!(name, decode::<String>(primitive).unwrap());
961 assert_eq!(name, decode::<String>(definite_constructed).unwrap());
962 assert_eq!(name, decode::<String>(indefinite_constructed).unwrap());
963 }
964
965 #[test]
966 fn utc_time() {
967 let time =
968 crate::types::GeneralizedTime::parse_from_str("991231235959+0000", "%y%m%d%H%M%S%z")
969 .unwrap();
970 let has_z = &[
972 0x17, 0x0D, 0x39, 0x39, 0x31, 0x32, 0x33, 0x31, 0x32, 0x33, 0x35, 0x39, 0x35, 0x39,
973 0x5A,
974 ];
975 let has_noz = &[
977 0x17, 0x11, 0x39, 0x39, 0x31, 0x32, 0x33, 0x31, 0x32, 0x33, 0x35, 0x39, 0x35, 0x39,
978 0x2B, 0x30, 0x30, 0x30, 0x30,
979 ];
980 assert_eq!(
981 time,
982 decode::<chrono::DateTime::<chrono::Utc>>(has_z).unwrap()
983 );
984
985 assert_eq!(
986 time,
987 crate::der::decode::<crate::types::UtcTime>(has_z).unwrap()
988 );
989
990 assert_eq!(
991 time,
992 decode::<chrono::DateTime::<chrono::Utc>>(has_noz).unwrap()
993 );
994 assert!(crate::der::decode::<crate::types::UtcTime>(has_noz).is_err());
995 }
996
997 #[test]
998 fn generalized_time() {
999 let time = crate::types::GeneralizedTime::parse_from_str(
1000 "20001231205959.999+0000",
1001 "%Y%m%d%H%M%S%.3f%z",
1002 )
1003 .unwrap();
1004 let has_z = &[
1005 0x18, 0x13, 0x32, 0x30, 0x30, 0x30, 0x31, 0x32, 0x33, 0x31, 0x32, 0x30, 0x35, 0x39,
1006 0x35, 0x39, 0x2E, 0x39, 0x39, 0x39, 0x5A,
1007 ];
1008 assert_eq!(
1009 time,
1010 decode::<chrono::DateTime::<chrono::FixedOffset>>(has_z).unwrap()
1011 );
1012 }
1013
1014 #[test]
1015 fn sequence_of() {
1016 let vec = alloc::vec!["Jon", "es"];
1017 let from_raw: Vec<String> = decode(
1018 &[
1019 0x30, 0x9, 0x0C, 0x03, 0x4A, 0x6F, 0x6E, 0x0C, 0x02, 0x65, 0x73,
1020 ][..],
1021 )
1022 .unwrap();
1023
1024 assert_eq!(vec, from_raw);
1025 }
1026
1027 #[test]
1028 fn sequence() {
1029 use types::Ia5String;
1030 #[derive(Debug, PartialEq)]
1032 struct Foo {
1033 name: Ia5String,
1034 ok: bool,
1035 }
1036
1037 impl types::Constructed<2, 0> for Foo {
1038 const FIELDS: types::fields::Fields<2> = types::fields::Fields::from_static([
1039 types::fields::Field::new_required(0, Ia5String::TAG, Ia5String::TAG_TREE, "name"),
1040 types::fields::Field::new_required(1, bool::TAG, bool::TAG_TREE, "ok"),
1041 ]);
1042 }
1043
1044 impl types::AsnType for Foo {
1045 const TAG: Tag = Tag::SEQUENCE;
1046 }
1047
1048 impl Decode for Foo {
1049 fn decode_with_tag_and_constraints<D: crate::Decoder>(
1050 decoder: &mut D,
1051 tag: Tag,
1052 _: Constraints,
1053 ) -> Result<Self, D::Error> {
1054 decoder.decode_sequence(tag, None::<fn() -> Self>, |sequence| {
1055 let name: Ia5String = Ia5String::decode(sequence)?;
1056 let ok: bool = bool::decode(sequence)?;
1057 Ok(Self { name, ok })
1058 })
1059 }
1060 }
1061
1062 let foo = Foo {
1063 name: String::from("Smith").try_into().unwrap(),
1064 ok: true,
1065 };
1066 let bytes = &[
1067 0x30, 0x0A, 0x16, 0x05, 0x53, 0x6d, 0x69, 0x74, 0x68, 0x01, 0x01, 0xff, ];
1071
1072 assert_eq!(foo, decode(bytes).unwrap());
1073 }
1074
1075 #[test]
1076 fn tagging() {
1077 type Type1 = VisibleString;
1078 type Type2 = Implicit<A3, Type1>;
1079 type Type3 = Explicit<C2, Type2>;
1080 type Type4 = Implicit<A7, Type3>;
1081 type Type5 = Implicit<C2, Type2>;
1082
1083 let jones = String::from("Jones");
1084 let jones1 = Type1::try_from(jones).unwrap();
1085 let jones2 = Type2::from(jones1.clone());
1086 let jones3 = Type3::from(jones2.clone());
1087 let jones4 = Type4::from(jones3.clone());
1088 let jones5 = Type5::from(jones2.clone());
1089
1090 assert_eq!(
1091 jones1,
1092 decode(&[0x1A, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73]).unwrap()
1093 );
1094 assert_eq!(
1095 jones2,
1096 decode(&[0x43, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73]).unwrap()
1097 );
1098 assert_eq!(
1099 jones3,
1100 decode(&[0xa2, 0x07, 0x43, 0x5, 0x4A, 0x6F, 0x6E, 0x65, 0x73]).unwrap()
1101 );
1102 assert_eq!(
1103 jones4,
1104 decode(&[0x67, 0x07, 0x43, 0x5, 0x4A, 0x6F, 0x6E, 0x65, 0x73]).unwrap()
1105 );
1106 assert_eq!(
1107 jones5,
1108 decode(&[0x82, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73]).unwrap()
1109 );
1110 }
1111
1112 #[test]
1113 fn flip1() {
1114 let _ = decode::<Open>(&[
1115 0x10, 0x10, 0x23, 0x00, 0xfe, 0x7f, 0x10, 0x03, 0x00, 0xff, 0xe4, 0x04, 0x50, 0x10,
1116 0x50, 0x10, 0x10, 0x10,
1117 ]);
1118 }
1119
1120 #[test]
1121 fn any() {
1122 let expected = &[0x1A, 0x05, 0x4A, 0x6F, 0x6E, 0x65, 0x73];
1123 assert_eq!(
1124 Any {
1125 contents: expected.to_vec()
1126 },
1127 decode(expected).unwrap()
1128 );
1129 }
1130
1131 #[test]
1132 fn any_indefinite() {
1133 let any = &[
1134 0x30, 0x80, 0x2C, 0x80, 0x04, 0x03, 0x4A, 0x6F, 0x6E, 0x04, 0x02, 0x65, 0x73, 0x00,
1135 0x00, 0x00, 0x00,
1136 ];
1137 assert_eq!(
1138 Any {
1139 contents: any.to_vec()
1140 },
1141 decode(any).unwrap(),
1142 );
1143 }
1144
1145 #[test]
1146 fn any_indefinite_fail_no_eoc() {
1147 let any = &[
1148 0x30, 0x80, 0x2C, 0x80, 0x04, 0x03, 0x4A, 0x6F, 0x6E, 0x04, 0x02, 0x65, 0x73, 0x00,
1149 0x00,
1150 ];
1151 assert!(decode::<Any>(any).is_err());
1152 }
1153
1154 #[test]
1155 fn decoding_oid() {
1156 use crate::Decoder;
1157
1158 let mut decoder =
1159 super::Decoder::new(&[0x06, 0x03, 0x88, 0x37, 0x01], DecoderOptions::der());
1160 let oid = decoder.decode_object_identifier(Tag::OBJECT_IDENTIFIER);
1161 assert!(oid.is_ok());
1162 let oid = oid.unwrap();
1163 assert_eq!(ObjectIdentifier::new([2, 999, 1].to_vec()).unwrap(), oid);
1164 }
1165}