48 lines
1 KiB
Go
48 lines
1 KiB
Go
package asn1
|
|
|
|
func build_uint64(data []byte) uint64 {
|
|
val := uint64(0)
|
|
|
|
for idx := 0; idx < len(data) && idx < 8; idx += 1 {
|
|
val = (val << 8) | uint64(data[idx])
|
|
}
|
|
|
|
return val
|
|
}
|
|
|
|
func decode(data []byte) (*Tag, uint64) {
|
|
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 = build_uint64(data[2:2 + length_bytes])
|
|
consumed += uint64(length_bytes)
|
|
}
|
|
|
|
if tag.constructed {
|
|
dist := uint64(0)
|
|
|
|
for dist < length {
|
|
child, traveled := decode(data[consumed + dist:consumed + length])
|
|
tag.children = append(tag.children, child)
|
|
dist += traveled
|
|
}
|
|
} else {
|
|
tag.value = data[consumed:consumed + length]
|
|
}
|
|
|
|
return &tag, consumed + length
|
|
}
|
|
|
|
func DecodeByteString(data []byte) *Tag {
|
|
tag, _ := decode(data)
|
|
return tag
|
|
}
|