#asn1-der #parser #red #codec #little #applications #integer

red_asn1

一个用于编码/解码ASN1 DER的小型库

14个不稳定版本 (3个破坏性更新)

0.3.5 2021年1月22日
0.3.4 2021年1月21日
0.3.3 2020年5月13日
0.3.1 2020年4月28日
0.0.9 2019年8月6日

#1416 in 解析器实现

Download history 70/week @ 2024-03-15 86/week @ 2024-03-22 126/week @ 2024-03-29 93/week @ 2024-04-05 123/week @ 2024-04-12 100/week @ 2024-04-19 128/week @ 2024-04-26 97/week @ 2024-05-03 104/week @ 2024-05-10 76/week @ 2024-05-17 101/week @ 2024-05-24 93/week @ 2024-05-31 84/week @ 2024-06-07 97/week @ 2024-06-14 151/week @ 2024-06-21 22/week @ 2024-06-28

每月下载量374次
用于 13 个crate(4个直接使用)

AGPL-3.0

92KB
2.5K SLoC

Red ASN1

一个用于构建/解析ASN1 DER的小型库

示例

解析和构建 bool

use red_asn1::Asn1Object;

assert_eq!(true, bool::parse(&[0x1, 0x1, 0xff]).unwrap().1);
assert_eq!(false, bool::parse(&[0x1, 0x1, 0x0]).unwrap().1);

assert_eq!(true.build(), vec![0x1, 0x1, 0xff]);
assert_eq!(false.build(), vec![0x1, 0x1, 0x0]);

解析和构建 Integer

use red_asn1::{Integer, Asn1Object};

assert_eq!(2, Integer::parse(&[0x2, 0x1, 0x2]).unwrap().1);
assert_eq!(2.build(), vec![0x2, 0x1, 0x2]);

解析和构建 String

use red_asn1::Asn1Object;

assert_eq!(
    "John".to_string(), 
    String::parse(&[0x1b, 0x4, 0x4a, 0x6f, 0x68, 0x6e]).unwrap().1
);

assert_eq!(
    "John".to_string().build(), 
    vec![0x1b, 0x4, 0x4a, 0x6f, 0x68, 0x6e]
);

创建自定义序列

/*
Person ::= [APPLICATION 1] SEQUENCE {
    name:       [0] GeneralString,
    age:        [1] Integer,
    address:    [2] GeneralString OPTIONAL,
}
*/

use red_asn1::*;
use red_asn1_derive::Sequence;

#[derive(Sequence, Default)]
#[seq(application_tag = 1)]
struct Person {
    #[seq_field(context_tag = 0)]
    pub name: GeneralString,
    #[seq_field(context_tag = 1)]
    pub age: Integer,
    #[seq_field(context_tag = 2)]
    pub address: Option<GeneralString>
}

let john = Person{
    name: GeneralString::from("John").into(),
    age: Integer::from(18).into(),
    address: None
};

assert_eq!(
    vec![
        0x61, 0xf, 0x30, 0xd,
        0xa0, 0x6, 0x1b, 0x4, 0x4a, 0x6f, 0x68, 0x6e, // "John"
        0xa1, 0x3, 0x2, 0x1, 0x12 // 18
    ]
    , john.build()
);

let (_, rachel) = Person::parse(&[
    0x61, 0x1b, 0x30, 0x19,
    0xa0, 0x8, 0x1b, 0x6, 0x52, 0x61, 0x63, 0x68, 0x65, 0x6c, // "Rachel"
    0xa1, 0x3, 0x2, 0x1, 0x1e, // 30
    0xa2, 0x8, 0x1b, 0x6, 0x48, 0x61, 0x77, 0x61, 0x69, 0x69 // "Hawaii"
]).unwrap();

assert_eq!("Rachel", rachel.name);
assert_eq!(30, rachel.age);
assert_eq!(Some("Hawaii".to_string()), rachel.address);

实现类型

ASN1 red_asn1类型 Rust类型
BOOLEAN 布尔 bool
INTEGER 整数 i128, i64, i32, i16, u32
BIT STRING 比特字符串
OCTET STRING 字节字符串 Vec<u8>
通用字符串 通用字符串 字符串
IA5String IA5String ascii::AsciiString
通用时间 通用时间
SEQUENCE OF 序列 Vec<T: Asn1Object>
SEQUENCE 使用 #[derive(Sequence, Default)] 的结构体
OPTIONAL 可选 Option

依赖

~2.5MB
~39K SLoC