首页 > 文章列表 > 简化 ASN1 的编解码过程中的字段省略方法

简化 ASN1 的编解码过程中的字段省略方法

244 2024-02-03
问题内容

type bearer struct {
    CreatedAt time.Time     `asn1:"generalized"`
    ExpiresAt time.Time     `asn1:"generalized"`
    Nonce     string
    Signature []byte        `asn1:"-"`
    TTL       time.Duration `asn1:"-"`
    Frequency int           `asn1:"-"`
}

c := &bearer{
  CreatedAt: time.Now()
  ExpiresAt: time.Now().Add(1*time.Minute())
  Nonce: "123456789abcdefghijklmnop"
  Frequency: 1
}

b, err := asn1.Marshal(*c)
os.WriteFile("b64.txt", b, 0777)

将成功编组该结构,但是,当使用 Bash 检查该结构时 base64 -d b64.txt > b64.txt.der 我仍然可以看到 asn1:"-" 字段实际上已编组并写入文件,并且没有值的字段得到 Error: 对象长度为零.。为什么 asn1:"-" 不像 json 那样工作?


正确答案


因为 encoding/json 包是为了支持 - 选项而实现的,而encoding/asn1 不是。至于为什么,这里不是地方。接受 encoding/asn1 的主要目标是支持读写 X.509 证书,这并不意味着成为 ASN1 实现的“瑞士军刀”。

如果要排除某些字段,请创建排除这些字段的结构类型。为了避免重复,您可以将这些“剥离”的结构嵌入到您自己的结构中,其中包括附加字段,例如:

type bearerAsn1 struct {
    CreatedAt time.Time `asn1:"generalized"`
    ExpiresAt time.Time `asn1:"generalized"`
    Nonce     string
}

type bearer struct {
    bearerAsn1
    Signature []byte
    TTL       time.Duration
    Frequency int
}

仅marshal/unmarshal bearer.bearerAsn1,所以bearer的其他字段自然会被排除。