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