goasn.1ber

Go unmarshal asn failing


package main

import (
    "encoding/asn1"
    "fmt"
)

type SimpleStruct struct {
    Value int
}

func main() {
    berBytes := []byte{0x02, 0x01, 0x05}

    var simpleStruct SimpleStruct
    _, err := asn1.Unmarshal(berBytes, &simpleStruct)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    fmt.Printf("Decoded value: %d\n", simpleStruct.Value)
}

I was trying to unmarshal but getting below error:

Error: asn1: structure error: tags don't match (16 vs {class:0 tag:2 length:1 isCompound:false}) {optional:false explicit:false application:false private:false defaultValue: tag: stringType:0 timeType:0 set:false omitEmpty:false} SimpleStruct @2

Could someone please help? Thanks


Solution

  • 0x020105 encodes integer 5 (see https://lapo.it/asn1js/#AgEF), so it should be unmarshaled into an integer instead of a struct which has an integer field:

    package main
    
    import (
        "encoding/asn1"
        "fmt"
    )
    
    func main() {
        berBytes := []byte{0x02, 0x01, 0x05}
    
        var v int
        _, err := asn1.Unmarshal(berBytes, &v)
        if err != nil {
            fmt.Println("Error:", err)
            return
        }
    
        fmt.Printf("Decoded value: %d\n", v)
        // Output:
        //   Decoded value: 5
    }
    

    And SimpleStruct{Value: 5} is marshaled into 0x3003020105:

    package main
    
    import (
        "encoding/asn1"
        "fmt"
    )
    
    type SimpleStruct struct {
        Value int
    }
    
    func main() {
        simpleStruct := SimpleStruct{Value: 5}
        buf, err := asn1.Marshal(simpleStruct)
        if err != nil {
            fmt.Println("Error:", err)
            return
        }
    
        fmt.Printf("Encoded value: 0x%x\n", buf)
        // Output:
        //   Encoded value: 0x3003020105
    }