57 lines
1.2 KiB
Go
57 lines
1.2 KiB
Go
package asn1
|
|
|
|
import (
|
|
"jasn1/helpers"
|
|
|
|
"errors"
|
|
)
|
|
|
|
func decode(data []byte) (*Tag, uint64, error) {
|
|
if len(data) < 2 {
|
|
return nil, 0, errors.New("Data is not a certificate structure")
|
|
}
|
|
|
|
tag := Tag {
|
|
Kind: TagType(data[0] & 0x1F),
|
|
Constructed: ((data[0] & 0x20) >> 5) != 0,
|
|
Class: TagClass((data[0] & 0xC0) >> 6),
|
|
}
|
|
|
|
length := uint64(data[1])
|
|
long_form := ((data[1] & 0x80) >> 7) != 0
|
|
consumed := uint64(2)
|
|
|
|
if long_form {
|
|
length_bytes := data[1] & 0x7F
|
|
length = helpers.BuildUint64(data[2:2 + length_bytes])
|
|
consumed += uint64(length_bytes)
|
|
}
|
|
|
|
if uint64(len(data[2:])) < length {
|
|
return nil, 0, errors.New("Not enough data for certificate structure")
|
|
}
|
|
|
|
if tag.Constructed {
|
|
dist := uint64(0)
|
|
|
|
for dist < length {
|
|
child, traveled, err := decode(data[consumed + dist:consumed + length])
|
|
|
|
if err != nil {
|
|
return nil, 0, err
|
|
}
|
|
|
|
tag.Children = append(tag.Children, child)
|
|
dist += traveled
|
|
}
|
|
} else {
|
|
tag.Value = data[consumed:consumed + length]
|
|
}
|
|
|
|
return &tag, consumed + length, nil
|
|
}
|
|
|
|
func DecodeByteString(data []byte) (*Tag, error) {
|
|
tag, _, err := decode(data)
|
|
return tag, err
|
|
}
|