Part 4 ended with the bank checking a cryptogram, and I skipped over how the cryptogram got to the bank. Between the card machine and your bank there are usually at least two other companies. Each one opens the message, reads part of it, rewrites a few fields and sends it on.

This post follows the same $25 tap through that trip, as bytes. The code is a working ISO 8583 packer and parser in Python and C#. It builds the authorisation request the terminal sends, passes it through an acquirer and a switch, lets the issuer check the cryptogram with part 4's code, and carries the answer back to the card. You can also give it a message from a test system and it will list the fields and check the ARQC, provided the message uses the same layout. Layouts vary between networks, and I'll come back to that.

The message

Card networks still carry authorisations in ISO 8583. The standard dates from 1987, and nearly every network's message spec is a dialect of it. A message has three parts: a four-digit message type, a bitmap that says which fields are present, and then those fields in number order.

This is the start of the request our terminal sends:

Output
010C                 length of what follows: 268 bytes
30313030             message type "0100", an authorisation request
7038468020C08200     the bitmap
3136 34373631...     field 2: "16", then the 16-digit card number

The bitmap has 64 bits, one for each field, and bit 1 is the top bit of the first byte. 70 is 0111 0000, so fields 2, 3 and 4 are present. Work through all eight bytes and you get fifteen fields: 2, 3, 4, 11, 12, 13, 18, 22, 23, 25, 35, 41, 42, 49 and 55. If bit 1 is set, a second bitmap follows for fields 65 to 128. This message doesn't need one.

Packing is a loop over the fields in number order: set each field's bit and append its bytes.

Python
def pack(mti: str, fields: dict[int, str | bytes]) -> bytes:
    """Build one message: MTI, bitmap, then the fields in number order, behind a 2-byte length."""
    present = sorted(fields)
    bitmap = bytearray(16 if present[-1] > 64 else 8)
    if len(bitmap) == 16:
        bitmap[0] |= 0x80                               # bit 1: a secondary bitmap follows
    body = b""
    for n in present:
        bitmap[(n - 1) // 8] |= 0x80 >> ((n - 1) % 8)   # bit 1 is the top bit of the first byte
        body += pack_field(n, fields[n])
    msg = mti.encode("ascii") + bytes(bitmap) + body
    return len(msg).to_bytes(2, "big") + msg
The same in C#
C#
public static byte[] Pack(string mti, IDictionary<int, object> fields)
{
    var present = fields.Keys.Order().ToArray();
    var bitmap = new byte[present[^1] > 64 ? 16 : 8];
    if (bitmap.Length == 16)
        bitmap[0] |= 0x80;                                 // bit 1: a secondary bitmap follows
    var body = new List<byte>();
    foreach (var n in present)
    {
        bitmap[(n - 1) / 8] |= (byte)(0x80 >> ((n - 1) % 8));   // bit 1 is the top bit of the first byte
        body.AddRange(PackField(n, fields[n]));
    }
    byte[] msg = [.. Encoding.ASCII.GetBytes(mti), .. bitmap, .. body];
    return [(byte)(msg.Length >> 8), (byte)msg.Length, .. msg];
}

In this layout every field except field 55 is ASCII text, and variable-length fields start with two or three ASCII digits giving their length. The layout is a choice, and it's the first thing that changes when you move to another network. Some send numbers as packed BCD. Older mainframe links use EBCDIC. Some send the bitmap as 16 hex characters instead of 8 bytes. Field 4 is the amount almost everywhere, but how the amount is encoded on the wire depends on whose spec you're reading. That's why the parser here only claims to read its own layout.

Where the chip data goes

The terminal doesn't put everything into field 55. Values that existed before chip cards already had fields of their own, and EMV maps the chip's data onto them:

ValueChip tagField
Card number5A2
Transaction type9C3, first two digits
Amount9F024
Date9A13, month and day only
PAN sequence number5F3423
Track 2 equivalent5735
Currency5F2A49
Cryptogram and the data it covers9F26, 9F10, 9F37 and the rest55

Some of these conversions are small but easy to get wrong. Tag 57 separates the card number from the expiry date with a hex D and pads the end with F. Field 35 uses = and has no padding:

Python
track2 = h(self.TRACK2).replace("D", "=").rstrip("F")   # tag 57 uses D and F padding; field 35 uses '='
The same in C#
C#
var track2 = Emv.H(Track2).Replace('D', '=').TrimEnd('F');   // tag 57 uses D and F padding; field 35 uses '='

The amount and the currency travel twice, once in fields 4 and 49 and again inside field 55. Case 4 below is about that.

Field 55

Field 55 holds the chip data as TLV, the same tag-length-value format the card uses. Here it's 125 bytes, preceded by the three ASCII digits 125:

Output
9F26  application cryptogram           2007D63548109602
9F27  cryptogram information data      80
9F10  issuer application data          0FA501A03000000000000000000000000F000000000000000000000000000000
9F37  unpredictable number             8A41C2F0
9F36  application transaction counter  0001
95    terminal verification results    0000008000
9A    transaction date                 261126
9C    transaction type                 00
9F02  amount, authorised               000000002500
5F2A  transaction currency             0840
82    application interchange profile  1980
9F1A  terminal country                 0840
9F03  amount, other                    000000000000
9F33  terminal capabilities            E0F8C8
9F34  CVM results                      1F0302
9F35  terminal type                    22

The first thirteen rows are the cryptogram, the information about it, and the eleven values it covers, so the issuer can rebuild the signed data from field 55 alone. EMV's minimum list for an authorisation request is close to that. The last three rows describe what the terminal can do and what it did about cardholder verification, and networks add requirements of their own on top. The cryptogram information data, 9F27, isn't strictly needed by the issuer, though nearly every terminal sends it.

None of the companies between the terminal and the issuer needs to change field 55, and in a healthy system none of them does. Here is what each hop does change, and what comes back:

A green-bar printout table of fields 2, 4, 7, 11, 32, 37, 38, 39 and 55 across five columns: terminal, acquirer, switch, issuer, and the acquirer on the way back. The acquirer highlights its new values for fields 7, 11, 32 and 37; the switch reads 476173 from field 2; the issuer adds 38, 39 = 00 and field 55 = tag 91; on the way back field 11 returns to 000123 and fields 7 and 32 are struck out. Red pen notes say field 55 is the same 125 bytes at every hop until the issuer answers, and that field 11 must be put back or the terminal ignores its own approval.
What each hop changes, from the walk-through's output. Field 55 doesn't change until the issuer replaces it with its answer.

The acquirer

The merchant's bank gets the message first. In the walk-through it changes four fields and leaves field 55 alone:

Output
acquirer -> switch      changed fields 7, 11, 32, 37; field 55 byte for byte the same

Field 7 is the time the message was sent. Field 11, the system trace audit number or STAN, is the sender's own sequence number, so the acquirer replaces the terminal's with its own. Field 32 identifies the acquirer. Field 37 is the retrieval reference number, which is what support staff ask for when you dispute a charge.

My first version of the acquirer did that and nothing more. The issuer approved the tap, and then the terminal threw the approval away:

Output
terminal                not the answer to this request (MTI 0110, STAN 418207): treat as no response, send a reversal

The terminal matches answers to requests by trace number, and the answer came back with the acquirer's number, 418207, instead of its own 000123. The acquirer has to remember which number it replaced and put it back on the return trip. In production, getting this wrong looks like a timeout. The terminal then sends a reversal for a payment the bank approved, which is the behaviour EMV asks for when a response doesn't arrive.

Python
def forward(self, frame: bytes, mutate=None) -> bytes:
    _, f = unpack(frame)
    self.stan += 1
    self.pending[f"{self.stan:06d}"] = f[11]
    f |= {7: "1126143005", 11: f"{self.stan:06d}", 32: self.ID, 37: f"6330{f[12][:2]}{self.stan:06d}"}
    if mutate:
        mutate(f)
    return pack("0100", f)

def back(self, frame: bytes) -> bytes:
    mti, f = unpack(frame)
    f[11] = self.pending.pop(f[11])                 # the terminal's own trace number again
    for n in (7, 32):                               # ours, not the terminal's business
        f.pop(n, None)
    return pack(mti, f)
The same in C#
C#
public byte[] Forward(byte[] frame, Action<SortedDictionary<int, object>>? mutate = null)
{
    var f = Iso8583.Unpack(frame).Fields;
    stan++;
    pending[stan.ToString("D6")] = f[11];
    f[7] = "1126143005";
    f[11] = stan.ToString("D6");
    f[32] = Id;
    f[37] = $"6330{((string)f[12])[..2]}{stan:D6}";
    mutate?.Invoke(f);
    return Iso8583.Pack("0100", f);
}

public byte[] Back(byte[] frame)
{
    var (mti, f) = Iso8583.Unpack(frame);
    pending.Remove((string)f[11], out var theirs);
    f[11] = theirs!;                                       // the terminal's own trace number again
    f.Remove(7);                                           // ours, not the terminal's business
    f.Remove(32);
    return Iso8583.Pack(mti, f);
}

The mutate hook is only there for the failure cases further down. A real acquirer has no reason to touch the fields it doesn't own.

The switch

The switch, which is the card network or a domestic switch, reads the first six digits of field 2 and picks the issuer. For routing that's all it needs to look at:

Output
switch                  field 2 starts 476173: route to issuer A

A real switch does more than this one. It converts between its own layout and each member's, logs everything, and can step in when an issuer doesn't answer in time. Networks offer issuers a stand-in service that approves or declines within limits the issuer has set, and some of these services can check the cryptogram too, if the issuer has given the network the keys. Field 55 still passes through as it is.

The issuer

The issuer unpacks the message, pulls out field 55, parses the TLV and runs part 4's checks: everything present, a cryptogram method it knows, the card's key rebuilt from the card number and sequence number, the session key from the counter, the MAC compared in constant time, then the counter checked for replay.

I added one check that part 4 couldn't have, because part 4 never had the whole message. The cryptogram covers tag 9F02, the amount inside field 55. The amount the bank actually holds against your account is field 4. Nothing in the cryptography connects the two, so the host has to compare them:

Python
# The cryptogram covers tag 9F02 inside field 55. Field 4, the amount the bank will actually post,
# is outside it. Only this comparison ties the two together.
if self.check_amount and f[4] != h(t["9F02"]):
    return answer("05", f"field 4 is {int(f[4]) / 100:.2f}, the card signed {int(h(t['9F02'])) / 100:.2f}",
                  mac(sk, t["9F26"] + self.DECLINE)[:4] + self.DECLINE)
The same in C#
C#
// The cryptogram covers tag 9F02 inside field 55. Field 4, the amount the bank will actually post,
// is outside it. Only this comparison ties the two together.
if (checkAmount && (string)f[4] != Emv.H(t["9F02"]))
    return Answer("05", $"field 4 is {Money((string)f[4])}, the card signed {Money(Emv.H(t["9F02"]))}",
        [.. Emv.Mac(sk, [.. t["9F26"], .. Decline])[..4], .. Decline]);

For the real tap, both say 25.00 and the cryptogram is the same eight bytes part 4 produced:

Output
issuer                  cryptogram 2007D63548109602 matches; approved for 25.00

The answer

The response is an 0110. It echoes the fields the acquirer needs to match it up, adds an approval code in field 38 and a response code in field 39, and puts the ARPC in field 55 as tag 91. By the time the acquirer has restored the terminal's trace number, this is what arrives at the terminal:

Output
007B30313130703800000EC08200313634373631373339303031303130303130
3030303030303030303030303030323530303030303132333134333030353131
323636333330313434313832303737333139303530305445524D30303432434F
524E455243414645303030313738343030313091081048D28A00820000

The message ends with field 55: its length 010 (ASCII, so 303130), then 91 08 1048D28A 00820000, the same tag 91 as in part 4.

The terminal turns field 39 into tag 8A for the card. It's still two ASCII characters, so "00" becomes 3030. It sends 8A and tag 91 to the card with the second GENERATE AC, and the card checks the ARPC:

Output
terminal                approved, 8A = 3030, tag 91 genuine

Five ways the trip goes wrong

Each case changes one thing at one hop and sends the same tap again:

Output
1. field 55's length counted in hex digits
  issuer                  can't read the message: field 55 (ICC system related data) says 250 bytes, only 125 are left
  terminal                no answer it can use: after the timeout it sends a reversal

2. the message passes through a text step
  issuer                  can't read the message: field 2 (primary account number) should start with 2 length digits, found BFBD
  terminal                no answer it can use: after the timeout it sends a reversal

3. a host drops the tags it doesn't recognise
  issuer                  field 55 has no 9F10, so the cryptogram can't be checked
  terminal                declined (05), 8A = 3035; no tag 91, so no issuer authentication; the card's settings decide the rest

4a. field 4 raised to USD 30.00, issuer checks the cryptogram only
  issuer                  cryptogram 2007D63548109602 matches; approved for 30.00
  terminal                approved, 8A = 3030, tag 91 genuine

4b. the same, issuer also compares field 4 with tag 9F02
  issuer                  field 4 is 30.00, the card signed 25.00
  terminal                declined (05), 8A = 3035, tag 91 genuine

5. field 55 lost on the way back
  issuer                  cryptogram 2007D63548109602 matches; approved for 25.00
  terminal                approved, 8A = 3030; no tag 91, so no issuer authentication; the card's settings decide the rest

1. Length in hex digits. Field 55 is 125 bytes, and a gateway writes its length as 250. It's an easy mistake in code that carries field 55 around as a hex string, because that string really is 250 characters long. My parser refuses because there aren't 250 bytes left. A more forgiving parser would read what's there and carry on, and here it would get away with it, since field 55 happens to be the last field. Put any field after it and that field is lost.

2. A text step. Somewhere in the path the message is held as UTF-8 text and then turned back into bytes. That happens in message queues, JSON logs and string columns in databases. Any byte above 7F that isn't valid UTF-8 comes back as EF BF BD, the replacement character. Look at which field the error blames: field 2, and field 2 is fine. The damage is in the bitmap, whose bytes 80, C0 and 82 each grew to three bytes, so the parser lost its place before it reached field 55. When a parser complains about an early field of a message that was fine at the source, compare the raw bytes on both sides of every hop before you trust the error message.

3. A tag filter. A host keeps only the tags on its own list, and 9F10 isn't on it. Without the issuer application data the issuer can't tell which method the card used, and it can't rebuild the signed data either. This host declines. Another issuer might approve on risk and flag the transaction, but either way it's no longer a chip-verified payment.

4. The amount. This is the case I'd show anyone who builds an issuer host. Someone raises field 4 to $30 and leaves field 55 alone. The cryptogram still matches, because the card signed $25 and field 55 still says $25. An issuer that only checks the cryptogram approves $30, and the ARPC it sends back is genuine, because the ARPC covers the cryptogram and not the amount. The card accepts it. The only thing that catches it is the comparison between field 4 and 9F02. There are legitimate reasons for amounts to differ, such as tips and final amounts that change before clearing, so which differences to allow is the issuer's call. Mine allows none, which would be too strict for a restaurant that adds tips and is about right for a coffee cart.

5. No field 55 on the way back. A hop doesn't map field 55 in responses. The approval still gets through on field 39, and the terminal has no tag 91 to give the card. EMV calls this a downgraded authorisation: the terminal skips issuer authentication and carries on with the response code. After that it's up to the card. Some applications approve and remember that the issuer was never authenticated. Others are personalised to decline when tag 91 doesn't arrive (EMV's Common Payment Application has a setting for this), and then the bank has approved a payment that the till shows as declined. Taps rarely get tag 91 to the card anyway, as parts 1 and 4 explained, so this mostly affects inserted cards. Field 55 in the response also carries issuer scripts, so a hop that drops it drops any PIN unblock the bank sent as well.

If you run one of these hops

  • Treat field 55 as bytes from the moment you read it off the socket until you write it out again. Don't convert it to a string at any point.
  • Log field 55 as hex at the edge of every system you own. When a cryptogram fails, compare your bytes with the terminal's before anyone looks at keys.
  • Give every field you replace back on the return trip, starting with the trace number.
  • On the issuer side, compare field 4 with 9F02 and field 49 with 5F2A, and write down which differences you accept.

For the technical reader

  • Layout used here. A 2-byte big-endian length header that doesn't count itself, then a 4-character ASCII MTI and a binary primary bitmap (secondary when bit 1 is set). Fields are ASCII, with ASCII LL/LLL length prefixes, except field 55: raw bytes with an LLL prefix that counts bytes. That's a common arrangement on TCP links, not a standard one.
  • Field numbers. ISO 8583:1987 numbering. ISO 8583:1987 has no field for chip data. Field 55, ICC system related data (b...255, LLL), comes from ISO 8583:1993, and many 1987-based specs borrowed it. EMV Book 4's informative mapping of tags to fields is where the table above comes from.
  • What has to be in field 55. Book 4 lists the minimum for authorisation requests and responses: AIP, ATC, ARQC, issuer application data, TVR and unpredictable number among the chip-specific elements, plus amount, other amount, country, currency, date and type. It also says the CID doesn't need to be forwarded to the issuer.
  • Response codes. 00 (approved), 05 (do not honour) and 30 (format error) are ISO 8583:1987 values. Networks define more specific codes, including ones for cryptogram failures.
  • Exceptions. With no tag 91 in the response, the terminal skips EXTERNAL AUTHENTICATE and sets "issuer authentication was performed" to 0 in the TSI. With no valid response, it decides offline using the default action codes, and with online data capture it sends a reversal whatever it decides.

What's next

Part 6 is about the other thing that rides back in the response's field 55: issuer scripts, tags 71 and 72. They're how a bank unblocks a PIN, changes a limit or blocks a card through the next authorisation, without the card ever going back to the bank. They're protected by two more keys loaded at personalisation, MK-SMI for integrity and MK-SMC for confidentiality, and part 6 goes through both.

The full scripts

Both scripts do the same thing and print the same output, byte for byte. The Python needs pycryptodome (pip install pycryptodome). The C# is a .NET 10 file-based app: dotnet run Field55.cs.

With no arguments you get the walk-through. To look at a message, pass it as hex with --msg. Add --imk with a test key and the issuer checks the cryptogram too, using the sequence number from field 23. This is the terminal's request from tap 1:

Bash
python field55.py --imk 0123456789ABCDEFFEDCBA9876543210 --msg 010C303130307038468020C08200313634373631373339303031303130303130303030303030303030303030303032353030303030313233313433303035313132363538313430373130303130303336343736313733393030313031303031303D323831323230313030303030303030303030305445524D30303432434F524E45524341464530303031373834303132359F26082007D635481096029F2701809F10200FA501A03000000000000000000000000F0000000000000000000000000000009F37048A41C2F09F36020001950500000080009A032611269C01009F02060000000025005F2A020840820219809F1A0208409F03060000000000009F3303E0F8C89F34031F03029F350122

It reads only this post's layout. For another network's layout, change FIELDS and the two length-prefix lines, and leave the TLV and cryptography code as it is. Use test keys only. A live issuer key belongs in an HSM, never on a command line.

field55.py (Python)
Python
"""Carry one contactless tap from the terminal to the issuer and back as real ISO 8583 messages.

The tap is the USD 25.00 one from part 4: same card, same test key, same ARQC (2007D63548109602).
Here it travels as bytes: the terminal packs an 0100 authorisation request, the acquirer and the switch
pass it on, the issuer unpacks field 55, checks the cryptogram and answers with an 0110 that carries
tag 91 back to the card.

The message layout is one common way to put ISO 8583 on a TCP socket. Every network publishes its own,
and this is the part that changes from one to the next:
  - a 2-byte big-endian length in front of each message (not counted in itself)
  - the message type indicator (MTI) as 4 ASCII digits, e.g. "0100"
  - the bitmap as 8 raw bytes (16 if bit 1 says a second bitmap follows): bit n set = field n present
  - numeric and text fields as ASCII; variable ones led by 2 or 3 ASCII digits giving their length
  - field 55 as raw bytes behind a 3-digit length that counts BYTES (ISO 8583:1993 defines it as b...255)
Field numbers and formats are ISO 8583:1987's, plus field 55 from 1993, mapped the way EMV Book 4 Annex C does.

Two ways to run it (TEST keys only, never a live issuer key):
  python field55.py                                   the walk-through: one tap there and back, then five ways it breaks
  python field55.py --msg HEX [--imk KEY --psn 01]    unpack a message in this layout, list its fields and field 55;
                                                      with --imk, also check the ARQC (common core version 5 cards only)

Needs pycryptodome:  pip install pycryptodome
"""
import argparse
import hmac
import sys

from Crypto.Cipher import DES, DES3


def x(s: str) -> bytes:
    return bytes.fromhex(s.replace(" ", ""))


def h(b: bytes) -> str:
    return b.hex().upper()


# ================================================================ ISO 8583

# field: (name, type, max length, length digits). Length digits 0 = fixed length.
# Types: n = digits, an/ans = text (right-padded with spaces), z = track 2 characters, b = raw bytes.
FIELDS = {
    2: ("primary account number", "n", 19, 2),
    3: ("processing code", "n", 6, 0),                  # first 2 digits = transaction type (tag 9C)
    4: ("amount, transaction", "n", 12, 0),             # minor units: 000000002500 = 25.00
    7: ("transmission date and time", "n", 10, 0),      # MMDDhhmmss, set by whoever sends the message
    11: ("system trace audit number", "n", 6, 0),       # the sender's own sequence number (STAN)
    12: ("time, local transaction", "n", 6, 0),         # hhmmss
    13: ("date, local transaction", "n", 4, 0),         # MMDD
    18: ("merchant type", "n", 4, 0),                   # merchant category code
    22: ("POS entry mode", "n", 3, 0),                  # 07x = contactless chip, as the card networks use it
    23: ("card sequence number", "n", 3, 0),            # tag 5F34, the PAN sequence number
    25: ("POS condition code", "n", 2, 0),
    32: ("acquiring institution ID", "n", 11, 2),
    35: ("track 2 data", "z", 37, 2),                   # from tag 57, with '=' as the separator
    37: ("retrieval reference number", "an", 12, 0),
    38: ("authorisation ID response", "an", 6, 0),      # the approval code on your receipt
    39: ("response code", "an", 2, 0),                  # 00 = approved
    41: ("card acceptor terminal ID", "ans", 8, 0),
    42: ("card acceptor ID", "ans", 15, 0),
    49: ("currency code, transaction", "n", 3, 0),      # tag 5F2A without its leading zero: 840 = US dollar
    55: ("ICC system related data", "b", 255, 3),       # the chip's TLV data, untouched
}


def pack(mti: str, fields: dict[int, str | bytes]) -> bytes:
    """Build one message: MTI, bitmap, then the fields in number order, behind a 2-byte length."""
    present = sorted(fields)
    bitmap = bytearray(16 if present[-1] > 64 else 8)
    if len(bitmap) == 16:
        bitmap[0] |= 0x80                               # bit 1: a secondary bitmap follows
    body = b""
    for n in present:
        bitmap[(n - 1) // 8] |= 0x80 >> ((n - 1) % 8)   # bit 1 is the top bit of the first byte
        body += pack_field(n, fields[n])
    msg = mti.encode("ascii") + bytes(bitmap) + body
    return len(msg).to_bytes(2, "big") + msg


def pack_field(n: int, value: str | bytes) -> bytes:
    name, kind, size, digits = FIELDS[n]
    raw = value if kind == "b" else value.encode("ascii")
    if kind == "n" and not value.isdigit():
        raise ValueError(f"field {n} ({name}) must be digits, got {value!r}")
    if digits == 0:                                     # fixed length
        if kind in ("an", "ans"):
            raw = raw.ljust(size, b" ")
        if len(raw) != size:
            raise ValueError(f"field {n} ({name}) is fixed at {size}, got {len(raw)}")
        return raw
    if len(raw) > size:
        raise ValueError(f"field {n} ({name}) allows {size}, got {len(raw)}")
    return str(len(raw)).zfill(digits).encode("ascii") + raw   # the length counts bytes, never hex digits


def unpack(frame: bytes) -> tuple[str, dict[int, str | bytes]]:
    """Read one message back. Raises ValueError with the field number when the bytes don't add up."""
    if int.from_bytes(frame[:2], "big") != len(frame) - 2:
        raise ValueError(f"length header says {int.from_bytes(frame[:2], 'big')}, message is {len(frame) - 2} bytes")
    msg, mti = frame[2:], frame[2:6].decode("ascii")
    bitmap_len = 16 if msg[4] & 0x80 else 8
    bitmap, i, fields = msg[4:4 + bitmap_len], 4 + bitmap_len, {}
    for n in range(2, bitmap_len * 8 + 1):
        if not bitmap[(n - 1) // 8] & (0x80 >> ((n - 1) % 8)):
            continue
        if n not in FIELDS:
            raise ValueError(f"bitmap has field {n}, which this layout doesn't define")
        name, kind, size, digits = FIELDS[n]
        length = size
        if digits:
            prefix = msg[i:i + digits]
            if not prefix.isdigit():
                raise ValueError(f"field {n} ({name}) should start with {digits} length digits, found {h(prefix)}")
            length = int(prefix)
            i += digits
            if length > size:
                raise ValueError(f"field {n} ({name}) says {length}, the most it allows is {size}")
        if i + length > len(msg):
            raise ValueError(f"field {n} ({name}) says {length} bytes, only {len(msg) - i} are left")
        raw = msg[i:i + length]
        i += length
        if kind != "b" and not raw.isascii():
            raise ValueError(f"field {n} ({name}) should be text, found {h(raw)}")
        if kind == "n" and not raw.isdigit():
            raise ValueError(f"field {n} ({name}) should be digits, found {h(raw)}")
        fields[n] = raw if kind == "b" else raw.decode("ascii").rstrip(" ") if kind in ("an", "ans") else raw.decode("ascii")
    if i != len(msg):
        raise ValueError(f"{len(msg) - i} bytes left over after the last field")
    return mti, fields


# ================================================================ TLV (EMV Book 3, Annex B)

def tlv(tag: str, value: bytes) -> bytes:
    n = len(value)
    length = bytes([n]) if n < 0x80 else b"\x81" + bytes([n]) if n < 0x100 else b"\x82" + n.to_bytes(2, "big")
    return x(tag) + length + value


def parse_tlv(data: bytes) -> dict[str, bytes]:
    out, i = {}, 0
    while i < len(data):
        if data[i] in (0x00, 0xFF):                     # padding between objects
            i += 1
            continue
        start = i
        i += 1
        if data[start] & 0x1F == 0x1F:                  # low 5 bits set: the tag goes on
            while i < len(data) and data[i] & 0x80:
                i += 1
            i += 1
        if i >= len(data):
            raise ValueError(f"field 55 ends inside tag {h(data[start:i])}")
        tag, n = h(data[start:i]), data[i]
        i += 1
        if n & 0x80:                                    # long form: 81 xx or 82 xx xx
            k = n & 0x7F
            n = int.from_bytes(data[i:i + k], "big")
            i += k
        if i + n > len(data):
            raise ValueError(f"tag {tag} says {n} bytes, only {len(data) - i} are left")
        out[tag] = data[i:i + n]
        i += n
    return out


NAMES = {
    "9F26": "application cryptogram", "9F27": "cryptogram information data", "9F10": "issuer application data",
    "9F37": "unpredictable number", "9F36": "application transaction counter", "95": "terminal verification results",
    "9A": "transaction date", "9C": "transaction type", "9F02": "amount, authorised", "5F2A": "transaction currency",
    "82": "application interchange profile", "9F1A": "terminal country", "9F03": "amount, other",
    "9F33": "terminal capabilities", "9F34": "CVM results", "9F35": "terminal type", "84": "dedicated file name (AID)",
    "91": "issuer authentication data", "71": "issuer script template 1", "72": "issuer script template 2",
}


# ================================================================ the cryptography from part 4 (EMV Book 2, Annex A1)

def odd_parity(key: bytes) -> bytes:
    return bytes(b & 0xFE | (bin(b >> 1).count("1") + 1) % 2 for b in key)


def card_master_key(imk: bytes, pan: str, psn: str) -> bytes:
    y = x((pan + psn)[-16:].rjust(16, "0"))
    tdes = DES3.new(imk, DES3.MODE_ECB)
    return odd_parity(tdes.encrypt(y) + tdes.encrypt(bytes(b ^ 0xFF for b in y)))


def session_key(mk: bytes, atc: bytes) -> bytes:
    tdes = DES3.new(mk, DES3.MODE_ECB)
    return tdes.encrypt(atc + b"\xF0" + bytes(5)) + tdes.encrypt(atc + b"\x0F" + bytes(5))


def mac(key: bytes, msg: bytes) -> bytes:
    msg += b"\x80" + bytes(-(len(msg) + 1) % 8)
    left, right = DES.new(key[:8], DES.MODE_ECB), DES.new(key[8:], DES.MODE_ECB)
    block = bytes(8)
    for i in range(0, len(msg), 8):
        block = left.encrypt(bytes(a ^ b for a, b in zip(msg[i:i + 8], block)))
    return left.encrypt(right.decrypt(block))


SIGNED = ["9F02", "9F03", "9F1A", "95", "5F2A", "9A", "9C", "9F37", "82", "9F36", "9F10"]   # Table CCD 3 order


# ================================================================ the four parties

class Card:
    """Part 4's card, cut down to what this post needs: answer GENERATE AC, then check tag 91."""

    def __init__(self, mk: bytes):
        self.mk, self.atc, self.sk, self.arqc = mk, 0, b"", b""

    def generate_ac(self, t: dict[str, bytes]) -> dict[str, bytes]:
        self.atc += 1
        atc = self.atc.to_bytes(2, "big")
        self.sk = session_key(self.mk, atc)
        iad = x("0F A5 01 A030000000") + bytes(8) + x("0F") + bytes(15)   # common core format A, version 5
        t = dict(t, **{"82": x("1980"), "9F36": atc, "9F10": iad})
        self.arqc = mac(self.sk, b"".join(t[tag] for tag in SIGNED))
        return {"9F27": x("80"), "9F36": atc, "9F26": self.arqc, "9F10": iad, "82": t["82"]}

    def issuer_authentication(self, tag91: bytes) -> bool:
        return hmac.compare_digest(mac(self.sk, self.arqc + tag91[4:8])[:4], tag91[:4])


class Terminal:
    TID, MID, MCC = "TERM0042", "CORNERCAFE00017", "5814"
    PAN, PSN = "4761739001010010", "01"
    TRACK2 = x("4761739001010010D2812201000000000000")   # tag 57: PAN, 'D', expiry YYMM, service code, the rest
    stan = 122

    def request(self, amount_cents: int, un: str, card: Card, when=("1126", "143005")) -> tuple[bytes, dict]:
        mmdd, hhmmss = when
        t = {"9F02": x(f"{amount_cents:012d}"), "9F03": bytes(6), "9F1A": x("0840"), "95": x("0000008000"),
             "5F2A": x("0840"), "9A": x("26" + mmdd), "9C": x("00"), "9F37": x(un)}
        t |= card.generate_ac(t)
        t |= {"9F33": x("E0F8C8"), "9F34": x("1F0302"), "9F35": x("22")}
        # Field 55: the tags Book 4 says an authorisation request needs, as TLV, in the order this terminal likes.
        f55 = b"".join(tlv(tag, t[tag]) for tag in ["9F26", "9F27", "9F10", "9F37", "9F36", "95", "9A", "9C",
                                                    "9F02", "5F2A", "82", "9F1A", "9F03", "9F33", "9F34", "9F35"])
        Terminal.stan += 1
        track2 = h(self.TRACK2).replace("D", "=").rstrip("F")   # tag 57 uses D and F padding; field 35 uses '='
        fields = {2: self.PAN, 3: "000000", 4: f"{amount_cents:012d}", 11: f"{Terminal.stan:06d}", 12: hhmmss,
                  13: mmdd, 18: self.MCC, 22: "071", 23: self.PSN.zfill(3), 25: "00", 35: track2,
                  41: self.TID, 42: self.MID, 49: "840", 55: f55}
        return pack("0100", fields), fields

    @staticmethod
    def response(frame: bytes, sent: dict, card: Card) -> str:
        mti, f = unpack(frame)
        if mti != "0110" or f[11] != sent[11] or f[41] != sent[41]:
            return f"not the answer to this request (MTI {mti}, STAN {f.get(11)}): treat as no response, send a reversal"
        decision = "approved" if f[39] == "00" else f"declined ({f[39]})"
        # Field 39 becomes tag 8A, two ASCII characters, for the second GENERATE AC: "00" is 3030.
        arc = h(f[39].encode("ascii"))
        if 55 not in f or "91" not in parse_tlv(f[55]):
            return f"{decision}, 8A = {arc}; no tag 91, so no issuer authentication; the card's settings decide the rest"
        ok = card.issuer_authentication(parse_tlv(f[55])["91"])
        return f"{decision}, 8A = {arc}, tag 91 {'genuine' if ok else 'FORGED'}"


class Acquirer:
    """The merchant's bank: swaps in its own trace number, adds its ID and a reference, forwards the rest.
    On the way back it has to undo the swap, or the terminal won't recognise its own answer."""
    ID = "412345"

    def __init__(self):
        self.stan, self.pending = 418206, {}            # our STAN -> the terminal's STAN

    def forward(self, frame: bytes, mutate=None) -> bytes:
        _, f = unpack(frame)
        self.stan += 1
        self.pending[f"{self.stan:06d}"] = f[11]
        f |= {7: "1126143005", 11: f"{self.stan:06d}", 32: self.ID, 37: f"6330{f[12][:2]}{self.stan:06d}"}
        if mutate:
            mutate(f)
        return pack("0100", f)

    def back(self, frame: bytes) -> bytes:
        mti, f = unpack(frame)
        f[11] = self.pending.pop(f[11])                 # the terminal's own trace number again
        for n in (7, 32):                               # ours, not the terminal's business
            f.pop(n, None)
        return pack(mti, f)


class Switch:
    """Routes on the first digits of the card number. It reads field 2 and nothing else."""
    ROUTES = {"476173": "issuer A"}

    def route(self, frame: bytes) -> str:
        _, f = unpack(frame)
        return self.ROUTES.get(f[2][:6], "no route")


class Issuer:
    APPROVE, DECLINE = x("00820000"), x("00000000")     # card status update: approved / declined

    def __init__(self, imk: bytes, cards: dict[str, str], check_amount=True):
        self.imk, self.cards, self.check_amount = imk, cards, check_amount
        self.last_atc: dict[str, int] = {}

    def authorise(self, frame: bytes) -> tuple[bytes, str]:
        try:
            mti, f = unpack(frame)
        except ValueError as e:
            return b"", f"can't read the message: {e}"   # no answer: it can't even tell who to send one to
        out = {n: f[n] for n in (2, 3, 4, 7, 11, 12, 13, 32, 37, 41, 42, 49) if n in f}

        def answer(code: str, why: str, tag91: bytes = b"") -> tuple[bytes, str]:
            if code == "00":
                out[38] = "731905"
            out[39] = code
            if tag91:
                out[55] = tlv("91", tag91)
            return pack("0110", out), why

        if 55 not in f:
            return answer("05", "no field 55, so nothing to check the card with")
        try:
            t = parse_tlv(f[55])
        except ValueError as e:
            return answer("30", f"field 55 doesn't parse: {e}")   # 30 = format error
        missing = [tag for tag in SIGNED + ["9F26", "9F27"] if tag not in t]
        if missing:
            return answer("05", "field 55 has no " + " ".join(missing) + ", so the cryptogram can't be checked")
        if t["9F10"][:2] != x("0FA5"):
            return answer("05", f"issuer application data {h(t['9F10'][:2])}: not a method this host checks")
        pan = f[2]
        sk = session_key(card_master_key(self.imk, pan, self.cards[pan]), t["9F36"])
        expected = mac(sk, b"".join(t[tag] for tag in SIGNED))
        if not hmac.compare_digest(expected, t["9F26"]):
            return answer("05", f"cryptogram {h(t['9F26'])} doesn't match {h(expected)}")
        # The cryptogram covers tag 9F02 inside field 55. Field 4, the amount the bank will actually post,
        # is outside it. Only this comparison ties the two together.
        if self.check_amount and f[4] != h(t["9F02"]):
            return answer("05", f"field 4 is {int(f[4]) / 100:.2f}, the card signed {int(h(t['9F02'])) / 100:.2f}",
                          mac(sk, t["9F26"] + self.DECLINE)[:4] + self.DECLINE)
        atc = int.from_bytes(t["9F36"], "big")
        if atc <= self.last_atc.get(pan, 0):
            return answer("05", f"counter {atc:04X} already used", mac(sk, t["9F26"] + self.DECLINE)[:4] + self.DECLINE)
        self.last_atc[pan] = atc
        return answer("00", f"cryptogram {h(expected)} matches; approved for {int(f[4]) / 100:.2f}",
                      mac(sk, t["9F26"] + self.APPROVE)[:4] + self.APPROVE)


# ================================================================ printing

def show(frame: bytes, indent="    ") -> None:
    mti, f = unpack(frame)
    print(f"{indent}{len(frame)} bytes on the wire, MTI {mti}, bitmap {h(frame[6:14])}")
    for n, v in f.items():
        shown = f"{len(v)} bytes" if isinstance(v, bytes) else v
        print(f"{indent}  {n:>3}  {FIELDS[n][0]:<30} {shown}")
        if n == 55:
            for tag, val in parse_tlv(v).items():
                print(f"{indent}         {tag:<5}{NAMES.get(tag, ''):<33}{h(val)}")


def hexdump(frame: bytes, indent="    ") -> None:
    for i in range(0, len(frame), 32):
        print(f"{indent}{h(frame[i:i + 32])}")


# ================================================================ the walk-through

IMK = x("0123456789ABCDEF FEDCBA9876543210")           # a well-known TEST key: never use it for real cards


def run(title: str, amount=2500, un="8A41C2F0", acquirer_edit=None, on_wire=None, response_edit=None,
        issuer=None, verbose=False) -> None:
    card = Card(card_master_key(IMK, Terminal.PAN, Terminal.PSN))
    issuer = issuer or Issuer(IMK, {Terminal.PAN: Terminal.PSN})
    acquirer = Acquirer()
    print(f"\n{title}")
    req, sent = Terminal().request(amount, un, card)
    if verbose:
        print("  terminal -> acquirer, as bytes")
        hexdump(req)
        print("  the same, field by field")
        show(req)
    fwd = acquirer.forward(req, acquirer_edit)
    if on_wire:
        fwd = on_wire(fwd)
    if verbose:
        a, b = unpack(req)[1], unpack(fwd)[1]
        changed = [n for n in sorted(set(a) | set(b)) if a.get(n) != b.get(n)]
        print(f"  acquirer -> switch      changed fields {', '.join(map(str, changed))}; "
              f"field 55 {'byte for byte the same' if a[55] == b[55] else 'CHANGED'}")
        print(f"  switch                  field 2 starts {b[2][:6]}: route to {Switch().route(fwd)}")
    resp, why = issuer.authorise(fwd)
    print(f"  issuer                  {why}")
    if not resp:
        print("  terminal                no answer it can use: after the timeout it sends a reversal")
        return
    if response_edit:
        resp = response_edit(resp)
    resp = acquirer.back(resp)
    if verbose:
        print("  acquirer -> terminal, field by field")
        show(resp)
        print("  the same, as bytes")
        hexdump(resp)
    print(f"  terminal                {Terminal.response(resp, sent, card)}")


def walk_through() -> None:
    run("Tap 1: USD 25.00, there and back", verbose=True)

    print("\nWhat goes wrong")

    def hex_length(frame: bytes) -> bytes:
        # A gateway that writes field 55's length as the number of hex DIGITS: twice the real number.
        _, f = unpack(frame)
        body = frame[2:-len(f[55]) - 3] + str(2 * len(f[55])).zfill(3).encode() + f[55]
        return len(body).to_bytes(2, "big") + body
    run("1. field 55's length counted in hex digits", on_wire=hex_length)

    def through_text(frame: bytes) -> bytes:
        # A queue or logger that holds the message as UTF-8 text, then turns it back into bytes and
        # frames it again. Anything above 7F that isn't valid UTF-8 comes back as EF BF BD.
        body = frame[2:].decode("utf-8", errors="replace").encode("utf-8")
        return len(body).to_bytes(2, "big") + body
    run("2. the message passes through a text step", on_wire=through_text)

    def tidy(f: dict) -> None:
        # A host that keeps only the tags on its own list. 9F10 isn't on it.
        keep = ["9F26", "9F27", "9F37", "9F36", "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03"]
        t = parse_tlv(f[55])
        f[55] = b"".join(tlv(tag, t[tag]) for tag in keep if tag in t)
    run("3. a host drops the tags it doesn't recognise", acquirer_edit=tidy)

    def bigger(f: dict) -> None:
        f[4] = "000000003000"                            # USD 30.00 in field 4; field 55 still says 25.00
    run("4a. field 4 raised to USD 30.00, issuer checks the cryptogram only", acquirer_edit=bigger,
        issuer=Issuer(IMK, {Terminal.PAN: Terminal.PSN}, check_amount=False))
    run("4b. the same, issuer also compares field 4 with tag 9F02", acquirer_edit=bigger)

    def no_55(frame: bytes) -> bytes:
        # A switch that doesn't map field 55 on the way back.
        mti, f = unpack(frame)
        f.pop(55, None)
        return pack(mti, f)
    run("5. field 55 lost on the way back", response_edit=no_55)


def inspect(args) -> int:
    frame = x(args.msg)
    if int.from_bytes(frame[:2], "big") != len(frame) - 2:
        frame = len(frame).to_bytes(2, "big") + frame    # no length header given: add one
    show(frame, "")
    _, f = unpack(frame)
    if args.imk:
        resp, why = Issuer(x(args.imk), {f[2]: args.psn or f.get(23, "000")[-2:]}).authorise(frame)
        print(f"\nissuer check: {why}")
        if resp:
            print(f"answer: {h(resp)}")
        return 0 if resp and unpack(resp)[1][39] == "00" else 1
    return 0


if __name__ == "__main__":
    if len(sys.argv) == 1:
        walk_through()
    else:
        p = argparse.ArgumentParser(description="Unpack an ISO 8583 message in this script's layout and check its ARQC.")
        p.add_argument("--msg", required=True, help="the message as hex, with or without the 2-byte length header")
        p.add_argument("--imk", help="issuer master key for cryptograms, 32 hex (TEST keys only)")
        p.add_argument("--psn", help="PAN sequence number, 2 digits (default: from field 23)")
        sys.exit(inspect(p.parse_args()))
Field55.cs (C#)
C#
// Carry one contactless tap from the terminal to the issuer and back as real ISO 8583 messages.
//
// The tap is the USD 25.00 one from part 4: same card, same test key, same ARQC (2007D63548109602).
// Here it travels as bytes: the terminal packs an 0100 authorisation request, the acquirer and the switch
// pass it on, the issuer unpacks field 55, checks the cryptogram and answers with an 0110 that carries
// tag 91 back to the card.
//
// The message layout is one common way to put ISO 8583 on a TCP socket. Every network publishes its own,
// and this is the part that changes from one to the next:
//   - a 2-byte big-endian length in front of each message (not counted in itself)
//   - the message type indicator (MTI) as 4 ASCII digits, e.g. "0100"
//   - the bitmap as 8 raw bytes (16 if bit 1 says a second bitmap follows): bit n set = field n present
//   - numeric and text fields as ASCII; variable ones led by 2 or 3 ASCII digits giving their length
//   - field 55 as raw bytes behind a 3-digit length that counts BYTES (ISO 8583:1993 defines it as b...255)
// Field numbers and formats are ISO 8583:1987's, plus field 55 from 1993, mapped the way EMV Book 4 Annex C does.
//
// Two ways to run it (.NET 10, TEST keys only, never a live issuer key):
//   dotnet run Field55.cs                                         the walk-through: one tap there and back, then five ways it breaks
//   dotnet run Field55.cs -- --msg HEX [--imk KEY --psn 01]       unpack a message in this layout, list its fields and field 55;
//                                                                 with --imk, also check the ARQC (common core version 5 cards only)
using System.Globalization;
using System.Security.Cryptography;
using System.Text;

if (args.Length == 0)
{
    WalkThrough();
    return 0;
}
return Inspect(args);

static void WalkThrough()
{
    Run("Tap 1: USD 25.00, there and back", verbose: true);

    Console.WriteLine("\nWhat goes wrong");

    // A gateway that writes field 55's length as the number of hex DIGITS: twice the real number.
    static byte[] HexLength(byte[] frame)
    {
        var f55 = (byte[])Iso8583.Unpack(frame).Fields[55];
        byte[] body = [.. frame[2..^(f55.Length + 3)], .. Encoding.ASCII.GetBytes((2 * f55.Length).ToString("D3")), .. f55];
        return [(byte)(body.Length >> 8), (byte)body.Length, .. body];
    }
    Run("1. field 55's length counted in hex digits", onWire: HexLength);

    // A queue or logger that holds the message as UTF-8 text, then turns it back into bytes and
    // frames it again. Anything above 7F that isn't valid UTF-8 comes back as EF BF BD.
    static byte[] ThroughText(byte[] frame)
    {
        var body = Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(frame, 2, frame.Length - 2));
        return [(byte)(body.Length >> 8), (byte)body.Length, .. body];
    }
    Run("2. the message passes through a text step", onWire: ThroughText);

    // A host that keeps only the tags on its own list. 9F10 isn't on it.
    static void Tidy(SortedDictionary<int, object> f)
    {
        string[] keep = ["9F26", "9F27", "9F37", "9F36", "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03"];
        var t = Tlv.Parse((byte[])f[55]);
        f[55] = keep.Where(t.ContainsKey).SelectMany(tag => Tlv.Build(tag, t[tag])).ToArray();
    }
    Run("3. a host drops the tags it doesn't recognise", acquirerEdit: Tidy);

    static void Bigger(SortedDictionary<int, object> f) => f[4] = "000000003000";   // USD 30.00 in field 4; field 55 still says 25.00
    Run("4a. field 4 raised to USD 30.00, issuer checks the cryptogram only", acquirerEdit: Bigger,
        issuer: new Issuer(Emv.Imk, new() { [Terminal.Pan] = Terminal.Psn }, checkAmount: false));
    Run("4b. the same, issuer also compares field 4 with tag 9F02", acquirerEdit: Bigger);

    // A switch that doesn't map field 55 on the way back.
    static byte[] No55(byte[] frame)
    {
        var (mti, f) = Iso8583.Unpack(frame);
        f.Remove(55);
        return Iso8583.Pack(mti, f);
    }
    Run("5. field 55 lost on the way back", responseEdit: No55);
}

static void Run(string title, int amount = 2500, string un = "8A41C2F0", Action<SortedDictionary<int, object>>? acquirerEdit = null,
    Func<byte[], byte[]>? onWire = null, Func<byte[], byte[]>? responseEdit = null, Issuer? issuer = null, bool verbose = false)
{
    var card = new Card(Emv.CardMasterKey(Emv.Imk, Terminal.Pan, Terminal.Psn));
    issuer ??= new Issuer(Emv.Imk, new() { [Terminal.Pan] = Terminal.Psn });
    var acquirer = new Acquirer();
    Console.WriteLine($"\n{title}");
    var (req, sent) = new Terminal().Request(amount, un, card);
    if (verbose)
    {
        Console.WriteLine("  terminal -> acquirer, as bytes");
        Print.HexDump(req);
        Console.WriteLine("  the same, field by field");
        Print.Show(req);
    }
    var fwd = acquirer.Forward(req, acquirerEdit);
    if (onWire != null)
        fwd = onWire(fwd);
    if (verbose)
    {
        var a = Iso8583.Unpack(req).Fields;
        var b = Iso8583.Unpack(fwd).Fields;
        var changed = a.Keys.Union(b.Keys).Order().Where(n => !Iso8583.Same(a.GetValueOrDefault(n), b.GetValueOrDefault(n)));
        Console.WriteLine($"  acquirer -> switch      changed fields {string.Join(", ", changed)}; " +
                          $"field 55 {(Iso8583.Same(a[55], b[55]) ? "byte for byte the same" : "CHANGED")}");
        Console.WriteLine($"  switch                  field 2 starts {((string)b[2])[..6]}: route to {new Switch().Route(fwd)}");
    }
    var (resp, why) = issuer.Authorise(fwd);
    Console.WriteLine($"  issuer                  {why}");
    if (resp.Length == 0)
    {
        Console.WriteLine("  terminal                no answer it can use: after the timeout it sends a reversal");
        return;
    }
    if (responseEdit != null)
        resp = responseEdit(resp);
    resp = acquirer.Back(resp);
    if (verbose)
    {
        Console.WriteLine("  acquirer -> terminal, field by field");
        Print.Show(resp);
        Console.WriteLine("  the same, as bytes");
        Print.HexDump(resp);
    }
    Console.WriteLine($"  terminal                {Terminal.Response(resp, sent, card)}");
}

static int Inspect(string[] a)
{
    string? Arg(string name) => Array.IndexOf(a, name) is var i and >= 0 && i + 1 < a.Length ? a[i + 1] : null;
    var frame = Emv.X(Arg("--msg") ?? throw new ArgumentException("--msg is required"));
    if ((frame[0] << 8 | frame[1]) != frame.Length - 2)
        frame = [(byte)(frame.Length >> 8), (byte)frame.Length, .. frame];   // no length header given: add one
    Print.Show(frame, "");
    var f = Iso8583.Unpack(frame).Fields;
    if (Arg("--imk") is not { } imk)
        return 0;
    var psn = Arg("--psn") ?? (f.TryGetValue(23, out var csn) ? (string)csn : "000")[^2..];
    var (resp, why) = new Issuer(Emv.X(imk), new() { [(string)f[2]] = psn }).Authorise(frame);
    Console.WriteLine($"\nissuer check: {why}");
    if (resp.Length > 0)
        Console.WriteLine($"answer: {Emv.H(resp)}");
    return resp.Length > 0 && (string)Iso8583.Unpack(resp).Fields[39] == "00" ? 0 : 1;
}

// ================================================================ ISO 8583

static class Iso8583
{
    // field: (name, type, max length, length digits). Length digits 0 = fixed length.
    // Types: n = digits, an/ans = text (right-padded with spaces), z = track 2 characters, b = raw bytes.
    public static readonly Dictionary<int, (string Name, string Kind, int Size, int Digits)> Fields = new()
    {
        [2] = ("primary account number", "n", 19, 2),
        [3] = ("processing code", "n", 6, 0),                  // first 2 digits = transaction type (tag 9C)
        [4] = ("amount, transaction", "n", 12, 0),             // minor units: 000000002500 = 25.00
        [7] = ("transmission date and time", "n", 10, 0),      // MMDDhhmmss, set by whoever sends the message
        [11] = ("system trace audit number", "n", 6, 0),       // the sender's own sequence number (STAN)
        [12] = ("time, local transaction", "n", 6, 0),         // hhmmss
        [13] = ("date, local transaction", "n", 4, 0),         // MMDD
        [18] = ("merchant type", "n", 4, 0),                   // merchant category code
        [22] = ("POS entry mode", "n", 3, 0),                  // 07x = contactless chip, as the card networks use it
        [23] = ("card sequence number", "n", 3, 0),            // tag 5F34, the PAN sequence number
        [25] = ("POS condition code", "n", 2, 0),
        [32] = ("acquiring institution ID", "n", 11, 2),
        [35] = ("track 2 data", "z", 37, 2),                   // from tag 57, with '=' as the separator
        [37] = ("retrieval reference number", "an", 12, 0),
        [38] = ("authorisation ID response", "an", 6, 0),      // the approval code on your receipt
        [39] = ("response code", "an", 2, 0),                  // 00 = approved
        [41] = ("card acceptor terminal ID", "ans", 8, 0),
        [42] = ("card acceptor ID", "ans", 15, 0),
        [49] = ("currency code, transaction", "n", 3, 0),      // tag 5F2A without its leading zero: 840 = US dollar
        [55] = ("ICC system related data", "b", 255, 3),       // the chip's TLV data, untouched
    };

    // Build one message: MTI, bitmap, then the fields in number order, behind a 2-byte length.
    public static byte[] Pack(string mti, IDictionary<int, object> fields)
    {
        var present = fields.Keys.Order().ToArray();
        var bitmap = new byte[present[^1] > 64 ? 16 : 8];
        if (bitmap.Length == 16)
            bitmap[0] |= 0x80;                                 // bit 1: a secondary bitmap follows
        var body = new List<byte>();
        foreach (var n in present)
        {
            bitmap[(n - 1) / 8] |= (byte)(0x80 >> ((n - 1) % 8));   // bit 1 is the top bit of the first byte
            body.AddRange(PackField(n, fields[n]));
        }
        byte[] msg = [.. Encoding.ASCII.GetBytes(mti), .. bitmap, .. body];
        return [(byte)(msg.Length >> 8), (byte)msg.Length, .. msg];
    }

    static byte[] PackField(int n, object value)
    {
        var (name, kind, size, digits) = Fields[n];
        var raw = kind == "b" ? (byte[])value : Encoding.ASCII.GetBytes((string)value);
        if (kind == "n" && !(((string)value).Length > 0 && ((string)value).All(char.IsAsciiDigit)))
            throw new ArgumentException($"field {n} ({name}) must be digits, got '{value}'");
        if (digits == 0)                                       // fixed length
        {
            if (kind is "an" or "ans")
                raw = Encoding.ASCII.GetBytes(((string)value).PadRight(size));
            if (raw.Length != size)
                throw new ArgumentException($"field {n} ({name}) is fixed at {size}, got {raw.Length}");
            return raw;
        }
        if (raw.Length > size)
            throw new ArgumentException($"field {n} ({name}) allows {size}, got {raw.Length}");
        return [.. Encoding.ASCII.GetBytes(raw.Length.ToString($"D{digits}")), .. raw];   // the length counts bytes, never hex digits
    }

    // Read one message back. Throws FormatException with the field number when the bytes don't add up.
    public static (string Mti, SortedDictionary<int, object> Fields) Unpack(byte[] frame)
    {
        int header = frame[0] << 8 | frame[1];
        if (header != frame.Length - 2)
            throw new FormatException($"length header says {header}, message is {frame.Length - 2} bytes");
        var msg = frame[2..];
        var mti = Encoding.ASCII.GetString(msg, 0, 4);
        int bitmapLen = (msg[4] & 0x80) != 0 ? 16 : 8, i = 4 + bitmapLen;
        var bitmap = msg[4..i];
        var fields = new SortedDictionary<int, object>();
        for (int n = 2; n <= bitmapLen * 8; n++)
        {
            if ((bitmap[(n - 1) / 8] & (0x80 >> ((n - 1) % 8))) == 0)
                continue;
            if (!Fields.TryGetValue(n, out var spec))
                throw new FormatException($"bitmap has field {n}, which this layout doesn't define");
            var (name, kind, size, digits) = spec;
            int length = size;
            if (digits > 0)
            {
                var prefix = msg[i..Math.Min(i + digits, msg.Length)];
                if (prefix.Length < digits || !prefix.All(b => b is >= (byte)'0' and <= (byte)'9'))
                    throw new FormatException($"field {n} ({name}) should start with {digits} length digits, found {Emv.H(prefix)}");
                length = int.Parse(Encoding.ASCII.GetString(prefix));
                i += digits;
                if (length > size)
                    throw new FormatException($"field {n} ({name}) says {length}, the most it allows is {size}");
            }
            if (i + length > msg.Length)
                throw new FormatException($"field {n} ({name}) says {length} bytes, only {msg.Length - i} are left");
            var raw = msg[i..(i + length)];
            i += length;
            if (kind != "b" && raw.Any(b => b > 0x7F))
                throw new FormatException($"field {n} ({name}) should be text, found {Emv.H(raw)}");
            if (kind == "n" && !(raw.Length > 0 && raw.All(b => b is >= (byte)'0' and <= (byte)'9')))
                throw new FormatException($"field {n} ({name}) should be digits, found {Emv.H(raw)}");
            fields[n] = kind == "b" ? raw : kind is "an" or "ans" ? Encoding.ASCII.GetString(raw).TrimEnd(' ') : Encoding.ASCII.GetString(raw);
        }
        if (i != msg.Length)
            throw new FormatException($"{msg.Length - i} bytes left over after the last field");
        return (mti, fields);
    }

    public static bool Same(object? a, object? b) =>
        a is byte[] x && b is byte[] y ? x.AsSpan().SequenceEqual(y) : Equals(a, b);
}

// ================================================================ TLV (EMV Book 3, Annex B)

static class Tlv
{
    public static byte[] Build(string tag, byte[] value)
    {
        int n = value.Length;
        byte[] length = n < 0x80 ? [(byte)n] : n < 0x100 ? [0x81, (byte)n] : [0x82, (byte)(n >> 8), (byte)n];
        return [.. Emv.X(tag), .. length, .. value];
    }

    public static Dictionary<string, byte[]> Parse(byte[] data)
    {
        var output = new Dictionary<string, byte[]>();
        int i = 0;
        while (i < data.Length)
        {
            if (data[i] is 0x00 or 0xFF)                       // padding between objects
            {
                i++;
                continue;
            }
            int start = i++;
            if ((data[start] & 0x1F) == 0x1F)                  // low 5 bits set: the tag goes on
            {
                while (i < data.Length && (data[i] & 0x80) != 0)
                    i++;
                i++;
            }
            if (i >= data.Length)
                throw new FormatException($"field 55 ends inside tag {Emv.H(data[start..Math.Min(i, data.Length)])}");
            string tag = Emv.H(data[start..i]);
            int n = data[i++];
            if ((n & 0x80) != 0)                               // long form: 81 xx or 82 xx xx
            {
                int k = n & 0x7F;
                n = 0;
                for (int j = 0; j < k && i < data.Length; j++)
                    n = n << 8 | data[i++];
            }
            if (i + n > data.Length)
                throw new FormatException($"tag {tag} says {n} bytes, only {data.Length - i} are left");
            output[tag] = data[i..(i + n)];
            i += n;
        }
        return output;
    }

    public static readonly Dictionary<string, string> Names = new()
    {
        ["9F26"] = "application cryptogram", ["9F27"] = "cryptogram information data", ["9F10"] = "issuer application data",
        ["9F37"] = "unpredictable number", ["9F36"] = "application transaction counter", ["95"] = "terminal verification results",
        ["9A"] = "transaction date", ["9C"] = "transaction type", ["9F02"] = "amount, authorised", ["5F2A"] = "transaction currency",
        ["82"] = "application interchange profile", ["9F1A"] = "terminal country", ["9F03"] = "amount, other",
        ["9F33"] = "terminal capabilities", ["9F34"] = "CVM results", ["9F35"] = "terminal type", ["84"] = "dedicated file name (AID)",
        ["91"] = "issuer authentication data", ["71"] = "issuer script template 1", ["72"] = "issuer script template 2",
    };
}

// ================================================================ the cryptography from part 4 (EMV Book 2, Annex A1)

static class Emv
{
    public static readonly byte[] Imk = X("0123456789ABCDEF FEDCBA9876543210");   // a well-known TEST key: never use it for real cards

    public static readonly string[] Signed = ["9F02", "9F03", "9F1A", "95", "5F2A", "9A", "9C", "9F37", "82", "9F36", "9F10"];   // Table CCD 3 order

    public static byte[] X(string s) => Convert.FromHexString(s.Replace(" ", ""));
    public static string H(byte[] b) => Convert.ToHexString(b);

    // EMV keys are double length (K1 K2). Some OpenSSL builds only take three parts, so pass K1 K2 K1: the same cipher.
    static byte[] Ecb3(byte[] key, byte[] block)
    {
        using var tdes = TripleDES.Create();
        tdes.Key = [.. key, .. key[..8]];
        return tdes.EncryptEcb(block, PaddingMode.None);
    }

    static byte[] OddParity(byte[] key) =>
        [.. key.Select(b => (byte)(b & 0xFE | (System.Numerics.BitOperations.PopCount((uint)(b >> 1)) + 1) % 2))];

    public static byte[] CardMasterKey(byte[] imk, string pan, string psn)
    {
        string digits = pan + psn;
        var y = X(digits[Math.Max(0, digits.Length - 16)..].PadLeft(16, '0'));
        return OddParity([.. Ecb3(imk, y), .. Ecb3(imk, [.. y.Select(b => (byte)~b)])]);
    }

    public static byte[] SessionKey(byte[] mk, byte[] atc) =>
        [.. Ecb3(mk, [atc[0], atc[1], 0xF0, 0, 0, 0, 0, 0]), .. Ecb3(mk, [atc[0], atc[1], 0x0F, 0, 0, 0, 0, 0])];

    public static byte[] Mac(byte[] key, byte[] msg)
    {
        byte[] padded = [.. msg, 0x80, .. new byte[(8 - (msg.Length + 1) % 8) % 8]];
        using var left = DES.Create();
        using var right = DES.Create();
        left.Key = key[..8];
        right.Key = key[8..16];
        var block = new byte[8];
        for (int i = 0; i < padded.Length; i += 8)
        {
            for (int j = 0; j < 8; j++)
                block[j] ^= padded[i + j];
            block = left.EncryptEcb(block, PaddingMode.None);
        }
        return left.EncryptEcb(right.DecryptEcb(block, PaddingMode.None), PaddingMode.None);
    }

    public static byte[] SignedData(Dictionary<string, byte[]> t) => [.. Signed.SelectMany(tag => t[tag])];
}

// ================================================================ the four parties

// Part 4's card, cut down to what this post needs: answer GENERATE AC, then check tag 91.
class Card(byte[] mk)
{
    int atc;
    byte[] sk = [], arqc = [];

    public Dictionary<string, byte[]> GenerateAc(Dictionary<string, byte[]> terminal)
    {
        atc++;
        byte[] atcBytes = [(byte)(atc >> 8), (byte)atc];
        sk = Emv.SessionKey(mk, atcBytes);
        byte[] iad = [.. Emv.X("0F A5 01 A030000000"), .. new byte[8], 0x0F, .. new byte[15]];   // common core format A, version 5
        var t = new Dictionary<string, byte[]>(terminal) { ["82"] = Emv.X("1980"), ["9F36"] = atcBytes, ["9F10"] = iad };
        arqc = Emv.Mac(sk, Emv.SignedData(t));
        return new() { ["9F27"] = [0x80], ["9F36"] = atcBytes, ["9F26"] = arqc, ["9F10"] = iad, ["82"] = t["82"] };
    }

    public bool IssuerAuthentication(byte[] tag91) =>
        CryptographicOperations.FixedTimeEquals(Emv.Mac(sk, [.. arqc, .. tag91[4..8]])[..4], tag91[..4]);
}

class Terminal
{
    const string Tid = "TERM0042", Mid = "CORNERCAFE00017", Mcc = "5814";
    public const string Pan = "4761739001010010", Psn = "01";
    static readonly byte[] Track2 = Emv.X("4761739001010010D2812201000000000000");   // tag 57: PAN, 'D', expiry YYMM, service code, the rest
    static int stan = 122;

    public (byte[] Frame, SortedDictionary<int, object> Fields) Request(int amountCents, string un, Card card, string mmdd = "1126", string hhmmss = "143005")
    {
        var t = new Dictionary<string, byte[]>
        {
            ["9F02"] = Emv.X(amountCents.ToString("D12")), ["9F03"] = new byte[6], ["9F1A"] = Emv.X("0840"), ["95"] = Emv.X("0000008000"),
            ["5F2A"] = Emv.X("0840"), ["9A"] = Emv.X("26" + mmdd), ["9C"] = [0x00], ["9F37"] = Emv.X(un),
        };
        foreach (var (k, v) in card.GenerateAc(t))
            t[k] = v;
        t["9F33"] = Emv.X("E0F8C8");
        t["9F34"] = Emv.X("1F0302");
        t["9F35"] = [0x22];
        // Field 55: the tags Book 4 says an authorisation request needs, as TLV, in the order this terminal likes.
        string[] order = ["9F26", "9F27", "9F10", "9F37", "9F36", "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03", "9F33", "9F34", "9F35"];
        byte[] f55 = [.. order.SelectMany(tag => Tlv.Build(tag, t[tag]))];
        stan++;
        var track2 = Emv.H(Track2).Replace('D', '=').TrimEnd('F');   // tag 57 uses D and F padding; field 35 uses '='
        var fields = new SortedDictionary<int, object>
        {
            [2] = Pan, [3] = "000000", [4] = amountCents.ToString("D12"), [11] = stan.ToString("D6"), [12] = hhmmss,
            [13] = mmdd, [18] = Mcc, [22] = "071", [23] = Psn.PadLeft(3, '0'), [25] = "00", [35] = track2,
            [41] = Tid, [42] = Mid, [49] = "840", [55] = f55,
        };
        return (Iso8583.Pack("0100", fields), fields);
    }

    public static string Response(byte[] frame, SortedDictionary<int, object> sent, Card card)
    {
        var (mti, f) = Iso8583.Unpack(frame);
        if (mti != "0110" || !Equals(f[11], sent[11]) || !Equals(f[41], sent[41]))
            return $"not the answer to this request (MTI {mti}, STAN {f.GetValueOrDefault(11)}): treat as no response, send a reversal";
        var rc = (string)f[39];
        var decision = rc == "00" ? "approved" : $"declined ({rc})";
        // Field 39 becomes tag 8A, two ASCII characters, for the second GENERATE AC: "00" is 3030.
        var arc = Emv.H(Encoding.ASCII.GetBytes(rc));
        if (!f.TryGetValue(55, out var f55) || !Tlv.Parse((byte[])f55).TryGetValue("91", out var tag91))
            return $"{decision}, 8A = {arc}; no tag 91, so no issuer authentication; the card's settings decide the rest";
        return $"{decision}, 8A = {arc}, tag 91 {(card.IssuerAuthentication(tag91) ? "genuine" : "FORGED")}";
    }
}

// The merchant's bank: swaps in its own trace number, adds its ID and a reference, forwards the rest.
// On the way back it has to undo the swap, or the terminal won't recognise its own answer.
class Acquirer
{
    const string Id = "412345";
    int stan = 418206;
    readonly Dictionary<string, object> pending = [];          // our STAN -> the terminal's STAN

    public byte[] Forward(byte[] frame, Action<SortedDictionary<int, object>>? mutate = null)
    {
        var f = Iso8583.Unpack(frame).Fields;
        stan++;
        pending[stan.ToString("D6")] = f[11];
        f[7] = "1126143005";
        f[11] = stan.ToString("D6");
        f[32] = Id;
        f[37] = $"6330{((string)f[12])[..2]}{stan:D6}";
        mutate?.Invoke(f);
        return Iso8583.Pack("0100", f);
    }

    public byte[] Back(byte[] frame)
    {
        var (mti, f) = Iso8583.Unpack(frame);
        pending.Remove((string)f[11], out var theirs);
        f[11] = theirs!;                                       // the terminal's own trace number again
        f.Remove(7);                                           // ours, not the terminal's business
        f.Remove(32);
        return Iso8583.Pack(mti, f);
    }
}

// Routes on the first digits of the card number. It reads field 2 and nothing else.
class Switch
{
    static readonly Dictionary<string, string> Routes = new() { ["476173"] = "issuer A" };

    public string Route(byte[] frame) => Routes.GetValueOrDefault(((string)Iso8583.Unpack(frame).Fields[2])[..6], "no route");
}

class Issuer(byte[] imk, Dictionary<string, string> cards, bool checkAmount = true)
{
    static readonly byte[] Approve = Emv.X("00820000"), Decline = Emv.X("00000000");   // card status update: approved / declined
    readonly Dictionary<string, int> lastAtc = [];

    static string Money(string digits) => (long.Parse(digits) / 100m).ToString("0.00", CultureInfo.InvariantCulture);

    public (byte[] Frame, string Why) Authorise(byte[] frame)
    {
        SortedDictionary<int, object> f;
        try
        {
            f = Iso8583.Unpack(frame).Fields;
        }
        catch (FormatException e)
        {
            return ([], $"can't read the message: {e.Message}");   // no answer: it can't even tell who to send one to
        }
        var output = new SortedDictionary<int, object>();
        foreach (var n in new[] { 2, 3, 4, 7, 11, 12, 13, 32, 37, 41, 42, 49 })
            if (f.TryGetValue(n, out var v))
                output[n] = v;

        (byte[], string) Answer(string code, string why, byte[]? tag91 = null)
        {
            if (code == "00")
                output[38] = "731905";
            output[39] = code;
            if (tag91 is { Length: > 0 })
                output[55] = Tlv.Build("91", tag91);
            return (Iso8583.Pack("0110", output), why);
        }

        if (!f.TryGetValue(55, out var f55))
            return Answer("05", "no field 55, so nothing to check the card with");
        Dictionary<string, byte[]> t;
        try
        {
            t = Tlv.Parse((byte[])f55);
        }
        catch (FormatException e)
        {
            return Answer("30", $"field 55 doesn't parse: {e.Message}");   // 30 = format error
        }
        var missing = Emv.Signed.Concat(["9F26", "9F27"]).Where(tag => !t.ContainsKey(tag)).ToArray();
        if (missing.Length > 0)
            return Answer("05", $"field 55 has no {string.Join(" ", missing)}, so the cryptogram can't be checked");
        if (Emv.H(t["9F10"][..2]) != "0FA5")
            return Answer("05", $"issuer application data {Emv.H(t["9F10"][..2])}: not a method this host checks");
        var pan = (string)f[2];
        var sk = Emv.SessionKey(Emv.CardMasterKey(imk, pan, cards[pan]), t["9F36"]);
        var expected = Emv.Mac(sk, Emv.SignedData(t));
        if (!CryptographicOperations.FixedTimeEquals(expected, t["9F26"]))
            return Answer("05", $"cryptogram {Emv.H(t["9F26"])} doesn't match {Emv.H(expected)}");
        // The cryptogram covers tag 9F02 inside field 55. Field 4, the amount the bank will actually post,
        // is outside it. Only this comparison ties the two together.
        if (checkAmount && (string)f[4] != Emv.H(t["9F02"]))
            return Answer("05", $"field 4 is {Money((string)f[4])}, the card signed {Money(Emv.H(t["9F02"]))}",
                [.. Emv.Mac(sk, [.. t["9F26"], .. Decline])[..4], .. Decline]);
        int atc = t["9F36"][0] << 8 | t["9F36"][1];
        if (atc <= lastAtc.GetValueOrDefault(pan))
            return Answer("05", $"counter {atc:X4} already used", [.. Emv.Mac(sk, [.. t["9F26"], .. Decline])[..4], .. Decline]);
        lastAtc[pan] = atc;
        return Answer("00", $"cryptogram {Emv.H(expected)} matches; approved for {Money((string)f[4])}",
            [.. Emv.Mac(sk, [.. t["9F26"], .. Approve])[..4], .. Approve]);
    }
}

// ================================================================ printing

static class Print
{
    public static void Show(byte[] frame, string indent = "    ")
    {
        var (mti, f) = Iso8583.Unpack(frame);
        Console.WriteLine($"{indent}{frame.Length} bytes on the wire, MTI {mti}, bitmap {Emv.H(frame[6..14])}");
        foreach (var (n, v) in f)
        {
            var shown = v is byte[] b ? $"{b.Length} bytes" : (string)v;
            Console.WriteLine($"{indent}  {n,3}  {Iso8583.Fields[n].Name,-30} {shown}");
            if (n == 55)
                foreach (var (tag, val) in Tlv.Parse((byte[])v))
                    Console.WriteLine($"{indent}         {tag,-5}{Tlv.Names.GetValueOrDefault(tag, ""),-33}{Emv.H(val)}");
        }
    }

    public static void HexDump(byte[] frame, string indent = "    ")
    {
        for (int i = 0; i < frame.Length; i += 32)
            Console.WriteLine($"{indent}{Emv.H(frame[i..Math.Min(i + 32, frame.Length)])}");
    }
}