1#[cfg(feature = "alloc")]
16use alloc::vec::Vec;
17use core::marker::PhantomData;
18
19use crate::{Error, error::DerTypeId};
20
21#[derive(Debug)]
23pub struct DerIterator<'a, T> {
24 reader: untrusted::Reader<'a>,
25 marker: PhantomData<T>,
26}
27
28impl<'a, T> DerIterator<'a, T> {
29 pub(crate) fn new(input: untrusted::Input<'a>) -> Self {
31 Self {
32 reader: untrusted::Reader::new(input),
33 marker: PhantomData,
34 }
35 }
36}
37
38impl<'a, T: FromDer<'a>> Iterator for DerIterator<'a, T> {
39 type Item = Result<T, Error>;
40
41 fn next(&mut self) -> Option<Self::Item> {
42 (!self.reader.at_end()).then(|| T::from_der(&mut self.reader))
43 }
44}
45
46pub(crate) trait FromDer<'a>: Sized + 'a {
47 fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error>;
49
50 const TYPE_ID: DerTypeId;
51}
52
53pub(crate) fn read_all<'a, T: FromDer<'a>>(input: untrusted::Input<'a>) -> Result<T, Error> {
54 input.read_all(Error::TrailingData(T::TYPE_ID), T::from_der)
55}
56
57#[allow(clippy::upper_case_acronyms)]
59#[derive(Clone, Copy, Eq, PartialEq)]
60#[repr(u8)]
61pub(crate) enum Tag {
62 Boolean = 0x01,
63 Integer = 0x02,
64 BitString = 0x03,
65 OctetString = 0x04,
66 OID = 0x06,
67 Enum = 0x0A,
68 Sequence = CONSTRUCTED | 0x10, UTCTime = 0x17,
70 GeneralizedTime = 0x18,
71
72 #[allow(clippy::identity_op)]
73 ContextSpecificConstructed0 = CONTEXT_SPECIFIC | CONSTRUCTED | 0,
74 ContextSpecificConstructed1 = CONTEXT_SPECIFIC | CONSTRUCTED | 1,
75 ContextSpecificConstructed3 = CONTEXT_SPECIFIC | CONSTRUCTED | 3,
76}
77
78pub(crate) const CONSTRUCTED: u8 = 0x20;
79pub(crate) const CONTEXT_SPECIFIC: u8 = 0x80;
80
81impl From<Tag> for usize {
82 #[allow(clippy::as_conversions)]
83 fn from(tag: Tag) -> Self {
84 tag as Self
85 }
86}
87
88impl From<Tag> for u8 {
89 #[allow(clippy::as_conversions)]
90 fn from(tag: Tag) -> Self {
91 tag as Self
92 } }
94
95#[inline(always)]
96pub(crate) fn expect_tag_and_get_value_limited<'a>(
97 input: &mut untrusted::Reader<'a>,
98 tag: Tag,
99 size_limit: usize,
100) -> Result<untrusted::Input<'a>, Error> {
101 let (actual_tag, inner) = read_tag_and_get_value_limited(input, size_limit)?;
102 if usize::from(tag) != usize::from(actual_tag) {
103 return Err(Error::BadDer);
104 }
105 Ok(inner)
106}
107
108pub(crate) fn nested_limited<'a, R>(
109 input: &mut untrusted::Reader<'a>,
110 tag: Tag,
111 error: Error,
112 decoder: impl FnOnce(&mut untrusted::Reader<'a>) -> Result<R, Error>,
113 size_limit: usize,
114) -> Result<R, Error> {
115 match expect_tag_and_get_value_limited(input, tag, size_limit) {
116 Ok(value) => value.read_all(error, decoder),
117 Err(_) => Err(error),
118 }
119}
120
121pub(crate) fn nested<'a, R>(
124 input: &mut untrusted::Reader<'a>,
125 tag: Tag,
126 error: Error,
127 decoder: impl FnOnce(&mut untrusted::Reader<'a>) -> Result<R, Error>,
128) -> Result<R, Error> {
129 nested_limited(input, tag, error, decoder, TWO_BYTE_DER_SIZE)
130}
131
132pub(crate) fn expect_tag<'a>(
133 input: &mut untrusted::Reader<'a>,
134 tag: Tag,
135) -> Result<untrusted::Input<'a>, Error> {
136 let (actual_tag, value) = read_tag_and_get_value_limited(input, TWO_BYTE_DER_SIZE)?;
137 if usize::from(tag) != usize::from(actual_tag) {
138 return Err(Error::BadDer);
139 }
140
141 Ok(value)
142}
143
144#[inline(always)]
145pub(crate) fn read_tag_and_get_value<'a>(
146 input: &mut untrusted::Reader<'a>,
147) -> Result<(u8, untrusted::Input<'a>), Error> {
148 read_tag_and_get_value_limited(input, TWO_BYTE_DER_SIZE)
149}
150
151#[inline(always)]
152pub(crate) fn read_tag_and_get_value_limited<'a>(
153 input: &mut untrusted::Reader<'a>,
154 size_limit: usize,
155) -> Result<(u8, untrusted::Input<'a>), Error> {
156 let tag = input.read_byte().map_err(end_of_input_err)?;
157 if (tag & HIGH_TAG_RANGE_START) == HIGH_TAG_RANGE_START {
158 return Err(Error::BadDer); }
160
161 let length = match input.read_byte().map_err(end_of_input_err)? {
165 n if (n & SHORT_FORM_LEN_MAX) == 0 => usize::from(n),
166 LONG_FORM_LEN_ONE_BYTE => {
167 let length_byte = input.read_byte().map_err(end_of_input_err)?;
168 if length_byte < SHORT_FORM_LEN_MAX {
169 return Err(Error::BadDer); }
171 usize::from(length_byte)
172 }
173 LONG_FORM_LEN_TWO_BYTES => {
174 let length_byte_one = usize::from(input.read_byte().map_err(end_of_input_err)?);
175 let length_byte_two = usize::from(input.read_byte().map_err(end_of_input_err)?);
176 let combined = (length_byte_one << 8) | length_byte_two;
177 if combined <= LONG_FORM_LEN_ONE_BYTE_MAX {
178 return Err(Error::BadDer); }
180 combined
181 }
182 LONG_FORM_LEN_THREE_BYTES => {
183 let length_byte_one = usize::from(input.read_byte().map_err(end_of_input_err)?);
184 let length_byte_two = usize::from(input.read_byte().map_err(end_of_input_err)?);
185 let length_byte_three = usize::from(input.read_byte().map_err(end_of_input_err)?);
186 let combined = (length_byte_one << 16) | (length_byte_two << 8) | length_byte_three;
187 if combined <= LONG_FORM_LEN_TWO_BYTES_MAX {
188 return Err(Error::BadDer); }
190 combined
191 }
192 LONG_FORM_LEN_FOUR_BYTES => {
193 let length_byte_one = usize::from(input.read_byte().map_err(end_of_input_err)?);
194 let length_byte_two = usize::from(input.read_byte().map_err(end_of_input_err)?);
195 let length_byte_three = usize::from(input.read_byte().map_err(end_of_input_err)?);
196 let length_byte_four = usize::from(input.read_byte().map_err(end_of_input_err)?);
197 let combined = (length_byte_one << 24)
198 | (length_byte_two << 16)
199 | (length_byte_three << 8)
200 | length_byte_four;
201 if combined <= LONG_FORM_LEN_THREE_BYTES_MAX {
202 return Err(Error::BadDer); }
204 combined
205 }
206 _ => {
207 return Err(Error::BadDer); }
209 };
210
211 if length >= size_limit {
212 return Err(Error::BadDer); }
214
215 let inner = input.read_bytes(length).map_err(end_of_input_err)?;
216 Ok((tag, inner))
217}
218
219#[cfg(feature = "alloc")]
222#[allow(clippy::as_conversions)]
223pub(crate) fn asn1_wrap(tag: Tag, bytes: &[u8]) -> Vec<u8> {
224 let len = bytes.len();
225 if len < usize::from(SHORT_FORM_LEN_MAX) {
227 let mut ret = Vec::with_capacity(2 + len);
230 ret.push(tag.into()); ret.push(len as u8); ret.extend_from_slice(bytes); ret
234 } else {
235 let size = len.to_be_bytes();
240 let leading_zero_bytes = size
243 .iter()
244 .position(|&byte| byte != 0)
245 .unwrap_or(size.len());
246 assert!(leading_zero_bytes < size.len());
247 let encoded_bytes = size.len() - leading_zero_bytes;
249 let mut ret = Vec::with_capacity(2 + encoded_bytes + len);
250 let number_of_length_bytes_byte = SHORT_FORM_LEN_MAX + encoded_bytes as u8;
252 ret.push(tag.into()); ret.push(number_of_length_bytes_byte); ret.extend_from_slice(&size[leading_zero_bytes..]); ret.extend_from_slice(bytes); ret
257 }
258}
259
260pub(crate) const TWO_BYTE_DER_SIZE: usize = LONG_FORM_LEN_TWO_BYTES_MAX;
266
267pub(crate) const MAX_DER_SIZE: usize = LONG_FORM_LEN_FOUR_BYTES_MAX;
272
273const HIGH_TAG_RANGE_START: u8 = 31;
278
279const SHORT_FORM_LEN_MAX: u8 = 128;
283
284const LONG_FORM_LEN_ONE_BYTE: u8 = 0x81;
286
287const LONG_FORM_LEN_ONE_BYTE_MAX: usize = 0xff;
289
290const LONG_FORM_LEN_TWO_BYTES: u8 = 0x82;
292
293const LONG_FORM_LEN_TWO_BYTES_MAX: usize = 0xff_ff;
295
296const LONG_FORM_LEN_THREE_BYTES: u8 = 0x83;
298
299const LONG_FORM_LEN_THREE_BYTES_MAX: usize = 0xff_ff_ff;
301
302const LONG_FORM_LEN_FOUR_BYTES: u8 = 0x84;
304
305const LONG_FORM_LEN_FOUR_BYTES_MAX: usize = 0xff_ff_ff_ff;
307
308pub(crate) fn nested_of_mut<'a>(
311 input: &mut untrusted::Reader<'a>,
312 outer_tag: Tag,
313 inner_tag: Tag,
314 error: Error,
315 allow_empty: bool,
316 mut decoder: impl FnMut(&mut untrusted::Reader<'a>) -> Result<(), Error>,
317) -> Result<(), Error> {
318 nested(input, outer_tag, error.clone(), |outer| {
319 if allow_empty && outer.at_end() {
320 return Ok(());
321 }
322 loop {
323 nested(outer, inner_tag, error.clone(), |inner| decoder(inner))?;
324 if outer.at_end() {
325 break;
326 }
327 }
328 Ok(())
329 })
330}
331
332pub(crate) fn bit_string_with_no_unused_bits<'a>(
333 input: &mut untrusted::Reader<'a>,
334) -> Result<untrusted::Input<'a>, Error> {
335 nested(
336 input,
337 Tag::BitString,
338 Error::TrailingData(DerTypeId::BitString),
339 |value| {
340 let unused_bits_at_end = value.read_byte().map_err(|_| Error::BadDer)?;
341 if unused_bits_at_end != 0 {
342 return Err(Error::BadDer);
343 }
344 Ok(value.read_bytes_to_end())
345 },
346 )
347}
348
349pub(crate) struct BitStringFlags<'a> {
350 raw_bits: &'a [u8],
351}
352
353impl BitStringFlags<'_> {
354 pub(crate) fn bit_set(&self, bit: usize) -> bool {
355 let byte_index = bit / 8;
356 let bit_shift = 7 - (bit % 8);
357
358 if self.raw_bits.len() < (byte_index + 1) {
359 false
360 } else {
361 ((self.raw_bits[byte_index] >> bit_shift) & 1) != 0
362 }
363 }
364}
365
366pub(crate) fn bit_string_flags(input: untrusted::Input<'_>) -> Result<BitStringFlags<'_>, Error> {
374 input.read_all(Error::BadDer, |bit_string| {
375 let padding_bits = bit_string.read_byte().map_err(|_| Error::BadDer)?;
380 let raw_bits = bit_string.read_bytes_to_end().as_slice_less_safe();
381
382 if padding_bits > 7 || (raw_bits.is_empty() && padding_bits != 0) {
385 return Err(Error::BadDer);
386 }
387
388 let last_byte = raw_bits[raw_bits.len() - 1];
391 let padding_mask = (1 << padding_bits) - 1;
392
393 match padding_bits > 0 && (last_byte & padding_mask) != 0 {
394 true => Err(Error::BadDer),
395 false => Ok(BitStringFlags { raw_bits }),
396 }
397 })
398}
399
400impl<'a> FromDer<'a> for u8 {
401 fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
402 match *nonnegative_integer(reader)?.as_slice_less_safe() {
403 [b] => Ok(b),
404 _ => Err(Error::BadDer),
405 }
406 }
407
408 const TYPE_ID: DerTypeId = DerTypeId::U8;
409}
410
411pub(crate) fn nonnegative_integer<'a>(
412 input: &mut untrusted::Reader<'a>,
413) -> Result<untrusted::Input<'a>, Error> {
414 let value = expect_tag(input, Tag::Integer)?;
415 match value
416 .as_slice_less_safe()
417 .split_first()
418 .ok_or(Error::BadDer)?
419 {
420 (0, rest) => {
422 match rest.first() {
423 None => Ok(value),
425 Some(&second) if second & 0x80 == 0x80 => Ok(untrusted::Input::from(rest)),
427 _ => Err(Error::BadDer),
429 }
430 }
431 (first, _) if first & 0x80 == 0x00 => Ok(value),
433 (_, _) => Err(Error::BadDer),
435 }
436}
437
438pub(crate) fn end_of_input_err(_: untrusted::EndOfInput) -> Error {
439 Error::BadDer
440}
441
442impl<'a> FromDer<'a> for bool {
445 fn from_der(reader: &mut untrusted::Reader<'a>) -> Result<Self, Error> {
446 if !reader.peek(Tag::Boolean.into()) {
447 return Ok(false);
448 }
449
450 nested(
451 reader,
452 Tag::Boolean,
453 Error::TrailingData(Self::TYPE_ID),
454 |input| match input.read_byte() {
455 Ok(0xff) => Ok(true),
456 Ok(0x00) => Ok(false),
457 _ => Err(Error::BadDer),
458 },
459 )
460 }
461
462 const TYPE_ID: DerTypeId = DerTypeId::Bool;
463}
464
465macro_rules! oid {
466 ( $first:expr, $second:expr, $( $tail:expr ),* ) =>
467 (
468 [(40 * $first) + $second, $( $tail ),*]
469 )
470}
471
472#[cfg(test)]
473mod tests {
474 use super::DerTypeId;
475 use std::prelude::v1::*;
476
477 #[cfg(feature = "alloc")]
478 #[test]
479 fn test_asn1_wrap() {
480 let wrap_in_sequence = |bytes: &[u8]| super::asn1_wrap(super::Tag::Sequence, bytes);
482
483 assert_eq!(vec![0x30, 0x00], wrap_in_sequence(&[]));
485
486 assert_eq!(
488 vec![0x30, 0x04, 0x00, 0x11, 0x22, 0x33],
489 wrap_in_sequence(&[0x00, 0x11, 0x22, 0x33])
490 );
491
492 let mut val = Vec::new();
494 val.resize(255, 0x12);
495 assert_eq!(
496 vec![0x30, 0x81, 0xff, 0x12, 0x12, 0x12],
497 wrap_in_sequence(&val)[..6]
498 );
499
500 let mut val = Vec::new();
502 val.resize(4660, 0x12);
503 wrap_in_sequence(&val);
504 assert_eq!(
505 vec![0x30, 0x82, 0x12, 0x34, 0x12, 0x12],
506 wrap_in_sequence(&val)[..6]
507 );
508
509 let mut val = Vec::new();
511 val.resize(0xffff, 0x12);
512 let result = wrap_in_sequence(&val);
513 assert_eq!(vec![0x30, 0x82, 0xff, 0xff, 0x12, 0x12], result[..6]);
514 assert_eq!(result.len(), 0xffff + 4);
515
516 let mut val = Vec::new();
518 val.resize(0x100000, 0x12);
519 let result = wrap_in_sequence(&val);
520 assert_eq!(vec![0x30, 0x83, 0x10, 0x00, 0x00, 0x12, 0x12], result[..7]);
521 assert_eq!(result.len(), 0x100000 + 5);
522
523 let mut val = Vec::new();
525 val.resize(0x1000000, 0x12);
526 let result = wrap_in_sequence(&val);
527 assert_eq!(
528 vec![0x30, 0x84, 0x01, 0x00, 0x00, 0x00, 0x12, 0x12],
529 result[..8]
530 );
531 assert_eq!(result.len(), 0x1000000 + 6);
532 }
533
534 #[test]
535 fn test_optional_boolean() {
536 use super::{Error, FromDer};
537
538 assert!(!bool::from_der(&mut bytes_reader(&[])).unwrap());
540
541 assert!(!bool::from_der(&mut bytes_reader(&[0x05, 0x00])).unwrap());
543
544 assert_eq!(
546 Err(Error::BadDer),
547 bool::from_der(&mut bytes_reader(&[0x01, 0x01, 0x42]))
548 );
549
550 assert!(bool::from_der(&mut bytes_reader(&[0x01, 0x01, 0xff])).unwrap());
552
553 assert!(!bool::from_der(&mut bytes_reader(&[0x01, 0x01, 0x00])).unwrap());
555 }
556
557 #[test]
558 fn test_bit_string_with_no_unused_bits() {
559 use super::{Error, bit_string_with_no_unused_bits};
560
561 assert_eq!(
563 bit_string_with_no_unused_bits(&mut bytes_reader(&[0x01, 0x01, 0xff])).unwrap_err(),
564 Error::TrailingData(DerTypeId::BitString),
565 );
566
567 assert_eq!(
569 bit_string_with_no_unused_bits(&mut bytes_reader(&[0x42, 0xff, 0xff])).unwrap_err(),
570 Error::TrailingData(DerTypeId::BitString),
571 );
572
573 assert_eq!(
575 bit_string_with_no_unused_bits(&mut bytes_reader(&[])).unwrap_err(),
576 Error::TrailingData(DerTypeId::BitString),
577 );
578
579 assert_eq!(
581 bit_string_with_no_unused_bits(&mut bytes_reader(&[0x03, 0x03, 0x04, 0x12, 0x34]))
582 .unwrap_err(),
583 Error::BadDer,
584 );
585
586 assert_eq!(
588 bit_string_with_no_unused_bits(&mut bytes_reader(&[0x03, 0x03, 0x00, 0x12, 0x34]))
589 .unwrap()
590 .as_slice_less_safe(),
591 &[0x12, 0x34],
592 );
593 }
594
595 fn bytes_reader(bytes: &[u8]) -> untrusted::Reader<'_> {
596 untrusted::Reader::new(untrusted::Input::from(bytes))
597 }
598
599 #[test]
600 fn read_tag_and_get_value_default_limit() {
601 use super::{Error, read_tag_and_get_value};
602
603 let inputs = &[
604 &[EXAMPLE_TAG, 0x83, 0xFF, 0xFF, 0xFF].as_slice(),
606 &[EXAMPLE_TAG, 0x84, 0xFF, 0xFF, 0xFF, 0xFF].as_slice(),
608 ];
609
610 for input in inputs {
611 let mut bytes = untrusted::Reader::new(untrusted::Input::from(input));
612 assert!(matches!(
615 read_tag_and_get_value(&mut bytes),
616 Err(Error::BadDer)
617 ));
618 }
619 }
620
621 #[test]
622 fn read_tag_and_get_value_limited_high_form() {
623 use super::{Error, LONG_FORM_LEN_TWO_BYTES_MAX, read_tag_and_get_value_limited};
624
625 let mut bytes = untrusted::Reader::new(untrusted::Input::from(&[0xFF]));
626 assert!(matches!(
628 read_tag_and_get_value_limited(&mut bytes, LONG_FORM_LEN_TWO_BYTES_MAX),
629 Err(Error::BadDer)
630 ));
631 }
632
633 #[test]
634 fn read_tag_and_get_value_limited_non_canonical() {
635 use super::{Error, LONG_FORM_LEN_TWO_BYTES_MAX, read_tag_and_get_value_limited};
636
637 let inputs = &[
638 &[EXAMPLE_TAG, 0x81, 0x01].as_slice(),
640 &[EXAMPLE_TAG, 0x82, 0x00, 0x01].as_slice(),
642 &[EXAMPLE_TAG, 0x83, 0x00, 0x00, 0x01].as_slice(),
644 &[EXAMPLE_TAG, 0x84, 0x00, 0x00, 0x00, 0x01].as_slice(),
646 ];
647
648 for input in inputs {
649 let mut bytes = untrusted::Reader::new(untrusted::Input::from(input));
650 assert!(matches!(
652 read_tag_and_get_value_limited(&mut bytes, LONG_FORM_LEN_TWO_BYTES_MAX),
653 Err(Error::BadDer)
654 ));
655 }
656 }
657
658 #[test]
659 #[cfg(feature = "alloc")]
660 fn read_tag_and_get_value_limited_limits() {
661 use super::{Error, read_tag_and_get_value_limited};
662
663 let short_input = &[0xFF];
664 let short_input_encoded = &[
665 &[EXAMPLE_TAG],
666 der_encode_length(short_input.len()).as_slice(),
667 short_input,
668 ]
669 .concat();
670
671 let long_input = &[1_u8; 65537];
672 let long_input_encoded = &[
673 &[EXAMPLE_TAG],
674 der_encode_length(long_input.len()).as_slice(),
675 long_input,
676 ]
677 .concat();
678
679 struct Testcase<'a> {
680 input: &'a [u8],
681 limit: usize,
682 err: Option<Error>,
683 }
684
685 let testcases = &[
686 Testcase {
687 input: short_input_encoded,
688 limit: 1,
689 err: Some(Error::BadDer),
690 },
691 Testcase {
692 input: short_input_encoded,
693 limit: short_input_encoded.len() + 1,
694 err: None,
695 },
696 Testcase {
697 input: long_input_encoded,
698 limit: long_input.len(),
699 err: Some(Error::BadDer),
700 },
701 Testcase {
702 input: long_input_encoded,
703 limit: long_input.len() + 1,
704 err: None,
705 },
706 ];
707
708 for tc in testcases {
709 let mut bytes = untrusted::Reader::new(untrusted::Input::from(tc.input));
710
711 let res = read_tag_and_get_value_limited(&mut bytes, tc.limit);
712 match &tc.err {
713 None => assert!(res.is_ok()),
714 Some(e) => {
715 let actual = res.unwrap_err();
716 assert_eq!(&actual, e)
717 }
718 }
719 }
720 }
721
722 #[allow(clippy::as_conversions)] const EXAMPLE_TAG: u8 = super::Tag::Sequence as u8;
724
725 #[cfg(feature = "alloc")]
726 #[allow(clippy::as_conversions)] fn der_encode_length(length: usize) -> Vec<u8> {
728 if length < 128 {
729 vec![length as u8]
730 } else {
731 let mut encoded: Vec<u8> = Vec::new();
732 let mut remaining_length = length;
733
734 while remaining_length > 0 {
735 let byte = (remaining_length & 0xFF) as u8;
736 encoded.insert(0, byte);
737 remaining_length >>= 8;
738 }
739
740 let length_octet = encoded.len() as u8 | 0x80;
741 encoded.insert(0, length_octet);
742
743 encoded
744 }
745 }
746
747 #[test]
748 fn misencoded_bit_string_flags() {
749 use super::{Error, bit_string_flags};
750
751 let bad_padding_example = untrusted::Input::from(&[
752 0x08, 0x06, ]);
755 assert!(matches!(
756 bit_string_flags(bad_padding_example),
757 Err(Error::BadDer)
758 ));
759
760 let bad_padding_example = untrusted::Input::from(&[
761 0x01, ]);
764 assert!(matches!(
765 bit_string_flags(bad_padding_example),
766 Err(Error::BadDer)
767 ));
768 }
769
770 #[test]
771 fn valid_bit_string_flags() {
772 use super::bit_string_flags;
773
774 let example_key_usage = untrusted::Input::from(&[
775 0x01, 0x06, ]);
778 let res = bit_string_flags(example_key_usage).unwrap();
779
780 assert!(!res.bit_set(0));
781 assert!(!res.bit_set(1));
782 assert!(!res.bit_set(2));
783 assert!(!res.bit_set(3));
784 assert!(!res.bit_set(4));
785 assert!(res.bit_set(5));
787 assert!(res.bit_set(6));
788 assert!(!res.bit_set(7));
789 assert!(!res.bit_set(8));
790 assert!(!res.bit_set(256));
792 }
793
794 #[test]
795 fn test_small_nonnegative_integer() {
796 use super::{Error, FromDer, Tag};
797
798 for value in 0..=127 {
799 let data = [Tag::Integer.into(), 1, value];
800 let mut rd = untrusted::Reader::new(untrusted::Input::from(&data));
801 assert_eq!(u8::from_der(&mut rd), Ok(value),);
802 }
803
804 for value in 128..=255 {
805 let data = [Tag::Integer.into(), 2, 0x00, value];
806 let mut rd = untrusted::Reader::new(untrusted::Input::from(&data));
807 assert_eq!(u8::from_der(&mut rd), Ok(value),);
808 }
809
810 assert_eq!(
812 u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[
813 Tag::Sequence.into(),
814 1,
815 1
816 ]))),
817 Err(Error::BadDer)
818 );
819
820 assert_eq!(
822 u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[
823 Tag::Integer.into(),
824 1,
825 0xff
826 ]))),
827 Err(Error::BadDer)
828 );
829
830 assert_eq!(
832 u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[
833 Tag::Integer.into(),
834 2,
835 0x01,
836 0x00
837 ]))),
838 Err(Error::BadDer)
839 );
840
841 assert_eq!(
843 u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[
844 Tag::Integer.into(),
845 2,
846 0x00,
847 0x05
848 ]))),
849 Err(Error::BadDer)
850 );
851
852 assert_eq!(
854 u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[]))),
855 Err(Error::BadDer)
856 );
857
858 assert_eq!(
859 u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[
860 Tag::Integer.into(),
861 ]))),
862 Err(Error::BadDer)
863 );
864
865 assert_eq!(
866 u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[
867 Tag::Integer.into(),
868 1,
869 ]))),
870 Err(Error::BadDer)
871 );
872
873 assert_eq!(
874 u8::from_der(&mut untrusted::Reader::new(untrusted::Input::from(&[
875 Tag::Integer.into(),
876 2,
877 0
878 ]))),
879 Err(Error::BadDer)
880 );
881 }
882}