How to correctly encode APDU Le field according to Standard ISO_IEC_7816-4-2020

325 views Asked by At

How to correctly encode an extended Le field of an APDU

+------+------+------+------+------+-------------+------+
| CLA  | INS  | P1   | P2   | Lc   | DATA        | Le   |
+------+------+------+------+------+-------------+------+

Specifically regarding following sentence from the ISO_IEC_7816-4-2020 Standard page 9 section 5.2 Syntax:

An extended Le field consists of either three bytes (one byte set to '00' followed by two bytes with any value) if the Lc field is absent, or two bytes (with any value) if an extended Lc field is present.

Question1: If I want to encode a 2 byte Le field, does this mean, that the Lc field also has to be extended? Means, 2 byte Lc?

Question2: If I want to encode a 3 byte Le field, does tths mean, that the Lc field must be absent? Or only, when the Lc field is absent, I have to encode a 3 byte Le field?

enter image description here [Table 1 of ISO_IEC_7816-4-2020 Standard page9]

2

There are 2 answers

2
nvf On

Extended APDU is coded in the following way:

Case 2, extended: CLA INS P1 P2 Le ==> Le must be 3 bytes. Example:

CLA:00 INS:ZZ P1:00 P2:00 Le:00 01 F0

Case 3, extended: CLA INS P1 P2 Lc Data ==> Lc must be 3 bytes. Example:

CLA:00 INS:ZZ P1:00 P2:00 Lc:00 01 F0 Data: XX ... XX (0x1F0 bytes of data)

Case 4, extended: CLA INS P1 P2 Lc Data Le ==> Lc must be 3 bytes and Le must be 2 bytes. Example:

CLA:00 INS:ZZ P1:00 P2:00 Lc:00 01 F0 Data: XX ... XX Le: 02 D0

Question 1: there are two options: both fields are extended or both fields are short. If Lc is present and it's extended, so it must be 3 bytes and le must be 2 bytes.

Question 2: Le is encoded 3 bytes only when Lc is absent.

0
guidot On

Question 1:

I agree with the other answer, an APDU is either extended length (then for both directions) or not.

I suspect a kind of misunderstanding concerning question 2. If the 3-byte-encodiing applies, then the first byte has to be zero. There is no way, you can specify a value greater than 0xFFFF. (This limitation is only theoretical, since cards have still very limited RAM and need lots of it for purposes other than the I/O buffer. So they will report an error for much smaller values.)