如何进行 asn1 marshal/unmarshal 并省略字段?

问题描述 投票:0回答:1
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: Object has zero length.
。为什么
asn1:"-"
不像
json
那样起作用?

go marshalling unmarshalling asn.1
1个回答
0
投票

为什么

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
}

仅编组/解组

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

© www.soinside.com 2019 - 2024. All rights reserved.