Unmarshalling asn failed

WBOY
Release: 2024-02-14 16:27:08
forward
1183 people have browsed it

解组 asn 失败

php editor Xigua is here to share with you a question about "unmarshalling asn failed". In network communications, ASN (Autonomous System Number) is a number used to identify an autonomous system. However, sometimes the ungrouping fails when ungrouping the ASN. This may be caused by incorrect ASN encoding format, corrupted ASN packets, or incompatible parsers. In this article, we will discuss the reasons and solutions for the failure of unmarshalling ASN to help everyone better understand and solve this problem.

Question content

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)
}
Copy after login

I tried to unmarshal but got the following error:

<code>
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
</code>
Copy after login

Can anyone help? Thanks

Solution

0x020105 encodes the integer 5 (see https://www.php.cn/link/8ae7733f9bc11275e8d0a0fdabe5be0a), so it should Unmarshal it to an integer instead of a struct with integer fields:

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
}
Copy after login

and SimpleStruct{Value: 5} is marshalled to 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
}
Copy after login

The above is the detailed content of Unmarshalling asn failed. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template