-
Notifications
You must be signed in to change notification settings - Fork 0
/
tlv.go
284 lines (228 loc) · 6.08 KB
/
tlv.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package bertlv
import (
"encoding/hex"
"errors"
"fmt"
"strings"
)
type TLV struct {
Tag string
Value []byte
TLVs []TLV
}
func NewTag(tag string, value []byte) TLV {
return TLV{Tag: tag, Value: value}
}
func NewComposite(tag string, tlvs ...TLV) TLV {
return TLV{Tag: tag, TLVs: tlvs}
}
func Encode(tlvs []TLV) ([]byte, error) {
var encoded []byte
for i := range tlvs {
tag, err := hex.DecodeString(tlvs[i].Tag)
if err != nil {
return nil, fmt.Errorf("encoding tag %s: %w", tlvs[i], err)
}
if err := validateTag(tag); err != nil {
return nil, fmt.Errorf("validating tag %s: %w", tlvs[i].Tag, err)
}
// if it's a composite, encode the TLVs recursively
var value []byte
if len(tlvs[i].TLVs) > 0 {
if !isConstructed(tag) {
return nil, fmt.Errorf("tag %s is not constructed/composite", tlvs[i].Tag)
}
// encode the composite
encodedComposite, err := Encode(tlvs[i].TLVs)
if err != nil {
return nil, fmt.Errorf("encoding composite %s: %w", tlvs[i], err)
}
value = encodedComposite
} else {
value = tlvs[i].Value
}
length := encodeLength(len(value))
encoded = append(encoded, tag...)
encoded = append(encoded, length...)
encoded = append(encoded, value...)
}
return encoded, nil
}
func Decode(data []byte) ([]TLV, error) {
var tlvs []TLV
for len(data) > 0 {
// read the tag
tag, read, err := decodeTag(data)
if err != nil {
return nil, fmt.Errorf("reading tag: %w", err)
}
data = data[read:]
// read the length
length, read, err := decodeLength(data)
if err != nil {
return nil, fmt.Errorf("reading length: %w", err)
}
data = data[read:]
// ensure the value length is within bounds
if len(data) < length {
return nil, fmt.Errorf("insufficient data for expected length %d", length)
}
value := data[:length]
data = data[length:]
// if it's a composite, decode the TLVs recursively
hexTag := strings.ToUpper(hex.EncodeToString(tag))
if isConstructed(tag) {
decoded, err := Decode(value)
if err != nil {
return nil, fmt.Errorf("decoding composite: %w", err)
}
tlvs = append(tlvs, TLV{Tag: hexTag, TLVs: decoded})
} else {
tlvs = append(tlvs, TLV{Tag: hexTag, Value: value})
}
}
return tlvs, nil
}
// PrettyPrint prints the TLVs in a human-readable format.
func PrettyPrint(tlvs []TLV) {
sb := strings.Builder{}
prettyPrint(tlvs, &sb, 0)
fmt.Print(sb.String())
}
func prettyPrint(tlvs []TLV, sb *strings.Builder, level int) {
for _, tlv := range tlvs {
indent := strings.Repeat(" ", level)
tagName, found := emvTags[tlv.Tag]
sb.WriteString(fmt.Sprintf("%s%s", indent, tlv.Tag))
if len(tlv.TLVs) > 0 {
if found {
sb.WriteString(fmt.Sprintf(" - %s\n", tagName))
}
prettyPrint(tlv.TLVs, sb, level+1)
} else {
if filter, ok := tagFilters[tlv.Tag]; ok {
sb.WriteString(fmt.Sprintf(" %s", filter(tlv.Value)))
} else {
sb.WriteString(fmt.Sprintf(" %X", tlv.Value))
}
if found {
sb.WriteString(fmt.Sprintf(" - %s\n", tagName))
}
}
}
}
// Short Form (Length < 128 bytes) - The first byte is the length of the value
// field, and the value field follows immediately.
// Long Form (Length >= 128 bytes) - The first byte is 0x80 plus the number of
// bytes used to encode the length of the value field
func encodeLength(length int) []byte {
if length < 128 {
// short form
return []byte{byte(length)}
}
// long form
var lengthBytes []byte
for length > 0 {
lastByte := byte(length & 0xFF)
lengthBytes = append([]byte{lastByte}, lengthBytes...)
length >>= 8 // discard the last byte
}
return append([]byte{byte(0x80 | len(lengthBytes))}, lengthBytes...)
}
func validateTag(tag []byte) error {
if len(tag) == 0 {
return errors.New("tag cannot be empty")
}
if !isMultiByte(tag) {
if len(tag) > 1 {
return errors.New("invalid tag format: single-byte tag should not have additional bytes")
}
return nil // Single-byte tag is valid
}
// Multi-byte tag
if len(tag) < 2 {
return errors.New("multi-byte tag is incomplete; additional bytes are required")
}
// Check that the last byte has the MSB unset
if tag[len(tag)-1]&0x80 != 0 {
return errors.New("invalid tag format: last byte must not have MSB set")
}
// Check that each byte except the last has the MSB set
for i := 0; i < len(tag)-1; i++ {
if tag[i]&0x80 == 0 {
return fmt.Errorf("invalid tag format: byte %d should have MSB set", i)
}
}
return nil
}
func isMultiByte(tag []byte) bool {
return tag[0]&0x1F == 0x1F
}
// fifth bit should be set to 1 for constructed (composite) tags
func isConstructed(tag []byte) bool {
return tag[0]&0x20 == 0x20
}
func decodeTag(data []byte) ([]byte, int, error) {
if len(data) == 0 {
return nil, 0, errors.New("tag is empty")
}
if !isMultiByte(data) {
// single-byte tag
return data[:1], 1, nil
}
// multi-byte tag
// read until the last byte has the MSB unset
for i := 1; i < len(data); i++ {
if data[i]&0x80 == 0 {
return data[:i+1], i + 1, nil
}
}
return nil, len(data), errors.New("tag is incomplete")
}
func decodeLength(data []byte) (int, int, error) {
if len(data) == 0 {
return 0, 0, errors.New("length is empty")
}
if data[0] < 128 {
// short form
return int(data[0]), 1, nil
}
// long form
lengthBytes := int(data[0] & 0x7F)
if len(data) < lengthBytes+1 {
return 0, 0, errors.New("length is incomplete")
}
length := 0
for i := 1; i <= lengthBytes; i++ {
length = length<<8 | int(data[i])
}
return length, lengthBytes + 1, nil
}
// FindTagByPath returns the TLV with the specified path.
func FindTagByPath(tlvs []TLV, path string) (TLV, bool) {
tag, path, _ := strings.Cut(path, ".")
for _, tlv := range tlvs {
if tlv.Tag == tag {
if path == "" {
return tlv, true
}
if len(tlv.TLVs) > 0 {
return FindTagByPath(tlv.TLVs, path)
}
}
}
return TLV{}, false
}
// FindFirstTag returns the first TLV with the specified tag. It searches
// recursively.
func FindFirstTag(tlvs []TLV, tag string) (TLV, bool) {
for _, tlv := range tlvs {
if tlv.Tag == tag {
return tlv, true
}
if len(tlv.TLVs) > 0 {
return FindFirstTag(tlv.TLVs, tag)
}
}
return TLV{}, false
}