解组失败

问题描述 投票:0回答:1
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)
}

我试图解组但出现以下错误:

错误:asn1:结构错误:标签不匹配(16与{class:0标签:2长度:1 isCompound:false}){可选:false显式:false应用程序:false私有:false默认值:标签:stringType: 0 timeType:0 set:false omitEmpty:false} SimpleStruct @2

有人可以帮忙吗?谢谢

go asn.1 ber
1个回答
0
投票

0x020105
编码整数 5(参见 https://lapo.it/asn1js/#AgEF),因此应将其解组为整数,而不是具有整数字段的结构:

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
}

并且

SimpleStruct{Value: 5}
被编组为
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
}
© www.soinside.com 2019 - 2024. All rights reserved.