php editor Apple introduces you how to perform asn1 marshal/unmarshal and omit fields. When dealing with asn1 encoding, we often need to encode (marshal) or decode (unmarshal) the data, but sometimes we only care about some of the fields without parsing the entire structure. To achieve this goal, we can use some techniques to omit unnecessary fields, thereby improving processing efficiency. Next, we'll detail how to accomplish this.
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)
The structure will be successfully marshaled, however, when inspecting the structure using Bash base64 -d b64.txt > b64.txt.der
I still see asn1:"-"
The fields are actually marshaled and written to the file, and fields with no values get Error: Object length is zero.
. Why doesn't asn1:"-"
work like json
?
Because the encoding/json
package is implemented to support the -
option, and encoding/asn1
No. As for why, this is not the place. The main goal of accepting encoding/asn1
is to support reading and writing X.509 certificates, it is not meant to be a "Swiss Army Knife" of ASN1 implementations.
If you want to exclude certain fields, create a structure type that excludes these fields. To avoid duplication, you can embed these "stripped" structures into your own structures that include additional fields, for example:
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 }
Only marshal/unmarshal bearer.bearerAsn1
, so other fields of bearer
will naturally be excluded.
The above is the detailed content of How to do asn1 marshal/unmarshal and omit fields?. For more information, please follow other related articles on the PHP Chinese website!