Skip to content
This repository was archived by the owner on Mar 27, 2026. It is now read-only.

Commit fcbcee7

Browse files
author
Ron Frenkel
committed
Implemented reading of the length of a TLV structure,
as described in EMV 4.3 Book 3 Annex B2.
1 parent 40b5b79 commit fcbcee7

2 files changed

Lines changed: 23 additions & 3 deletions

File tree

emv/protocol/data.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,24 @@ def read_tag(data):
5454
return tag, i
5555

5656

57+
def read_length(data):
58+
""" Read length from a list of bytes, starting at the first byte.
59+
Returns the length, plus the number of bytes read from the list.
60+
61+
EMV 4.3 Book 3 Annex B2
62+
"""
63+
i = 0
64+
length = data[i]
65+
i += 1
66+
if length & 0x80:
67+
length_bytes_count = length & 0x7F
68+
length = 0
69+
for j in range(length_bytes_count):
70+
length = (length << 8) + data[i + j]
71+
i += length_bytes_count
72+
return length, i
73+
74+
5775
@total_ordering
5876
class Tag(object):
5977
""" Represents a data tag. Provides ordering and pretty rendering."""

emv/protocol/structures.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from collections import OrderedDict
2-
from .data import ELEMENT_FORMAT, render_element, read_tag, is_constructed, Tag
2+
from .data import ELEMENT_FORMAT, render_element, read_tag, read_length, is_constructed, Tag
33
from .data_elements import Parse, EPC_PRODUCT_ID
44
from ..util import decode_int, bit_set
55
import logging
@@ -45,8 +45,10 @@ def unmarshal(cls, data):
4545
if len(data) <= i:
4646
log.info("Invalid TLV - read beyond end of buffer at %s: %s", tag, data)
4747
return data
48-
length = data[i]
49-
i += 1
48+
49+
length, length_len = read_length(data[i:])
50+
i += length_len
51+
5052
value = data[i : i + length]
5153

5254
if is_constructed(tag[0]):

0 commit comments

Comments
 (0)