1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
//! # Basic Encoding Rules

pub mod de;
pub mod enc;
mod identifier;
mod rules;

pub use identifier::Identifier;
pub(crate) use rules::EncodingRules;

/// Attempts to decode `T` from `input` using BER.
pub fn decode<T: crate::Decode>(input: &[u8]) -> Result<T, de::Error> {
    T::decode(&mut de::Decoder::new(input, de::DecoderOptions::ber()))
}

/// Attempts to encode `value` to BER.
pub fn encode<T: crate::Encode>(value: &T) -> Result<alloc::vec::Vec<u8>, enc::Error> {
    let mut enc = enc::Encoder::new(enc::EncoderOptions::ber());

    value.encode(&mut enc)?;

    Ok(enc.output)
}

#[cfg(test)]
mod tests {
    use alloc::borrow::ToOwned;
    use alloc::vec;
    use alloc::vec::Vec;

    use crate::{
        tag::{Class, Tag},
        types::*,
        AsnType,
    };

    use super::*;

    #[test]
    fn null() {
        assert_eq!((), decode::<()>(&*encode(&()).unwrap()).unwrap());
    }

    #[test]
    fn seven_bit_integers() {
        use num_traits::ToPrimitive;
        macro_rules! test {
            ($($num:literal == $expected:expr),*) => {
                $(
                let enc = enc::Encoder::new(enc::EncoderOptions::ber());
                let mut output = Vec::new();
                enc.encode_seven_bit_integer($num, &mut output);
                assert_eq!($expected, &*output);
                assert_eq!($num, de::parser::parse_encoded_number(&*output).unwrap().1.to_u32().unwrap());
                )*
            }
        }

        test! {
            840 == &[200, 6],
            113549 == &[141, 247, 6]
        }
    }

    #[test]
    fn bool() {
        assert_eq!(true, decode(&encode(&true).unwrap()).unwrap());
        assert_eq!(false, decode(&encode(&false).unwrap()).unwrap());
    }

    macro_rules! integer_tests {
        ($($integer:ident),*) => {
            $(
                #[test]
                fn $integer() {
                    let min = <$integer>::min_value();
                    let max = <$integer>::max_value();

                    assert_eq!(min, decode(&encode(&min).unwrap()).unwrap());
                    assert_eq!(max, decode(&encode(&max).unwrap()).unwrap());
                }
            )*
        }
    }

    integer_tests! {
        i8,
        i16,
        i32,
        i64,
        i128,
        isize,
        u8,
        u16,
        u32,
        u64,
        u128,
        usize
    }

    #[test]
    fn octet_string() {
        let a = OctetString::from(vec![1u8, 2, 3, 4, 5]);
        let b = OctetString::from(vec![5u8, 4, 3, 2, 1]);

        assert_eq!(a, decode::<OctetString>(&encode(&a).unwrap()).unwrap());
        assert_eq!(b, decode::<OctetString>(&encode(&b).unwrap()).unwrap());
    }

    #[test]
    fn utf8_string() {
        let name = "Jones";
        assert_eq!(
            name,
            decode::<Utf8String>(&*encode(&name).unwrap()).unwrap()
        );
    }

    #[test]
    fn long_sequence_of() {
        let vec = vec![5u8; 0xffff];
        assert_eq!(
            vec,
            decode::<alloc::vec::Vec<u8>>(&encode(&vec).unwrap()).unwrap()
        );
    }

    #[test]
    fn object_identifier() {
        let iso = ObjectIdentifier::new(vec![1, 2]);
        let us_ansi = ObjectIdentifier::new(vec![1, 2, 840]);
        let rsa = ObjectIdentifier::new(vec![1, 2, 840, 113549]);
        let pkcs = ObjectIdentifier::new(vec![1, 2, 840, 113549, 1]);
        let random = ObjectIdentifier::new(vec![0, 3, 0, 3]);

        assert_eq!(iso.clone(), decode(&encode(&iso).unwrap()).unwrap());
        assert_eq!(us_ansi.clone(), decode(&encode(&us_ansi).unwrap()).unwrap());
        let bytes = encode(&pkcs).unwrap();
        assert_eq!(pkcs.clone(), decode(&bytes).unwrap());

        assert_eq!(rsa.clone(), decode(&encode(&rsa).unwrap()).unwrap());
        assert_eq!(random.clone(), decode(&encode(&random).unwrap()).unwrap());
    }

    #[test]
    fn bit_string() {
        const DATA: &[u8] = &[0, 0xD0];
        let small = BitString::from_vec(DATA.to_owned());
        let bits = BitString::from_vec([0x0A, 0x3B, 0x5F, 0x29, 0x1C, 0xD0][..].to_owned());

        assert_eq!(
            small,
            decode::<BitString>(&encode(&small).unwrap()).unwrap()
        );
        assert_eq!(bits, decode::<BitString>(&encode(&bits).unwrap()).unwrap());
    }

    #[test]
    fn implicit_prefix() {
        #[derive(Debug, PartialEq)]
        struct C0;
        impl AsnType for C0 {
            const TAG: Tag = Tag::new(Class::Context, 0);
        }

        type MyInteger = Implicit<C0, u64>;

        let new_int = MyInteger::new(5);

        assert_eq!(new_int, decode(&encode(&new_int).unwrap()).unwrap());
    }

    #[test]
    fn explicit_prefix() {
        #[derive(Debug, PartialEq)]
        struct C0;
        impl AsnType for C0 {
            const TAG: Tag = Tag::new(Class::Context, 0);
        }

        type MyInteger = Explicit<C0, u64>;

        let new_int = MyInteger::new(5);

        assert_eq!(new_int, decode(&encode(&new_int).unwrap()).unwrap());
    }

    #[test]
    fn explicit_empty_tag() {
        use crate::{tag::Class, types::Explicit, AsnType, Tag};

        #[derive(Debug, PartialEq)]
        struct C0;
        impl AsnType for C0 {
            const TAG: Tag = Tag::new(Class::Context, 0);
        }

        let value = <Explicit<C0, _>>::new(None::<()>);
        let data = &[0x80, 0][..];

        assert_eq!(data, &*crate::ber::encode(&value).unwrap());
        assert_eq!(value, crate::ber::decode::<Explicit<C0, _>>(data).unwrap());
    }

    #[test]
    fn implicit_tagged_constructed() {
        use crate::{tag::Class, types::Implicit, AsnType, Tag};
        #[derive(Debug, PartialEq)]
        struct C0;
        impl AsnType for C0 {
            const TAG: Tag = Tag::new(Class::Context, 0);
        }

        let value = <Implicit<C0, _>>::new(vec![1, 2]);
        let data = &[0xA0, 6, 2, 1, 1, 2, 1, 2][..];

        assert_eq!(data, &*crate::ber::encode(&value).unwrap());
        assert_eq!(
            value,
            crate::ber::decode::<Implicit<C0, Vec<i32>>>(data).unwrap()
        );
    }
}