Part 5 ended with tag 91 coming back to the card in field 55 of the response. Field 55 can carry something else on the way back: commands for the card. EMV calls them issuer scripts. A bank uses them to unblock a PIN, change a limit or block a card, and it delivers them inside an ordinary authorisation response.

This is the last part of Behind the Tap. The code uses the same test card as parts 4 and 5. Its offline PIN is blocked after three wrong entries, so the issuer queues two commands for it: a new PIN, and a lower limit on how many days the card may go without an online transaction. The scripts build both commands, carry them back in the response and let the card check them. You can also hand them a script that your own host built, and they will check every MAC in it.

Not on a tap

The first thing my issuer has to decide is whether it can send the commands at all. Part 4's tap comes in first:

Output
1. part 4's tap, USD 25.00
  card       ATC 0001, ARQC 2007D63548109602
  issuer     approved; 2 script command(s) held: field 22 is 071, a tap
  terminal   a tap: the card left the field before the answer came, so tag 91 stays with the terminal

That ARQC is the same eight bytes you saw at the end of part 4: same card, same keys, same ATC, so the cryptogram has to match. Look at what the output leaves out, though. There is no second GENERATE AC. A simulator will happily run one after a tap, because nothing in the code stops it, but a real tap can't. By the time the 0110 arrives the card has left the field, so neither tag 91 nor a script can reach it.

Visa's contactless kernel (Kernel 3) has an optional way round this, called Issuer Update Processing. The reader asks you to tap a second time and delivers tag 91 and the script then. The card and the reader both have to support it, and the acquirer or merchant has to switch it on. My issuer doesn't rely on it. It keeps the commands in a queue and waits for a transaction where the card stays in the reader for the whole exchange, which in ISO 8583 terms is field 22 starting with 05 (chip read by contact):

Python
def authorise(self, pan: str, entry_mode: str, f55: bytes, build=None) -> tuple[str, bytes, str]:
    t = dict(tlv_list(f55))
    psn = self.cards[pan]
    sk = session_key(card_master_key(self.imk_ac, pan, psn), t["9F36"] + bytes(6))
    if not hmac.compare_digest(mac(sk, b"".join(t[tag] for tag in SIGNED)), t["9F26"]):
        return "05", b"", "cryptogram doesn't match"
    out = tlv("91", mac(sk, t["9F26"] + self.APPROVE)[:4] + self.APPROVE)
    commands = self.queue.get(pan)
    if not commands:
        return "00", out, "approved"
    # A tap is over before the answer arrives. Kernel 3 can deliver a script when the card is presented
    # a second time, if card and reader both support it. This host doesn't count on that and waits for
    # a contact transaction (field 22 starting 05).
    if not entry_mode.startswith("05"):
        return "00", out, f"approved; {len(commands)} script command(s) held: field 22 is {entry_mode}, a tap"
    script = (build or self.build_script)(pan, psn, t["9F26"], commands)
    return "00", out + script, f"approved, with a {len(script)}-byte script in tag 72"
The same in C#
C#
public (string Code, byte[] Response, string Why) Authorise(string pan, string entryMode, byte[] f55, ScriptBuilder? build = null)
{
    var t = TlvList(f55).ToDictionary(e => e.Tag, e => e.Value);
    string psn = cards[pan];
    var sk = SessionKey(CardMasterKey(imkAc, pan, psn), [.. t["9F36"], .. new byte[6]]);
    if (!Same(Mac(sk, Concat(Signed.Select(tag => t[tag]))), t["9F26"]))
        return ("05", [], "cryptogram doesn't match");
    byte[] output = Tlv("91", [.. Mac(sk, [.. t["9F26"], .. Approve])[..4], .. Approve]);
    if (!Queue.TryGetValue(pan, out var commands) || commands.Count == 0)
        return ("00", output, "approved");
    // A tap is over before the answer arrives. Kernel 3 can deliver a script when the card is presented
    // a second time, if card and reader both support it. This host doesn't count on that and waits for
    // a contact transaction (field 22 starting 05).
    if (!entryMode.StartsWith("05"))
        return ("00", output, $"approved; {commands.Count} script command(s) held: field 22 is {entryMode}, a tap");
    var script = (build ?? ((p, s, a, c) => BuildScript(p, s, a, c)))(pan, psn, t["9F26"], commands);
    return ("00", [.. output, .. script], $"approved, with a {script.Length}-byte script in tag 72");
}

What a script looks like

The next day the card goes into a terminal for a $40 payment. The issuer checks the cryptogram, approves, and adds tag 72 to field 55 of the 0110:

Output
  field 55 of the 0110, 68 bytes:
    91 08 D64CB8F200820000
    72 38 9F18040000A001861E8C240002198711012FF299FBCDE23F00825742C3D6CAFA338E0430CB716B860F0CDA00C30A810200078E047CEBEF94

Taken apart:

BytesWhat it is
72 38Issuer script template 2, 56 bytes long
9F18 04 0000A001Script identifier. The terminal doesn't interpret it; it reports it back
86 1E 8C24000219…Command 1, 30 bytes: PIN CHANGE/UNBLOCK
86 0F 0CDA00C30A…Command 2, 15 bytes: PUT DATA

Tag 72 tells the terminal to send the commands after the second GENERATE AC, once the card has already decided the transaction. Tag 71 means before, which matters when a PUT DATA should change a limit in time for the current transaction. Neither command here needs that.

Each command is an ordinary APDU. The second one is easier to read:

Output
0C DA 00 C3 0A   81 02 0007   8E 04 7CEBEF94

DA is PUT DATA, and P1 P2 hold the tag being written: 00C3, the number of days offline limit from EMV's Common Payment Application. The new value, 0007, is in tag 81, and the four-byte MAC is in tag 8E. The C in the class byte 0C says the command uses secure messaging with the header covered by the MAC. Without secure messaging the class byte would be 00.

Two more keys

Part 4's card had one key for this kind of work, MK-AC, which makes the cryptogram and checks the ARPC. A card that accepts scripts has two more, loaded at personalisation in the same way: MK-SMI for integrity, which checks the MACs, and MK-SMC for confidentiality, which deciphers the new PIN. The issuer derives all three the same way, each from its own issuer master key, the card number and the sequence number.

The session keys are where scripts differ from the cryptogram. The cryptogram key is diversified with the ATC. The two secure messaging keys are diversified with the ARQC the card produced in this transaction:

Python
def session_key(mk: bytes, r: bytes) -> bytes:
    """Common session key derivation. R is the ATC + six 00s for the cryptogram key, the ARQC for the
    secure messaging keys. Byte 3 of R is replaced by F0 for the left half and 0F for the right."""
    tdes = DES3.new(mk, DES3.MODE_ECB)
    return tdes.encrypt(r[:2] + b"\xF0" + r[3:8]) + tdes.encrypt(r[:2] + b"\x0F" + r[3:8])
The same in C#
C#
// Common session key derivation. R is the ATC + six 00s for the cryptogram key, the ARQC for the
// secure messaging keys. Byte 3 of R is replaced by F0 for the left half and 0F for the right.
public static byte[] SessionKey(byte[] mk, byte[] r) =>
    [.. Ecb3(mk, [r[0], r[1], 0xF0, .. r[3..8]]), .. Ecb3(mk, [r[0], r[1], 0x0F, .. r[3..8]])];

For the $40 payment that gives these two keys:

Output
  this transaction's secure messaging keys (R = the ARQC):
    MAC        79773803D093ACE6050DF42F4F0F37C0
    encipher   DC59BE5B1A3CB43AC2757924375E2FF2

So a script only works in the transaction it was built for. The issuer can't prepare one in advance, and a script copied out of an old response fails (case 2 below).

The MAC chain

Each command's MAC covers the command header and the data object. The first MAC also covers the ARQC, put in front of the message as an extra block. Each later MAC covers the full eight-byte result of the MAC before it, though only the first four bytes of each are sent:

Python
def mac_input(chain: bytes, header: bytes, data_object: bytes) -> bytes:
    # Format 1 follows ISO/IEC 7816-4: the header CLA INS P1 P2 padded to a full block, then the data object
    # with an odd tag (81 or 87). The chaining value goes in front as one more block.
    return chain + header + x("80000000") + data_object


def secure_command(header: bytes, data_object: bytes, sk_smi: bytes, chain: bytes) -> tuple[bytes, bytes]:
    full = mac(sk_smi, mac_input(chain, header, data_object))
    body = data_object + x("8E04") + full[:4]
    return header + bytes([len(body)]) + body, full     # the full MAC is the next command's chaining value
The same in C#
C#
// Format 1 follows ISO/IEC 7816-4: the header CLA INS P1 P2 padded to a full block, then the data object
// with an odd tag (81 or 87). The chaining value goes in front as one more block.
public static byte[] MacInput(byte[] chain, byte[] header, byte[] dataObject) =>
    [.. chain, .. header, 0x80, 0, 0, 0, .. dataObject];

// Returns the command and its full MAC, which is the next command's chaining value.
public static (byte[] Apdu, byte[] Full) SecureCommand(byte[] header, byte[] dataObject, byte[] skSmi, byte[] chain)
{
    var full = Mac(skSmi, MacInput(chain, header, dataObject));
    byte[] body = [.. dataObject, 0x8E, 0x04, .. full[..4]];
    return ([.. header, (byte)body.Length, .. body], full);
}
The MAC chain for the $40 payment. On the left, the ARQC 1C2563C053DDB946 and the two session keys derived from it. Command 1's MAC input is the ARQC, the header 8C 24 00 02 padded with 80 00 00 00, and the enciphered PIN in tag 87; its MAC is 30CB716B, sent, plus 1947A5F2, kept. An arrow carries the full 30CB716B1947A5F2 into command 2's MAC input with header 0C DA 00 C3 and value 0007, giving 7CEBEF94 sent and B78F0BC8 kept. Red notes: take command 1 out and the card gets a different MAC here, 6982; a script built for any other transaction starts from the wrong ARQC.
Each MAC starts where the previous one ended, and the first starts from this transaction's ARQC.

The chain makes the card check the commands as one sequence. If one is dropped, moved or sent twice, the MAC of the next command fails. The ARQC at the start ties the first command to this transaction a second time, on top of the session key.

The new PIN

The PIN travels enciphered, in tag 87 instead of 81. The plaintext is the chip's own PIN block: the digit 2, the number of PIN digits, the digits, then F up to eight bytes. For 4821 that's 244821FFFFFFFFFF. The issuer adds a padding block of 80 followed by seven 00 bytes and enciphers the 16 bytes with Triple DES in CBC mode under the encipherment session key. The 01 in front of the result in tag 87 is the padding indicator, which says the plaintext was padded.

Python
def pin_block(pin: str) -> bytes:
    # The chip's own plaintext PIN block: control 2, the PIN length, the digits, then F to fill 8 bytes.
    return x(f"2{len(pin):X}{pin}".ljust(16, "F"))


def encipher(key: bytes, data: bytes) -> bytes:
    data += b"\x80" + bytes(-(len(data) + 1) % 8)      # always padded, so the padding indicator is 01
    return DES3.new(key, DES3.MODE_CBC, iv=bytes(8)).encrypt(data)
The same in C#
C#
// The chip's own plaintext PIN block: control 2, the PIN length, the digits, then F to fill 8 bytes.
public static byte[] PinBlock(string pin) => X($"2{pin.Length:X}{pin}".PadRight(16, 'F'));

// Always padded, so the padding indicator is 01.
public static byte[] Encipher(byte[] key, byte[] data)
{
    using var tdes = Tdes(key);
    return tdes.EncryptCbc(Pad(data), new byte[8], PaddingMode.None);
}

The MAC covers the enciphered bytes, so the card can check it before deciphering anything.

On the card

The Common Payment Application spells out every check the card makes and the status word for each failure: 6700 for a wrong length, 6987 when the MAC object is missing, 6982 when the MAC is wrong, and 6988 when the PIN block isn't in the chip's format. The card can only find that last problem after the MAC has passed and the PIN has been deciphered.

Python
def _run(self, header: bytes, lc: int, body: bytes) -> str:
    cla, ins, p1, p2 = header
    if len(body) != lc or len(body) < 6:
        return "6700"
    data_object, mac_object = body[:-6], body[-6:]
    if mac_object[:2] != x("8E04"):
        return "6987"                               # expected secure messaging data objects missing
    full = mac(self.sk_smi, mac_input(self.chain, header, data_object))
    if not hmac.compare_digest(full[:4], mac_object[2:]):
        return "6982"                               # security status not satisfied: wrong key, wrong transaction or a gap
    self.chain = full

    if (cla, ins, p1) == (0x8C, 0x24, 0x00) and p2 == 0x02:     # PIN CHANGE/UNBLOCK, change the PIN
        if lc != 0x19 or data_object[:3] != x("871101"):
            return "6988"
        block = decipher(self.sk_smc, data_object[3:19])[:8]
        digits = h(block)
        n = int(digits[1], 16)
        if digits[0] != "2" or not 4 <= n <= 12 or not digits[2:2 + n].isdigit() or set(digits[2 + n:]) != {"F"}:
            return "6988"                           # MAC fine, but the PIN block isn't in the chip's format
        self.pin, self.pin_tries = digits[2:2 + n], self.pin_try_limit
    elif (cla, ins, p1, p2) == (0x8C, 0x24, 0x00, 0x00):        # PIN CHANGE/UNBLOCK, unblock only
        self.pin_tries = self.pin_try_limit
    elif (cla, ins) == (0x0C, 0xDA):                            # PUT DATA, P1 P2 = the tag
        tag = f"{p1:02X}{p2:02X}".removeprefix("00")
        if data_object[:1] != x("81"):
            return "6987"
        if tag not in self.data:
            return "6A86"
        value = data_object[2:]
        if len(value) > len(self.data[tag]):
            return "6700"
        self.data[tag] = value
    else:
        return "6A81"                               # MAC fine, command not supported here
    self.script_counter = (self.script_counter + 1) % 16
    return "9000"
The same in C#
C#
string Execute(byte[] header, int lc, byte[] body)
{
    var (cla, ins, p1, p2) = (header[0], header[1], header[2], header[3]);
    if (body.Length != lc || body.Length < 6)
        return "6700";
    var (dataObject, macObject) = (body[..^6], body[^6..]);
    if (macObject[0] != 0x8E || macObject[1] != 0x04)
        return "6987";                                      // expected secure messaging data objects missing
    var full = Mac(skSmi, MacInput(chain, header, dataObject));
    if (!Same(full[..4], macObject[2..]))
        return "6982";                                      // security status not satisfied: wrong key, wrong transaction or a gap
    chain = full;

    if ((cla, ins, p1, p2) == (0x8C, 0x24, 0x00, 0x02))       // PIN CHANGE/UNBLOCK, change the PIN
    {
        if (lc != 0x19 || H(dataObject[..3]) != "871101")
            return "6988";
        string digits = H(Decipher(skSmc, dataObject[3..19])[..8]);
        int n = Convert.ToInt32(digits[1..2], 16);
        if (digits[0] != '2' || n is < 4 or > 12 || !digits[2..(2 + n)].All(char.IsAsciiDigit) || digits[(2 + n)..].Any(c => c != 'F'))
            return "6988";                                  // MAC fine, but the PIN block isn't in the chip's format
        (pin, PinTries) = (digits[2..(2 + n)], PinTryLimit);
    }
    else if ((cla, ins, p1, p2) == (0x8C, 0x24, 0x00, 0x00))  // PIN CHANGE/UNBLOCK, unblock only
        PinTries = PinTryLimit;
    else if ((cla, ins) == (0x0C, 0xDA))                      // PUT DATA, P1 P2 = the tag
    {
        string tag = p1 == 0 ? $"{p2:X2}" : $"{p1:X2}{p2:X2}";
        if (dataObject.Length == 0 || dataObject[0] != 0x81)
            return "6987";
        if (!Data.TryGetValue(tag, out var old))
            return "6A86";
        var value = dataObject[2..];
        if (value.Length > old.Length)
            return "6700";
        Data[tag] = value;
    }
    else
        return "6A81";                                      // MAC fine, command not supported here
    ScriptCounter = (ScriptCounter + 1) % 16;
    return "9000";
}

Once a command fails, the card refuses every later script command in the same transaction. The card enforces that itself rather than trusting the terminal to stop.

What the terminal reports

For each response the terminal looks only at the first status byte. 90 means success, and 62 and 63 are warnings that count as success too. Anything else ends the script. The terminal records the outcome in Issuer Script Results: one byte for the result (2 for success; 1 for failure, plus the number of the failed command; 0 for not performed), followed by the four-byte script identifier.

Output
  card       second GENERATE AC: TC (approved)
  terminal   tag 72: after the second GENERATE AC
    1. 8C240002198711012FF299FBCDE23F00825742C3D6CAFA338E0430CB716B  ->  9000
    2. 0CDA00C30A810200078E047CEBEF94  ->  9000
  terminal   Issuer Script Results 200000A001, TVR byte 5 00, TSI byte 1 04
  card now   PIN tries left 3, days offline limit 0007, script commands done 2
  VERIFY 4821 -> 9000

The terminal sends Issuer Script Results with the clearing record or the confirmation message, or in a reversal. After a decline, when there's no such message, it creates an advice if it can. That's the only way the issuer learns what happened. My issuer clears its queue only when the result starts with 2. Anything else and the commands go out again with the next contact transaction.

Python
def run_script(template: bytes, card: Card, tvr: bytearray, tsi: bytearray, before_final: bool) -> bytes:
    """Book 3 section 10.10 and Book 4 section 6.3.9. Returns 5 bytes of Issuer Script Results."""
    tag_bit = 0x20 if before_final else 0x10            # TVR byte 5: failed before / after final GENERATE AC
    if len(template) > 128:
        # Book 4: a terminal must take scripts up to 128 bytes in total. Over that, report it not performed.
        inner = tlv_list(template)[0][1]
        sid = next((v for t, v in tlv_list(inner) if t == "9F18"), bytes(4))
        print(f"    script is {len(template)} bytes, over the 128 this terminal takes: nothing sent")
        return x("00") + sid
    try:
        items = tlv_list(tlv_list(template)[0][1])
    except ValueError as e:
        print(f"    script doesn't parse ({e}): nothing sent")
        tsi[0] |= 0x04
        tvr[4] |= tag_bit
        return x("00") + bytes(4)
    sid = next((v for t, v in items if t == "9F18"), bytes(4))
    tsi[0] |= 0x04                                      # TSI byte 1: script processing was performed
    for n, (tag, apdu) in enumerate((i for i in items if i[0] == "86"), start=1):
        sw = card.command(apdu)
        print(f"    {n}. {h(apdu)}  ->  {sw}")
        if sw[:2] not in ("90", "62", "63"):            # only SW1 counts: 90 normal, 62 and 63 warnings
            tvr[4] |= tag_bit
            return bytes([0x10 | min(n, 15)]) + sid     # failed, at command n
    return x("20") + sid
The same in C#
C#
// Book 3 section 10.10 and Book 4 section 6.3.9. Returns 5 bytes of Issuer Script Results.
static byte[] RunScript(byte[] template, Card card, byte[] tvr, byte[] tsi, bool beforeFinal)
{
    byte tagBit = (byte)(beforeFinal ? 0x20 : 0x10);        // TVR byte 5: failed before / after final GENERATE AC
    if (template.Length > 128)
    {
        // Book 4: a terminal must take scripts up to 128 bytes in total. Over that, report it not performed.
        var inner = TlvList(TlvList(template)[0].Value);
        var id = inner.FirstOrDefault(e => e.Tag == "9F18").Value ?? new byte[4];
        Console.WriteLine($"    script is {template.Length} bytes, over the 128 this terminal takes: nothing sent");
        return [0x00, .. id];
    }
    List<(string Tag, byte[] Value)> items;
    try
    {
        items = TlvList(TlvList(template)[0].Value);
    }
    catch (FormatException e)
    {
        Console.WriteLine($"    script doesn't parse ({e.Message}): nothing sent");
        tsi[0] |= 0x04;
        tvr[4] |= tagBit;
        return new byte[5];
    }
    var sid = items.FirstOrDefault(e => e.Tag == "9F18").Value ?? new byte[4];
    tsi[0] |= 0x04;                                          // TSI byte 1: script processing was performed
    int n = 0;
    foreach (var (_, apdu) in items.Where(e => e.Tag == "86"))
    {
        n++;
        var sw = card.Command(apdu);
        Console.WriteLine($"    {n}. {H(apdu)}  ->  {sw}");
        if (sw[..2] is not ("90" or "62" or "63"))           // only SW1 counts: 90 normal, 62 and 63 warnings
        {
            tvr[4] |= tagBit;
            return [(byte)(0x10 | Math.Min(n, 15)), .. sid];  // failed, at command n
        }
    }
    return [0x20, .. sid];
}

Five ways it goes wrong

Each case starts again from a card with a blocked PIN and sends the $40 payment:

Output
1. the issuer MACs the script with the MK-AC instead of the MK-SMI
  card       ATC 0002, ARQC 1C2563C053DDB946
  issuer     approved, with a 58-byte script in tag 72
  card       second GENERATE AC: TC (approved)
  terminal   tag 72: after the second GENERATE AC
    1. 8C240002198711012FF299FBCDE23F00825742C3D6CAFA338E047FA74157  ->  6982
  terminal   Issuer Script Results 110000A001, TVR byte 5 10, TSI byte 1 04
  card now   PIN tries left 0, days offline limit 0014, script commands done 0

2. a script made for an earlier transaction
  card       ATC 0002, ARQC 1C2563C053DDB946
  issuer     approved, with a 58-byte script in tag 72
  card       second GENERATE AC: TC (approved)
  terminal   tag 72: after the second GENERATE AC
    1. 8C2400021987110100AB341AB75E8383A65CE6089A1503C28E046F646D6C  ->  6982
  terminal   Issuer Script Results 110000A001, TVR byte 5 10, TSI byte 1 04
  card now   PIN tries left 0, days offline limit 0014, script commands done 0

3. the PIN change taken out after the MACs were made
  card       ATC 0002, ARQC 1C2563C053DDB946
  issuer     approved, with a 58-byte script in tag 72
  card       second GENERATE AC: TC (approved)
  terminal   tag 72: after the second GENERATE AC
    1. 0CDA00C30A810200078E047CEBEF94  ->  6982
  terminal   Issuer Script Results 110000A001, TVR byte 5 10, TSI byte 1 04
  card now   PIN tries left 0, days offline limit 0014, script commands done 0

4. the new PIN sent as an online PIN block (ISO format 0)
  card       ATC 0002, ARQC 1C2563C053DDB946
  issuer     approved, with a 58-byte script in tag 72
  card       second GENERATE AC: TC (approved)
  terminal   tag 72: after the second GENERATE AC
    1. 8C24000219871101A8762277C360DC185D72A9A5A2D706308E04193388FF  ->  6988
  terminal   Issuer Script Results 110000A001, TVR byte 5 10, TSI byte 1 04
  card now   PIN tries left 0, days offline limit 0014, script commands done 0

5. a 96-byte UPDATE RECORD added to the same script
  card       ATC 0002, ARQC 1C2563C053DDB946
  issuer     approved, with a 170-byte script in tag 72
  card       second GENERATE AC: TC (approved)
  terminal   tag 72: after the second GENERATE AC
    script is 170 bytes, over the 128 this terminal takes: nothing sent
  terminal   Issuer Script Results 000000A001, TVR byte 5 00, TSI byte 1 00
  card now   PIN tries left 0, days offline limit 0014, script commands done 0

1. The wrong key. The host MACs the script under MK-AC instead of MK-SMI. Both keys are double-length Triple DES keys and both are derived the same way, so nothing on the issuer side objects. The card answers 6982 to the first command and the PIN stays blocked. The terminal reports 11 (failed at command 1) and sets byte 5 of the TVR to 10, the bit for a script that failed after the final GENERATE AC. The payment itself went through, because the card had already produced its TC before the script ran.

2. An old script. The script was built for part 4's ARQC and arrives with the $40 payment. The session key and the start of the chain both come from the wrong ARQC, so the card answers 6982. This is what stops someone who records an 0110 from replaying a PIN change later.

3. A command removed. The host builds the MACs and then takes the PIN change out of the script. PUT DATA is now first, but its MAC was chained from the PIN change's MAC, while the card starts its chain from the ARQC. If a script has to change, it has to be built again from the start.

4. The online PIN format. Online PIN often travels as ISO format 0: the PIN block XORed with part of the card number, enciphered under PIN keys shared along the way to the issuer. A host that already holds the new PIN in that format might pass it on as it is. The MAC passes, because the issuer MACed what it sent. The card deciphers the block, finds 0 where the 2 should be, and answers 6988. The PIN doesn't change, and the PUT DATA after it never runs.

5. Too long. EMV Book 4 only requires a terminal to accept issuer scripts up to 128 bytes in total per response. Adding a 96-byte UPDATE RECORD makes this script 170 bytes, so my terminal sends nothing and reports 00, not performed, with the script identifier. Some terminals accept more, but an issuer can only count on 128, so a large update has to be split over several transactions.

If you build the issuer side

  • Build each script after the ARQC check, from that ARQC. Don't cache scripts.
  • Keep three separate issuer master keys, and check which one every HSM call is using.
  • Hold scripts until a transaction can deliver them, and only clear them when Issuer Script Results come back starting with 2.
  • Keep each response's scripts within 128 bytes.
  • Send PIN changes in the chip's PIN block format, with control nibble 2, not in the online PIN format.

For the technical reader

  • Secure messaging. EMV Book 2's secure messaging chapter defines Format 1 and the recommended MAC chaining. Its Common Core Definitions require Format 1, 4-byte MACs, chaining, and padding indicator 01 for enciphered data. The session keys use the common session key derivation in Annex A1, with R set to the application cryptogram (followed by zeros for a 16-byte block cipher). Master keys use Option B, which is the same as Option A for a PAN of 16 digits or fewer.
  • The MAC input. ISO 9797-1 MAC algorithm 3 with DES and padding method 2, the same function as part 4. The message is the chaining value, then CLA INS P1 P2 padded to eight bytes, then the 81 or 87 data object. Book 2 points to ISO/IEC 7816-4 for the layout. The Python and C# versions print the same bytes, and the openssl command line gives the same keys, enciphered PIN and first MAC. Neither has been run against a real common core card, so test against your card's own documentation before relying on this layout. Card applications with their own secure messaging format build the MAC input differently.
  • Card behaviour. The Common Payment Application's chapter on issuer script command processing covers APPLICATION UNBLOCK, PIN CHANGE/UNBLOCK, PUT DATA and UPDATE RECORD, with the status words, the "script failed" handling and the list of data elements PUT DATA may change.
  • Terminal behaviour. Book 3's issuer-to-card script processing section and Annex E cover the order of commands, SW1-only checking, TVR byte 5 bits 6 and 5, and TSI byte 1 bit 3. Book 4 adds the 128-byte minimum, the coding of Issuer Script Results, where they're reported, and what to do with a script that's too long or doesn't parse.
  • Contactless. Kernel 3's Issuer Update Processing is optional for both the reader and the card and needs a second presentment. Kernels 5 and 6 describe similar optional processing.

The end of the series

That's the last part of Behind the Tap. The six posts, in order:

  1. Half a second: what the beep on a contactless tap really means: the time budget of a tap, and why the beep isn't the payment.
  2. Your phone is pretending to be a card: wallets, tokens and how the phone checks it's you.
  3. Your card has more numbers than you think: a token's life from request to suspension.
  4. Eight bytes that prove your card was there: the ARQC and the ARPC, worked through.
  5. How a tap gets to your bank: the same tap as ISO 8583 bytes, hop by hop.
  6. This one: what the bank can send back.

Parts 4, 5 and 6 share one test card and one set of test keys, so the numbers line up across them. The ARQC that part 4 calculates is the one part 5 carries through the network, and it's the first line of this post's walk-through.

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 Scripts.cs.

With no arguments you get the walk-through. To check a script, pass the tag 71 or 72 template with --check, along with the ARQC it was built for, the card number, the sequence number and your test SMI and SMC keys. This checks the script from the walk-through:

Bash
python scripts.py --check 72389F18040000A001861E8C240002198711012FF299FBCDE23F00825742C3D6CAFA338E0430CB716B860F0CDA00C30A810200078E047CEBEF94 \
  --arqc 1C2563C053DDB946 --pan 4761739001010010 --psn 01 \
  --smi 89ABCDEF0123456776543210FEDCBA98 --smc FEDCBA98765432100123456789ABCDEF
Output
tag 72, 58 bytes
script identifier 0000A001
8C240002198711012FF299FBCDE23F00825742C3D6CAFA338E0430CB716B
  MAC 30CB716B: matches
  PIN block: control 2, length 4, digits ****, filler all F, padding 8000000000000000
0CDA00C30A810200078E047CEBEF94
  MAC 7CEBEF94: matches

The PIN digits are masked. If a MAC fails, the tool doesn't decipher the PIN block, because with the wrong keys or the wrong ARQC it would only print noise. Use test keys only. A live issuer key belongs in an HSM, never on a command line.

scripts.py
Python
"""Send commands from the issuer to the card inside an authorisation response: EMV issuer scripts.

Same card and the same test issuer key as parts 4 and 5. The card's offline PIN is blocked, so the issuer
queues two commands for it: PIN CHANGE/UNBLOCK with a new PIN, and PUT DATA to change a limit. They ride
back to the terminal in field 55 of the 0110, inside tag 72, and the terminal hands them to the card after
the second GENERATE AC. The card only runs a command if its MAC checks out under the secure messaging key.

What follows the specs (EMV Book 2 section 9 and Annex A1.3, Book 3 section 10.10, Book 4 section 6.3.9,
and the Common Payment Application, chapter 18):
  - session keys for secure messaging come from the card's MK-SMI and MK-SMC, diversified with the
    ARQC of this transaction, so a script only works for the transaction it was made for
  - Format 1: the command data travels in tag 81 (plain) or 87 (enciphered), the MAC in tag 8E (4 bytes)
  - the MACs are chained: the first starts from the ARQC, each next one from the previous full MAC
  - the new PIN block is enciphered with Triple DES in CBC mode under the encipherment session key

Two ways to run it (TEST keys only, never a live issuer key):
  python scripts.py                              the walk-through: a tap, a chip-and-PIN payment, then five ways it breaks
  python scripts.py --check HEX --arqc HEX --pan PAN [--psn 01] --smi KEY --smc KEY
                                                 check a tag 71/72 script your host built: every MAC in the chain,
                                                 and the PIN block inside a PIN change (digits masked)

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()


# ================================================================ TLV, keeping order and repeats (a script has many 86s)

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 tlv_list(data: bytes) -> list[tuple[str, bytes]]:
    out, i = [], 0
    while i < len(data):
        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"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
            if k not in (1, 2) or i + k > len(data):
                raise ValueError(f"tag {tag} has a length byte {n:02X} that EMV doesn't use")
            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.append((tag, data[i:i + n]))
        i += n
    return out


# ================================================================ cryptography (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:
    # Option A. Common core cards use Option B, which is Option A for any PAN of 16 digits or fewer.
    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, r: bytes) -> bytes:
    """Common session key derivation. R is the ATC + six 00s for the cryptogram key, the ARQC for the
    secure messaging keys. Byte 3 of R is replaced by F0 for the left half and 0F for the right."""
    tdes = DES3.new(mk, DES3.MODE_ECB)
    return tdes.encrypt(r[:2] + b"\xF0" + r[3:8]) + tdes.encrypt(r[:2] + b"\x0F" + r[3:8])


def mac(key: bytes, msg: bytes) -> bytes:
    """ISO 9797-1 MAC algorithm 3 with padding method 2: the full 8 bytes (scripts send the first 4)."""
    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))


def encipher(key: bytes, data: bytes) -> bytes:
    data += b"\x80" + bytes(-(len(data) + 1) % 8)      # always padded, so the padding indicator is 01
    return DES3.new(key, DES3.MODE_CBC, iv=bytes(8)).encrypt(data)


def decipher(key: bytes, data: bytes) -> bytes:
    return DES3.new(key, DES3.MODE_CBC, iv=bytes(8)).decrypt(data)


def mac_input(chain: bytes, header: bytes, data_object: bytes) -> bytes:
    # Format 1 follows ISO/IEC 7816-4: the header CLA INS P1 P2 padded to a full block, then the data object
    # with an odd tag (81 or 87). The chaining value goes in front as one more block.
    return chain + header + x("80000000") + data_object


def secure_command(header: bytes, data_object: bytes, sk_smi: bytes, chain: bytes) -> tuple[bytes, bytes]:
    full = mac(sk_smi, mac_input(chain, header, data_object))
    body = data_object + x("8E04") + full[:4]
    return header + bytes([len(body)]) + body, full     # the full MAC is the next command's chaining value


def pin_block(pin: str) -> bytes:
    # The chip's own plaintext PIN block: control 2, the PIN length, the digits, then F to fill 8 bytes.
    return x(f"2{len(pin):X}{pin}".ljust(16, "F"))


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


# ================================================================ the card

class Card:
    """A common core card cut down to what scripts touch: the cryptogram, tag 91, and three script commands.
    Status words follow the Common Payment Application, chapter 18."""

    def __init__(self, mk_ac: bytes, mk_smi: bytes, mk_smc: bytes, atc: int):
        self.mk_ac, self.mk_smi, self.mk_smc = mk_ac, mk_smi, mk_smc
        self.atc = atc                                  # transactions so far
        self.pin, self.pin_tries, self.pin_try_limit = "1234", 0, 3   # 0 tries left: the offline PIN is blocked
        self.data = {"C3": x("0014")}                   # Number of Days Offline Limit, n4: 14 days
        self.script_counter = 0                         # counts successful script commands, cyclic 0 to F

    def generate_ac(self, t: dict[str, bytes]) -> dict[str, bytes]:
        self.atc += 1
        atc = self.atc.to_bytes(2, "big")
        iad = x("0F A5 01 A030000000") + bytes(8) + x("0F") + bytes(15)
        t = dict(t, **{"82": x("1980"), "9F36": atc, "9F10": iad})
        self.arqc = mac(session_key(self.mk_ac, atc + bytes(6)), b"".join(t[tag] for tag in SIGNED))
        # The secure messaging keys for this transaction exist from this moment: R is the ARQC.
        self.sk_smi, self.sk_smc = session_key(self.mk_smi, self.arqc), session_key(self.mk_smc, self.arqc)
        self.chain, self.script_failed = self.arqc, False
        return {"9F27": x("80"), "9F36": atc, "9F26": self.arqc, "9F10": iad, "82": t["82"]}

    def second_generate_ac(self, arc: bytes, tag91: bytes | None) -> str:
        sk = session_key(self.mk_ac, self.atc.to_bytes(2, "big") + bytes(6))
        genuine = tag91 is not None and hmac.compare_digest(mac(sk, self.arqc + tag91[4:8])[:4], tag91[:4])
        return "TC (approved)" if arc == b"00" and genuine else "AAC (declined)"

    def command(self, apdu: bytes) -> str:
        header, lc, body = apdu[:4], apdu[4], apdu[5:]
        if self.script_failed:
            return "6982"                               # after one failure, the rest of this transaction's script is refused
        sw = self._run(header, lc, body)
        if sw[:2] not in ("90", "62", "63"):
            self.script_failed = True
        return sw

    def _run(self, header: bytes, lc: int, body: bytes) -> str:
        cla, ins, p1, p2 = header
        if len(body) != lc or len(body) < 6:
            return "6700"
        data_object, mac_object = body[:-6], body[-6:]
        if mac_object[:2] != x("8E04"):
            return "6987"                               # expected secure messaging data objects missing
        full = mac(self.sk_smi, mac_input(self.chain, header, data_object))
        if not hmac.compare_digest(full[:4], mac_object[2:]):
            return "6982"                               # security status not satisfied: wrong key, wrong transaction or a gap
        self.chain = full

        if (cla, ins, p1) == (0x8C, 0x24, 0x00) and p2 == 0x02:     # PIN CHANGE/UNBLOCK, change the PIN
            if lc != 0x19 or data_object[:3] != x("871101"):
                return "6988"
            block = decipher(self.sk_smc, data_object[3:19])[:8]
            digits = h(block)
            n = int(digits[1], 16)
            if digits[0] != "2" or not 4 <= n <= 12 or not digits[2:2 + n].isdigit() or set(digits[2 + n:]) != {"F"}:
                return "6988"                           # MAC fine, but the PIN block isn't in the chip's format
            self.pin, self.pin_tries = digits[2:2 + n], self.pin_try_limit
        elif (cla, ins, p1, p2) == (0x8C, 0x24, 0x00, 0x00):        # PIN CHANGE/UNBLOCK, unblock only
            self.pin_tries = self.pin_try_limit
        elif (cla, ins) == (0x0C, 0xDA):                            # PUT DATA, P1 P2 = the tag
            tag = f"{p1:02X}{p2:02X}".removeprefix("00")
            if data_object[:1] != x("81"):
                return "6987"
            if tag not in self.data:
                return "6A86"
            value = data_object[2:]
            if len(value) > len(self.data[tag]):
                return "6700"
            self.data[tag] = value
        else:
            return "6A81"                               # MAC fine, command not supported here
        self.script_counter = (self.script_counter + 1) % 16
        return "9000"

    def verify(self, pin: str) -> str:
        if self.pin_tries == 0:
            return "6983"                               # PIN blocked
        if hmac.compare_digest(pin, self.pin):
            self.pin_tries = self.pin_try_limit
            return "9000"
        self.pin_tries -= 1
        return f"63C{self.pin_tries:X}"                 # wrong, this many tries left


# ================================================================ the issuer

class Issuer:
    APPROVE = x("00820000")                             # card status update, as in part 4

    def __init__(self, imk_ac: bytes, imk_smi: bytes, imk_smc: bytes, cards: dict[str, str]):
        self.imk_ac, self.imk_smi, self.imk_smc, self.cards = imk_ac, imk_smi, imk_smc, cards
        self.queue: dict[str, list[tuple]] = {}         # PAN -> commands waiting for a transaction that can carry them
        self.next_script_id = 0xA001

    def authorise(self, pan: str, entry_mode: str, f55: bytes, build=None) -> tuple[str, bytes, str]:
        t = dict(tlv_list(f55))
        psn = self.cards[pan]
        sk = session_key(card_master_key(self.imk_ac, pan, psn), t["9F36"] + bytes(6))
        if not hmac.compare_digest(mac(sk, b"".join(t[tag] for tag in SIGNED)), t["9F26"]):
            return "05", b"", "cryptogram doesn't match"
        out = tlv("91", mac(sk, t["9F26"] + self.APPROVE)[:4] + self.APPROVE)
        commands = self.queue.get(pan)
        if not commands:
            return "00", out, "approved"
        # A tap is over before the answer arrives. Kernel 3 can deliver a script when the card is presented
        # a second time, if card and reader both support it. This host doesn't count on that and waits for
        # a contact transaction (field 22 starting 05).
        if not entry_mode.startswith("05"):
            return "00", out, f"approved; {len(commands)} script command(s) held: field 22 is {entry_mode}, a tap"
        script = (build or self.build_script)(pan, psn, t["9F26"], commands)
        return "00", out + script, f"approved, with a {len(script)}-byte script in tag 72"

    def build_script(self, pan: str, psn: str, arqc: bytes, commands: list[tuple], imk_smi=None) -> bytes:
        sk_smi = session_key(card_master_key(imk_smi or self.imk_smi, pan, psn), arqc)
        sk_smc = session_key(card_master_key(self.imk_smc, pan, psn), arqc)
        chain, apdus = arqc, []
        for kind, value in commands:
            if kind == "pin":
                header, data_object = x("8C240002"), tlv("87", b"\x01" + encipher(sk_smc, pin_block(value)))
            elif kind == "pin-block":                   # a ready-made 8-byte block, for case 4
                header, data_object = x("8C240002"), tlv("87", b"\x01" + encipher(sk_smc, value))
            else:                                       # ("put", tag, value) and ("record", p1p2, value)
                tag, val = value
                header = x("0CDA" + tag.rjust(4, "0")) if kind == "put" else x("0CDC" + tag)
                data_object = tlv("81", val)
            apdu, chain = secure_command(header, data_object, sk_smi, chain)
            apdus.append(apdu)
        script_id = self.next_script_id.to_bytes(4, "big")
        self.next_script_id += 1
        return tlv("72", tlv("9F18", script_id) + b"".join(tlv("86", a) for a in apdus))

    def script_results(self, pan: str, results: bytes) -> None:
        # Issuer Script Results come back in the clearing record or the next message. Only a clean
        # result clears the queue; anything else, and the commands go out again next time.
        if results[:1] == x("20"):
            self.queue.pop(pan, None)


# ================================================================ the terminal

PAN, PSN = "4761739001010010", "01"
IMK_AC = x("0123456789ABCDEF FEDCBA9876543210")        # part 4's TEST key
IMK_SMI = x("89ABCDEF01234567 76543210FEDCBA98")       # TEST keys, made up for this post
IMK_SMC = x("FEDCBA9876543210 0123456789ABCDEF")


def run_script(template: bytes, card: Card, tvr: bytearray, tsi: bytearray, before_final: bool) -> bytes:
    """Book 3 section 10.10 and Book 4 section 6.3.9. Returns 5 bytes of Issuer Script Results."""
    tag_bit = 0x20 if before_final else 0x10            # TVR byte 5: failed before / after final GENERATE AC
    if len(template) > 128:
        # Book 4: a terminal must take scripts up to 128 bytes in total. Over that, report it not performed.
        inner = tlv_list(template)[0][1]
        sid = next((v for t, v in tlv_list(inner) if t == "9F18"), bytes(4))
        print(f"    script is {len(template)} bytes, over the 128 this terminal takes: nothing sent")
        return x("00") + sid
    try:
        items = tlv_list(tlv_list(template)[0][1])
    except ValueError as e:
        print(f"    script doesn't parse ({e}): nothing sent")
        tsi[0] |= 0x04
        tvr[4] |= tag_bit
        return x("00") + bytes(4)
    sid = next((v for t, v in items if t == "9F18"), bytes(4))
    tsi[0] |= 0x04                                      # TSI byte 1: script processing was performed
    for n, (tag, apdu) in enumerate((i for i in items if i[0] == "86"), start=1):
        sw = card.command(apdu)
        print(f"    {n}. {h(apdu)}  ->  {sw}")
        if sw[:2] not in ("90", "62", "63"):            # only SW1 counts: 90 normal, 62 and 63 warnings
            tvr[4] |= tag_bit
            return bytes([0x10 | min(n, 15)]) + sid     # failed, at command n
    return x("20") + sid


def transaction(title: str, card: Card, issuer: Issuer, amount_cents: int, un: str, date: str, entry_mode: str,
                build=None, deliver=None, verbose=False) -> None:
    print(f"\n{title}")
    tvr = bytearray(x("0000200000") if entry_mode.startswith("05") else x("0000008000"))  # 05x: PIN try limit exceeded
    tsi = bytearray(2)
    t = {"9F02": x(f"{amount_cents:012d}"), "9F03": bytes(6), "9F1A": x("0840"), "95": bytes(tvr),
         "5F2A": x("0840"), "9A": x(date), "9C": x("00"), "9F37": x(un)}
    t |= card.generate_ac(t)
    print(f"  card       ATC {h(t['9F36'])}, ARQC {h(t['9F26'])}")
    f55 = b"".join(tlv(tag, t[tag]) for tag in ["9F26", "9F27", "9F10", "9F37", "9F36", "95", "9A", "9C",
                                                "9F02", "5F2A", "82", "9F1A", "9F03"])
    code, resp55, why = issuer.authorise(PAN, entry_mode, f55, build)
    print(f"  issuer     {why}")
    if not entry_mode.startswith("05"):
        print("  terminal   a tap: the card left the field before the answer came, so tag 91 stays with the terminal")
        return
    if deliver:
        resp55 = deliver(resp55)
    tags = tlv_list(resp55)
    if verbose and len(tags) > 1:
        print(f"  field 55 of the 0110, {len(resp55)} bytes:")
        for tag, value in tags:
            whole = h(tlv(tag, value))
            print(f"    {whole[:len(tag)]} {whole[len(tag):len(tag) + 2]} {whole[len(tag) + 2:]}")
        sk_smi = session_key(card_master_key(IMK_SMI, PAN, PSN), t["9F26"])
        sk_smc = session_key(card_master_key(IMK_SMC, PAN, PSN), t["9F26"])
        print(f"  this transaction's secure messaging keys (R = the ARQC):\n    MAC        {h(sk_smi)}\n"
              f"    encipher   {h(sk_smc)}")
    results = b""
    for tag, value in tags:
        if tag == "71":
            print("  terminal   tag 71: before the second GENERATE AC")
            results += run_script(tlv(tag, value), card, tvr, tsi, True)
    tag91 = next((v for k, v in tags if k == "91"), None)
    print(f"  card       second GENERATE AC: {card.second_generate_ac(code.encode('ascii'), tag91)}")
    for tag, value in tags:
        if tag == "72":
            print("  terminal   tag 72: after the second GENERATE AC")
            results += run_script(tlv(tag, value), card, tvr, tsi, False)
    if results:
        print(f"  terminal   Issuer Script Results {h(results)}, TVR byte 5 {tvr[4]:02X}, TSI byte 1 {tsi[0]:02X}")
        issuer.script_results(PAN, results)
    print(f"  card now   PIN tries left {card.pin_tries}, days offline limit {h(card.data['C3'])}, "
          f"script commands done {card.script_counter}")


def fresh(atc=1) -> tuple[Card, Issuer]:
    # atc=1: the card has already made part 4's tap
    card = Card(*(card_master_key(k, PAN, PSN) for k in (IMK_AC, IMK_SMI, IMK_SMC)), atc=atc)
    issuer = Issuer(IMK_AC, IMK_SMI, IMK_SMC, {PAN: PSN})
    issuer.queue[PAN] = [("pin", "4821"), ("put", ("C3", x("0007")))]
    return card, issuer


def walk_through() -> None:
    card, issuer = fresh(atc=0)
    print("The PIN is blocked (0 tries left). The issuer queues a new PIN, 4821, and a days offline limit of 7.")
    transaction("1. part 4's tap, USD 25.00", card, issuer, 2500, "8A41C2F0", "261126", "071")
    transaction("2. card inserted, USD 40.00", card, issuer, 4000, "3C9B71E2", "261127", "051", verbose=True)
    print(f"  VERIFY 4821 -> {card.verify('4821')}")
    transaction("3. the next chip payment, USD 12.50", card, issuer, 1250, "51D0E7A4", "261128", "051")

    print("\nWhat goes wrong")

    card, issuer = fresh()
    transaction("1. the issuer MACs the script with the MK-AC instead of the MK-SMI", card, issuer, 4000, "3C9B71E2",
                "261127", "051", build=lambda *a: issuer.build_script(*a, imk_smi=IMK_AC))

    card, issuer = fresh()
    old = issuer.build_script(PAN, PSN, x("2007D63548109602"), issuer.queue[PAN])   # made for part 4's ARQC
    transaction("2. a script made for an earlier transaction", card, issuer, 4000, "3C9B71E2", "261127", "051",
                build=lambda *a: old)

    card, issuer = fresh()

    def drop_first(resp55: bytes) -> bytes:
        # A host that builds the MACs, then takes the PIN change back out of the script.
        out = b""
        for tag, value in tlv_list(resp55):
            if tag == "72":
                items = tlv_list(value)
                first = next(i for i, (t, _) in enumerate(items) if t == "86")
                value = b"".join(tlv(t, v) for t, v in items[:first] + items[first + 1:])
            out += tlv(tag, value)
        return out
    transaction("3. the PIN change taken out after the MACs were made", card, issuer, 4000, "3C9B71E2", "261127",
                "051", deliver=drop_first)

    card, issuer = fresh()
    iso0 = bytes(a ^ b for a, b in zip(x("044821FFFFFFFFFF"), x("0000173900101001")))   # ISO format 0 with the PAN
    issuer.queue[PAN] = [("pin-block", iso0), ("put", ("C3", x("0007")))]
    transaction("4. the new PIN sent as an online PIN block (ISO format 0)", card, issuer, 4000, "3C9B71E2",
                "261127", "051")

    card, issuer = fresh()
    issuer.queue[PAN].append(("record", ("0114", x("70") + bytes([94]) + bytes(94))))  # record 1 of SFI 2, 96 bytes
    transaction("5. a 96-byte UPDATE RECORD added to the same script", card, issuer, 4000, "3C9B71E2", "261127",
                "051")


# ================================================================ checking a script your host built

def check(args) -> int:
    try:
        template, arqc = x(args.check), x(args.arqc)
    except ValueError:
        print("--check and --arqc take hex")
        return 1
    pan, psn = args.pan, args.psn
    if len(arqc) != 8 or len(x(args.smi)) != 16 or len(x(args.smc)) != 16:
        print("the ARQC is 8 bytes and each key 16 (double-length Triple DES)")
        return 1
    sk_smi = session_key(card_master_key(x(args.smi), pan, psn), arqc)
    sk_smc = session_key(card_master_key(x(args.smc), pan, psn), arqc)
    try:
        outer = tlv_list(template)
    except ValueError as e:
        print(f"not a TLV template: {e}")
        return 1
    if len(outer) != 1 or outer[0][0] not in ("71", "72"):
        print("expected one tag 71 or 72 template")
        return 1
    print(f"tag {outer[0][0]}, {len(template)} bytes{' (over the 128 a terminal must take)' if len(template) > 128 else ''}")
    chain, ok = arqc, True
    for tag, value in tlv_list(outer[0][1]):
        if tag == "9F18":
            print(f"script identifier {h(value)}")
            continue
        if len(value) < 11:                             # header, Lc and at least 8E 04 + a 4-byte MAC
            print(f"{h(value)}\n  too short to be a secured command")
            ok = False
            continue
        header, body = value[:4], value[5:]
        data_object, mac_object = body[:-6], body[-6:]
        full = mac(sk_smi, mac_input(chain, header, data_object))
        good = mac_object[:2] == x("8E04") and hmac.compare_digest(full[:4], mac_object[2:])
        print(f"{h(value)}\n  MAC {h(mac_object[2:])}: {'matches' if good else 'expected ' + h(full[:4])}")
        if data_object[:2] == x("8711") and header[1] == 0x24 and not good:
            print("  PIN block not deciphered: with the MAC wrong, the keys or the ARQC are too")
        elif data_object[:2] == x("8711") and header[1] == 0x24:
            block = h(decipher(sk_smc, data_object[3:19]))
            n = int(block[1], 16)
            print(f"  PIN block: control {block[0]}, length {n}, digits {'*' * n}, "
                  f"filler {'all F' if set(block[2 + n:16]) == {'F'} else block[2 + n:16]}, padding {block[16:]}")
        ok &= good
        chain = full
    return 0 if ok else 1


if __name__ == "__main__":
    if len(sys.argv) == 1:
        walk_through()
        sys.exit(0)
    p = argparse.ArgumentParser(description="check an EMV issuer script (common core, Triple DES)")
    p.add_argument("--check", required=True, help="the tag 71 or 72 template, hex")
    p.add_argument("--arqc", required=True, help="the ARQC from the first GENERATE AC")
    p.add_argument("--pan", required=True)
    p.add_argument("--psn", default="00")
    p.add_argument("--smi", required=True, help="issuer master key for secure messaging integrity (TEST)")
    p.add_argument("--smc", required=True, help="issuer master key for secure messaging confidentiality (TEST)")
    sys.exit(check(p.parse_args()))
Scripts.cs
C#
// Send commands from the issuer to the card inside an authorisation response: EMV issuer scripts.
//
// Same card and the same test issuer key as parts 4 and 5. The card's offline PIN is blocked, so the issuer
// queues two commands for it: PIN CHANGE/UNBLOCK with a new PIN, and PUT DATA to change a limit. They ride
// back to the terminal in field 55 of the 0110, inside tag 72, and the terminal hands them to the card after
// the second GENERATE AC. The card only runs a command if its MAC checks out under the secure messaging key.
//
// What follows the specs (EMV Book 2 section 9 and Annex A1.3, Book 3 section 10.10, Book 4 section 6.3.9,
// and the Common Payment Application, chapter 18):
//   - session keys for secure messaging come from the card's MK-SMI and MK-SMC, diversified with the
//     ARQC of this transaction, so a script only works for the transaction it was made for
//   - Format 1: the command data travels in tag 81 (plain) or 87 (enciphered), the MAC in tag 8E (4 bytes)
//   - the MACs are chained: the first starts from the ARQC, each next one from the previous full MAC
//   - the new PIN block is enciphered with Triple DES in CBC mode under the encipherment session key
//
// Two ways to run it (.NET 10, TEST keys only, never a live issuer key):
//   dotnet run Scripts.cs                        the walk-through: a tap, a chip-and-PIN payment, then five ways it breaks
//   dotnet run Scripts.cs -- --check HEX --arqc HEX --pan PAN [--psn 01] --smi KEY --smc KEY
//                                                check a tag 71/72 script your host built: every MAC in the chain,
//                                                and the PIN block inside a PIN change (digits masked)
using System.Security.Cryptography;
using static Emv;

if (args.Length == 0)
{
    Walk.Through();
    return 0;
}
return Check.Run(args);

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

    // ============================================================ TLV, keeping order and repeats (a script has many 86s)

    public static byte[] Tlv(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 [.. X(tag), .. length, .. value];
    }

    public static List<(string Tag, byte[] Value)> TlvList(byte[] data)
    {
        var output = new List<(string, byte[])>();
        int i = 0;
        while (i < data.Length)
        {
            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($"ends inside tag {H(data[start..Math.Min(i, data.Length)])}");
            string tag = H(data[start..i]);
            int n = data[i++];
            if ((n & 0x80) != 0)                                // long form: 81 xx or 82 xx xx
            {
                int k = n & 0x7F;
                if (k is not (1 or 2) || i + k > data.Length)
                    throw new FormatException($"tag {tag} has a length byte {n:X2} that EMV doesn't use");
                n = k == 1 ? data[i] : data[i] << 8 | data[i + 1];
                i += k;
            }
            if (i + n > data.Length)
                throw new FormatException($"tag {tag} says {n} bytes, only {data.Length - i} are left");
            output.Add((tag, data[i..(i + n)]));
            i += n;
        }
        return output;
    }

    // ============================================================ cryptography (EMV Book 2, Annex A1)

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

    static byte[] Ecb3(byte[] key, byte[] block)
    {
        using var tdes = Tdes(key);
        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))];

    // Option A. Common core cards use Option B, which is Option A for any PAN of 16 digits or fewer.
    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)])]);
    }

    // Common session key derivation. R is the ATC + six 00s for the cryptogram key, the ARQC for the
    // secure messaging keys. Byte 3 of R is replaced by F0 for the left half and 0F for the right.
    public static byte[] SessionKey(byte[] mk, byte[] r) =>
        [.. Ecb3(mk, [r[0], r[1], 0xF0, .. r[3..8]]), .. Ecb3(mk, [r[0], r[1], 0x0F, .. r[3..8]])];

    static byte[] Pad(byte[] data) => [.. data, 0x80, .. new byte[(8 - (data.Length + 1) % 8) % 8]];

    // ISO 9797-1 MAC algorithm 3 with padding method 2: the full 8 bytes (scripts send the first 4).
    public static byte[] Mac(byte[] key, byte[] msg)
    {
        var padded = Pad(msg);
        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);
    }

    // Always padded, so the padding indicator is 01.
    public static byte[] Encipher(byte[] key, byte[] data)
    {
        using var tdes = Tdes(key);
        return tdes.EncryptCbc(Pad(data), new byte[8], PaddingMode.None);
    }

    public static byte[] Decipher(byte[] key, byte[] data)
    {
        using var tdes = Tdes(key);
        return tdes.DecryptCbc(data, new byte[8], PaddingMode.None);
    }

    // Format 1 follows ISO/IEC 7816-4: the header CLA INS P1 P2 padded to a full block, then the data object
    // with an odd tag (81 or 87). The chaining value goes in front as one more block.
    public static byte[] MacInput(byte[] chain, byte[] header, byte[] dataObject) =>
        [.. chain, .. header, 0x80, 0, 0, 0, .. dataObject];

    // Returns the command and its full MAC, which is the next command's chaining value.
    public static (byte[] Apdu, byte[] Full) SecureCommand(byte[] header, byte[] dataObject, byte[] skSmi, byte[] chain)
    {
        var full = Mac(skSmi, MacInput(chain, header, dataObject));
        byte[] body = [.. dataObject, 0x8E, 0x04, .. full[..4]];
        return ([.. header, (byte)body.Length, .. body], full);
    }

    // The chip's own plaintext PIN block: control 2, the PIN length, the digits, then F to fill 8 bytes.
    public static byte[] PinBlock(string pin) => X($"2{pin.Length:X}{pin}".PadRight(16, 'F'));

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

    public static byte[] Concat(IEnumerable<byte[]> parts) => [.. parts.SelectMany(p => p)];

    public static bool Same(byte[] a, byte[] b) => CryptographicOperations.FixedTimeEquals(a, b);

    public const string Pan = "4761739001010010", Psn = "01";
    public static readonly byte[] ImkAc = X("0123456789ABCDEF FEDCBA9876543210");    // part 4's TEST key
    public static readonly byte[] ImkSmi = X("89ABCDEF01234567 76543210FEDCBA98");   // TEST keys, made up for this post
    public static readonly byte[] ImkSmc = X("FEDCBA9876543210 0123456789ABCDEF");
}

// ================================================================ the card

// A common core card cut down to what scripts touch: the cryptogram, tag 91, and three script commands.
// Status words follow the Common Payment Application, chapter 18.
class Card(byte[] mkAc, byte[] mkSmi, byte[] mkSmc, int atc)
{
    int atc = atc;                                              // transactions so far
    string pin = "1234";
    public int PinTries { get; private set; } = 0;             // 0 tries left: the offline PIN is blocked
    const int PinTryLimit = 3;
    public Dictionary<string, byte[]> Data { get; } = new() { ["C3"] = X("0014") };   // Number of Days Offline Limit, n4: 14 days
    public int ScriptCounter { get; private set; }             // counts successful script commands, cyclic 0 to F
    byte[] arqc = [], skSmi = [], skSmc = [], chain = [];
    bool scriptFailed;

    public Dictionary<string, byte[]> GenerateAc(Dictionary<string, byte[]> terminal)
    {
        atc++;
        byte[] atcBytes = [(byte)(atc >> 8), (byte)atc];
        byte[] iad = [.. X("0F A5 01 A030000000"), .. new byte[8], 0x0F, .. new byte[15]];
        var t = new Dictionary<string, byte[]>(terminal) { ["82"] = X("1980"), ["9F36"] = atcBytes, ["9F10"] = iad };
        arqc = Mac(SessionKey(mkAc, [.. atcBytes, .. new byte[6]]), Concat(Signed.Select(tag => t[tag])));
        // The secure messaging keys for this transaction exist from this moment: R is the ARQC.
        (skSmi, skSmc, chain, scriptFailed) = (SessionKey(mkSmi, arqc), SessionKey(mkSmc, arqc), arqc, false);
        return new() { ["9F27"] = X("80"), ["9F36"] = atcBytes, ["9F26"] = arqc, ["9F10"] = iad, ["82"] = t["82"] };
    }

    public string SecondGenerateAc(string arc, byte[]? tag91)
    {
        var sk = SessionKey(mkAc, [(byte)(atc >> 8), (byte)atc, 0, 0, 0, 0, 0, 0]);
        bool genuine = tag91 is not null && Same(Mac(sk, [.. arqc, .. tag91[4..8]])[..4], tag91[..4]);
        return arc == "00" && genuine ? "TC (approved)" : "AAC (declined)";
    }

    public string Command(byte[] apdu)
    {
        if (scriptFailed)
            return "6982";                                      // after one failure, the rest of this transaction's script is refused
        var sw = Execute(apdu[..4], apdu[4], apdu[5..]);
        if (sw[..2] is not ("90" or "62" or "63"))
            scriptFailed = true;
        return sw;
    }

    string Execute(byte[] header, int lc, byte[] body)
    {
        var (cla, ins, p1, p2) = (header[0], header[1], header[2], header[3]);
        if (body.Length != lc || body.Length < 6)
            return "6700";
        var (dataObject, macObject) = (body[..^6], body[^6..]);
        if (macObject[0] != 0x8E || macObject[1] != 0x04)
            return "6987";                                      // expected secure messaging data objects missing
        var full = Mac(skSmi, MacInput(chain, header, dataObject));
        if (!Same(full[..4], macObject[2..]))
            return "6982";                                      // security status not satisfied: wrong key, wrong transaction or a gap
        chain = full;

        if ((cla, ins, p1, p2) == (0x8C, 0x24, 0x00, 0x02))       // PIN CHANGE/UNBLOCK, change the PIN
        {
            if (lc != 0x19 || H(dataObject[..3]) != "871101")
                return "6988";
            string digits = H(Decipher(skSmc, dataObject[3..19])[..8]);
            int n = Convert.ToInt32(digits[1..2], 16);
            if (digits[0] != '2' || n is < 4 or > 12 || !digits[2..(2 + n)].All(char.IsAsciiDigit) || digits[(2 + n)..].Any(c => c != 'F'))
                return "6988";                                  // MAC fine, but the PIN block isn't in the chip's format
            (pin, PinTries) = (digits[2..(2 + n)], PinTryLimit);
        }
        else if ((cla, ins, p1, p2) == (0x8C, 0x24, 0x00, 0x00))  // PIN CHANGE/UNBLOCK, unblock only
            PinTries = PinTryLimit;
        else if ((cla, ins) == (0x0C, 0xDA))                      // PUT DATA, P1 P2 = the tag
        {
            string tag = p1 == 0 ? $"{p2:X2}" : $"{p1:X2}{p2:X2}";
            if (dataObject.Length == 0 || dataObject[0] != 0x81)
                return "6987";
            if (!Data.TryGetValue(tag, out var old))
                return "6A86";
            var value = dataObject[2..];
            if (value.Length > old.Length)
                return "6700";
            Data[tag] = value;
        }
        else
            return "6A81";                                      // MAC fine, command not supported here
        ScriptCounter = (ScriptCounter + 1) % 16;
        return "9000";
    }

    public string Verify(string attempt)
    {
        if (PinTries == 0)
            return "6983";                                      // PIN blocked
        if (Same(System.Text.Encoding.ASCII.GetBytes(attempt), System.Text.Encoding.ASCII.GetBytes(pin)))
        {
            PinTries = PinTryLimit;
            return "9000";
        }
        PinTries--;
        return $"63C{PinTries:X}";                              // wrong, this many tries left
    }
}

// ================================================================ the issuer

// One queued command: "pin" (a new PIN), "pin-block" (a ready-made block), "put" (PUT DATA) or "record" (UPDATE RECORD).
record Cmd(string Kind, string Text = "", byte[]? Bytes = null);

delegate byte[] ScriptBuilder(string pan, string psn, byte[] arqc, List<Cmd> commands);

class Issuer(byte[] imkAc, byte[] imkSmi, byte[] imkSmc, Dictionary<string, string> cards)
{
    static readonly byte[] Approve = X("00820000");             // card status update, as in part 4
    public Dictionary<string, List<Cmd>> Queue { get; } = [];   // PAN -> commands waiting for a transaction that can carry them
    int nextScriptId = 0xA001;

    public (string Code, byte[] Response, string Why) Authorise(string pan, string entryMode, byte[] f55, ScriptBuilder? build = null)
    {
        var t = TlvList(f55).ToDictionary(e => e.Tag, e => e.Value);
        string psn = cards[pan];
        var sk = SessionKey(CardMasterKey(imkAc, pan, psn), [.. t["9F36"], .. new byte[6]]);
        if (!Same(Mac(sk, Concat(Signed.Select(tag => t[tag]))), t["9F26"]))
            return ("05", [], "cryptogram doesn't match");
        byte[] output = Tlv("91", [.. Mac(sk, [.. t["9F26"], .. Approve])[..4], .. Approve]);
        if (!Queue.TryGetValue(pan, out var commands) || commands.Count == 0)
            return ("00", output, "approved");
        // A tap is over before the answer arrives. Kernel 3 can deliver a script when the card is presented
        // a second time, if card and reader both support it. This host doesn't count on that and waits for
        // a contact transaction (field 22 starting 05).
        if (!entryMode.StartsWith("05"))
            return ("00", output, $"approved; {commands.Count} script command(s) held: field 22 is {entryMode}, a tap");
        var script = (build ?? ((p, s, a, c) => BuildScript(p, s, a, c)))(pan, psn, t["9F26"], commands);
        return ("00", [.. output, .. script], $"approved, with a {script.Length}-byte script in tag 72");
    }

    public byte[] BuildScript(string pan, string psn, byte[] arqc, List<Cmd> commands, byte[]? smiKey = null)
    {
        var skSmi = SessionKey(CardMasterKey(smiKey ?? imkSmi, pan, psn), arqc);
        var skSmc = SessionKey(CardMasterKey(imkSmc, pan, psn), arqc);
        var chain = arqc;
        var apdus = new List<byte[]>();
        foreach (var c in commands)
        {
            var (header, dataObject) = c.Kind switch
            {
                "pin" => (X("8C240002"), Tlv("87", [0x01, .. Encipher(skSmc, PinBlock(c.Text))])),
                "pin-block" => (X("8C240002"), Tlv("87", [0x01, .. Encipher(skSmc, c.Bytes!)])),   // a ready-made 8-byte block, for case 4
                "put" => (X("0CDA" + c.Text.PadLeft(4, '0')), Tlv("81", c.Bytes!)),
                _ => (X("0CDC" + c.Text), Tlv("81", c.Bytes!)),                                    // "record": P1 P2 given
            };
            (var apdu, chain) = SecureCommand(header, dataObject, skSmi, chain);
            apdus.Add(apdu);
        }
        byte[] scriptId = [(byte)(nextScriptId >> 24), (byte)(nextScriptId >> 16), (byte)(nextScriptId >> 8), (byte)nextScriptId];
        nextScriptId++;
        return Tlv("72", [.. Tlv("9F18", scriptId), .. Concat(apdus.Select(a => Tlv("86", a)))]);
    }

    // Issuer Script Results come back in the clearing record or the next message. Only a clean
    // result clears the queue; anything else, and the commands go out again next time.
    public void ScriptResults(string pan, byte[] results)
    {
        if (results[0] == 0x20)
            Queue.Remove(pan);
    }
}

// ================================================================ the terminal

static class Walk
{
    // Book 3 section 10.10 and Book 4 section 6.3.9. Returns 5 bytes of Issuer Script Results.
    static byte[] RunScript(byte[] template, Card card, byte[] tvr, byte[] tsi, bool beforeFinal)
    {
        byte tagBit = (byte)(beforeFinal ? 0x20 : 0x10);        // TVR byte 5: failed before / after final GENERATE AC
        if (template.Length > 128)
        {
            // Book 4: a terminal must take scripts up to 128 bytes in total. Over that, report it not performed.
            var inner = TlvList(TlvList(template)[0].Value);
            var id = inner.FirstOrDefault(e => e.Tag == "9F18").Value ?? new byte[4];
            Console.WriteLine($"    script is {template.Length} bytes, over the 128 this terminal takes: nothing sent");
            return [0x00, .. id];
        }
        List<(string Tag, byte[] Value)> items;
        try
        {
            items = TlvList(TlvList(template)[0].Value);
        }
        catch (FormatException e)
        {
            Console.WriteLine($"    script doesn't parse ({e.Message}): nothing sent");
            tsi[0] |= 0x04;
            tvr[4] |= tagBit;
            return new byte[5];
        }
        var sid = items.FirstOrDefault(e => e.Tag == "9F18").Value ?? new byte[4];
        tsi[0] |= 0x04;                                          // TSI byte 1: script processing was performed
        int n = 0;
        foreach (var (_, apdu) in items.Where(e => e.Tag == "86"))
        {
            n++;
            var sw = card.Command(apdu);
            Console.WriteLine($"    {n}. {H(apdu)}  ->  {sw}");
            if (sw[..2] is not ("90" or "62" or "63"))           // only SW1 counts: 90 normal, 62 and 63 warnings
            {
                tvr[4] |= tagBit;
                return [(byte)(0x10 | Math.Min(n, 15)), .. sid];  // failed, at command n
            }
        }
        return [0x20, .. sid];
    }

    static void Transaction(string title, Card card, Issuer issuer, long amountCents, string un, string date, string entryMode,
                            ScriptBuilder? build = null, Func<byte[], byte[]>? deliver = null, bool verbose = false)
    {
        Console.WriteLine($"\n{title}");
        var tvr = X(entryMode.StartsWith("05") ? "0000200000" : "0000008000");   // 05x: PIN try limit exceeded
        var tsi = new byte[2];
        var t = new Dictionary<string, byte[]>
        {
            ["9F02"] = X(amountCents.ToString("D12")), ["9F03"] = new byte[6], ["9F1A"] = X("0840"), ["95"] = [.. tvr],
            ["5F2A"] = X("0840"), ["9A"] = X(date), ["9C"] = X("00"), ["9F37"] = X(un),
        };
        foreach (var (k, v) in card.GenerateAc(t))
            t[k] = v;
        Console.WriteLine($"  card       ATC {H(t["9F36"])}, ARQC {H(t["9F26"])}");
        var f55 = Concat(new[] { "9F26", "9F27", "9F10", "9F37", "9F36", "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03" }
                         .Select(tag => Tlv(tag, t[tag])));
        var (code, resp55, why) = issuer.Authorise(Pan, entryMode, f55, build);
        Console.WriteLine($"  issuer     {why}");
        if (!entryMode.StartsWith("05"))
        {
            Console.WriteLine("  terminal   a tap: the card left the field before the answer came, so tag 91 stays with the terminal");
            return;
        }
        if (deliver is not null)
            resp55 = deliver(resp55);
        var tags = TlvList(resp55);
        if (verbose && tags.Count > 1)
        {
            Console.WriteLine($"  field 55 of the 0110, {resp55.Length} bytes:");
            foreach (var (tag, value) in tags)
            {
                var whole = H(Tlv(tag, value));
                Console.WriteLine($"    {whole[..tag.Length]} {whole[tag.Length..(tag.Length + 2)]} {whole[(tag.Length + 2)..]}");
            }
            var skSmi = SessionKey(CardMasterKey(ImkSmi, Pan, Psn), t["9F26"]);
            var skSmc = SessionKey(CardMasterKey(ImkSmc, Pan, Psn), t["9F26"]);
            Console.WriteLine($"  this transaction's secure messaging keys (R = the ARQC):\n    MAC        {H(skSmi)}\n    encipher   {H(skSmc)}");
        }
        byte[] results = [];
        foreach (var (tag, value) in tags.Where(e => e.Tag == "71"))
        {
            Console.WriteLine("  terminal   tag 71: before the second GENERATE AC");
            results = [.. results, .. RunScript(Tlv(tag, value), card, tvr, tsi, true)];
        }
        var tag91 = tags.FirstOrDefault(e => e.Tag == "91").Value;
        Console.WriteLine($"  card       second GENERATE AC: {card.SecondGenerateAc(code, tag91)}");
        foreach (var (tag, value) in tags.Where(e => e.Tag == "72"))
        {
            Console.WriteLine("  terminal   tag 72: after the second GENERATE AC");
            results = [.. results, .. RunScript(Tlv(tag, value), card, tvr, tsi, false)];
        }
        if (results.Length > 0)
        {
            Console.WriteLine($"  terminal   Issuer Script Results {H(results)}, TVR byte 5 {tvr[4]:X2}, TSI byte 1 {tsi[0]:X2}");
            issuer.ScriptResults(Pan, results);
        }
        Console.WriteLine($"  card now   PIN tries left {card.PinTries}, days offline limit {H(card.Data["C3"])}, script commands done {card.ScriptCounter}");
    }

    // atc=1: the card has already made part 4's tap
    static (Card, Issuer) Fresh(int atc = 1)
    {
        var card = new Card(CardMasterKey(ImkAc, Pan, Psn), CardMasterKey(ImkSmi, Pan, Psn), CardMasterKey(ImkSmc, Pan, Psn), atc);
        var issuer = new Issuer(ImkAc, ImkSmi, ImkSmc, new() { [Pan] = Psn });
        issuer.Queue[Pan] = [new("pin", "4821"), new("put", "C3", X("0007"))];
        return (card, issuer);
    }

    public static void Through()
    {
        var (card, issuer) = Fresh(atc: 0);
        Console.WriteLine("The PIN is blocked (0 tries left). The issuer queues a new PIN, 4821, and a days offline limit of 7.");
        Transaction("1. part 4's tap, USD 25.00", card, issuer, 2500, "8A41C2F0", "261126", "071");
        Transaction("2. card inserted, USD 40.00", card, issuer, 4000, "3C9B71E2", "261127", "051", verbose: true);
        Console.WriteLine($"  VERIFY 4821 -> {card.Verify("4821")}");
        Transaction("3. the next chip payment, USD 12.50", card, issuer, 1250, "51D0E7A4", "261128", "051");

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

        (card, issuer) = Fresh();
        var iss1 = issuer;
        Transaction("1. the issuer MACs the script with the MK-AC instead of the MK-SMI", card, issuer, 4000, "3C9B71E2",
                    "261127", "051", build: (p, s, a, c) => iss1.BuildScript(p, s, a, c, smiKey: ImkAc));

        (card, issuer) = Fresh();
        var old = issuer.BuildScript(Pan, Psn, X("2007D63548109602"), issuer.Queue[Pan]);   // made for part 4's ARQC
        Transaction("2. a script made for an earlier transaction", card, issuer, 4000, "3C9B71E2", "261127", "051",
                    build: (_, _, _, _) => old);

        // A host that builds the MACs, then takes the PIN change back out of the script.
        static byte[] DropFirst(byte[] resp55)
        {
            byte[] output = [];
            foreach (var (tag, value) in TlvList(resp55))
            {
                var v = value;
                if (tag == "72")
                {
                    var items = TlvList(value);
                    int first = items.FindIndex(e => e.Tag == "86");
                    items.RemoveAt(first);
                    v = Concat(items.Select(e => Tlv(e.Tag, e.Value)));
                }
                output = [.. output, .. Tlv(tag, v)];
            }
            return output;
        }
        (card, issuer) = Fresh();
        Transaction("3. the PIN change taken out after the MACs were made", card, issuer, 4000, "3C9B71E2", "261127",
                    "051", deliver: DropFirst);

        (card, issuer) = Fresh();
        byte[] iso0 = [.. X("044821FFFFFFFFFF").Zip(X("0000173900101001"), (a, b) => (byte)(a ^ b))];   // ISO format 0 with the PAN
        issuer.Queue[Pan] = [new("pin-block", Bytes: iso0), new("put", "C3", X("0007"))];
        Transaction("4. the new PIN sent as an online PIN block (ISO format 0)", card, issuer, 4000, "3C9B71E2",
                    "261127", "051");

        (card, issuer) = Fresh();
        issuer.Queue[Pan].Add(new("record", "0114", [0x70, 94, .. new byte[94]]));   // record 1 of SFI 2, 96 bytes
        Transaction("5. a 96-byte UPDATE RECORD added to the same script", card, issuer, 4000, "3C9B71E2", "261127",
                    "051");
    }
}

// ================================================================ checking a script your host built

static class Check
{
    public static int Run(string[] args)
    {
        var a = new Dictionary<string, string> { ["--psn"] = "00" };
        for (int i = 0; i + 1 < args.Length; i += 2)
            a[args[i]] = args[i + 1];
        foreach (var need in new[] { "--check", "--arqc", "--pan", "--smi", "--smc" })
            if (!a.ContainsKey(need))
            {
                Console.WriteLine("usage: --check HEX --arqc HEX --pan PAN [--psn 01] --smi KEY --smc KEY");
                return 2;
            }
        byte[] template, arqc;
        try
        {
            (template, arqc) = (X(a["--check"]), X(a["--arqc"]));
        }
        catch (FormatException)
        {
            Console.WriteLine("--check and --arqc take hex");
            return 1;
        }
        string pan = a["--pan"], psn = a["--psn"];
        if (arqc.Length != 8 || X(a["--smi"]).Length != 16 || X(a["--smc"]).Length != 16)
        {
            Console.WriteLine("the ARQC is 8 bytes and each key 16 (double-length Triple DES)");
            return 1;
        }
        var skSmi = SessionKey(CardMasterKey(X(a["--smi"]), pan, psn), arqc);
        var skSmc = SessionKey(CardMasterKey(X(a["--smc"]), pan, psn), arqc);
        List<(string Tag, byte[] Value)> outer;
        try
        {
            outer = TlvList(template);
        }
        catch (FormatException e)
        {
            Console.WriteLine($"not a TLV template: {e.Message}");
            return 1;
        }
        if (outer.Count != 1 || outer[0].Tag is not ("71" or "72"))
        {
            Console.WriteLine("expected one tag 71 or 72 template");
            return 1;
        }
        Console.WriteLine($"tag {outer[0].Tag}, {template.Length} bytes{(template.Length > 128 ? " (over the 128 a terminal must take)" : "")}");
        var chain = arqc;
        bool ok = true;
        foreach (var (tag, value) in TlvList(outer[0].Value))
        {
            if (tag == "9F18")
            {
                Console.WriteLine($"script identifier {H(value)}");
                continue;
            }
            if (value.Length < 11)                              // header, Lc and at least 8E 04 + a 4-byte MAC
            {
                Console.WriteLine($"{H(value)}\n  too short to be a secured command");
                ok = false;
                continue;
            }
            var (header, body) = (value[..4], value[5..]);
            var (dataObject, macObject) = (body[..^6], body[^6..]);
            var full = Mac(skSmi, MacInput(chain, header, dataObject));
            bool good = macObject[0] == 0x8E && macObject[1] == 0x04 && Same(full[..4], macObject[2..]);
            Console.WriteLine($"{H(value)}\n  MAC {H(macObject[2..])}: {(good ? "matches" : "expected " + H(full[..4]))}");
            bool pinChange = dataObject.Length >= 19 && dataObject[0] == 0x87 && dataObject[1] == 0x11 && header[1] == 0x24;
            if (pinChange && !good)
                Console.WriteLine("  PIN block not deciphered: with the MAC wrong, the keys or the ARQC are too");
            else if (pinChange)
            {
                string block = H(Decipher(skSmc, dataObject[3..19]));
                int n = Convert.ToInt32(block[1..2], 16);
                string filler = block[(2 + n)..16];
                Console.WriteLine($"  PIN block: control {block[0]}, length {n}, digits {new string('*', n)}, " +
                                  $"filler {(filler.Length > 0 && filler.All(c => c == 'F') ? "all F" : filler)}, padding {block[16..]}");
            }
            ok &= good;
            chain = full;
        }
        return ok ? 0 : 1;
    }
}