Use encoding/asn1 and PEM
Use encoding/asn1 and PEM
ASN.1 describes structured data; DER is a deterministic binary encoding of ASN.1 values. Go supports a subset of DER mappings. PEM wraps binary bytes in a text block with a type label and Base64 data. Neither encoding encrypts or authenticates data. This toy record is not a certificate or key.
package main
import ( "encoding/asn1" "errors" "fmt")
type Record struct { ID int Name string}
func readRecord(b []byte) (Record, error) { var r Record rest, e := asn1.Unmarshal(b, &r) if e != nil { return Record{}, e } if len(rest) != 0 || r.ID < 1 || r.Name == "" { return Record{}, errors.New("invalid record") } return r, nil}func main() { b, e := asn1.Marshal(Record{7, "lab"}) if e != nil { panic(e) } r, e := readRecord(b) fmt.Println(r.ID, r.Name, e == nil) _, e = readRecord(append(b, 0)) fmt.Println(e != nil)}Exported struct fields map to an ASN.1 sequence here; Unmarshal returns bytes not consumed. Reject trailing bytes when the contract expects a single record, and validate semantic fields separately. Note that extra elements inside a SEQUENCE mapped to a struct may be ignored rather than returned in rest; strict schemas require additional validation. Use crypto/x509 for certificates rather than hand-parsing their schema.
Expected output:
7 lab truetrueWrap bytes in PEM
package main
import ( "encoding/pem" "fmt")
func main() { s := pem.EncodeToMemory(&pem.Block{Type: "LAB DATA", Bytes: []byte{1, 2, 3}}) b, rest := pem.Decode(s) if b == nil { panic("missing block") } fmt.Println(b.Type, b.Bytes, len(rest))}PEM Decode finds a block and returns remaining input; nil indicates no block found. Validate the expected label, bounded input and leftover content. Decode can skip leading text, so strict envelopes need additional checks. Never print real private keys; PEM is not encryption.
Expected output:
LAB DATA [1 2 3] 0Try it locally
Marshal a record with ID zero, and verify that readRecord rejects it even though DER encoding succeeds.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Specialized library 04: Use encoding/asn1 and PEM
Check the lesson objective before moving on.
What should a single-record DER parser do with remaining bytes?
What protection does a PEM label provide?