Part 3 of a series on how chip cards are made. Part 1 covered what personalisation is, and part 2 the handshake between the chip and the bureau's machine.

The first two parts stayed inside the card bureau. This one moves to the shop counter.

A terminal at a market stall loses its network. A customer inserts a card. The terminal can't ask the bank anything, but it still has to decide whether the chip in front of it is genuine or a copy someone made last night.

It does this with three digital signatures, each one inside the next. EMV Book 2 describes the whole scheme, and it's precise enough to build from. So that's what this post does: a short script, in Python and in C#, that creates a test chain the way a scheme, a bank and a card bureau would, then checks it the way a terminal does. It uses no crypto libraries at all, just Python's built-in pow() and hashlib (or BigInteger.ModPow and SHA1 in C#), so every byte is visible. The snippets below are in Python, with the C# version folded under each one.

You don't need to read the code to follow along. Each step explains the idea first.

The problem the terminal has

When a terminal is online, the bank does the hard work. The chip produces a cryptogram, the bank checks it with keys only it holds, and the bank answers.

Offline, there's nobody to ask. The terminal has two sources of information: what's stored in the terminal, and what the card hands over. Anything the card hands over could have been copied from another card.

So the card has to prove two things on its own:

  1. Its data was written by a real bank and hasn't been changed since.
  2. It's the chip that data was written to, not a copy.

EMV calls this offline data authentication. There are three versions of it, SDA, DDA and CDA, and they differ in how much of that proof they give. All three use the same chain.

The chain

The EMV chain of trust: the terminal holds the scheme CA's public key; it opens the issuer certificate (tag 90), which gives the bank's public key; that opens the chip's certificate (tag 9F46), which gives the chip's public key; that checks the chip's fresh signature (tag 9F4B) over the terminal's random number
Output
Terminal stores:   CA public key  (found by RID + index 8F)
                        โ”‚ opens
                        โ–ผ
Card carries:      Issuer certificate (90)        โ†’  bank's public key
                        โ”‚ opens
                        โ–ผ
                   ICC certificate (9F46)         โ†’  chip's public key
                        โ”‚ checks
                        โ–ผ
                   Signature made just now (9F4B) โ†’  "this chip is here"

The terminal stores very little: a few public keys for each card scheme, belonging to the scheme's certificate authority (CA). Book 2 asks terminals to hold at least six per scheme (section 11.2.2). Everything else comes from the card, and each layer proves the next.

That's why a terminal in Lagos doesn't need to know anything about your bank. It trusts the scheme, the scheme vouches for the bank, and the bank vouches for the chip.

Step 1: RSA, briefly

Every signature in the chain is RSA. An RSA key is two numbers: a modulus n, which is the product of two large secret primes, and an exponent e. Signing a number x is x^d mod n, using the private exponent d. Checking it is x^e mod n, using the public one.

Python
# chain.py: make_key()
def make_key(bits, e=65537):
    """A TEST RSA key pair. EMV allows only two public exponents: 3 or 2^16 + 1 (Book 2 6.1)."""
    p, q = random_prime(bits // 2, e), random_prime(bits // 2, e)
    n = p * q
    d = pow(e, -1, (p - 1) * (q - 1))   # the private exponent: the inverse of e
    return {"n": n, "e": e, "d": d, "size": bits // 8}
The same in C#
C#
// Chain.cs: MakeKey()
// A TEST RSA key pair. EMV allows only two public exponents: 3 or 2^16 + 1 (Book 2 6.1).
static RsaKey MakeKey(int bits, int e = 65537)
{
    BigInteger p = RandomPrime(bits / 2, e), q = RandomPrime(bits / 2, e);
    return new RsaKey(p * q, e, ModInverse(e, (p - 1) * (q - 1)), bits / 8); // d: the inverse of e
}

random_prime draws random odd numbers and tests each with Miller-Rabin until one is prime. Making all three keys takes about half a second.

Why no crypto library?

EMV uses raw RSA with its own block format on top, not the standard padding schemes (PKCS#1 or PSS) that libraries are built around. Most libraries discourage raw RSA, for good reasons in general, so you end up working against the API. Here it's one call to pow() (BigInteger.ModPow in C#), and nothing is hidden.

Step 2: a signature that carries its message

A normal signature sits next to the message it signs. EMV's signatures work differently: the signature contains most of the message. When the terminal checks it, the message comes back out. Book 2 calls this a digital signature scheme giving message recovery (Annex A2.1, based on ISO/IEC 9796-2).

Python
# chain.py: sign() and recover()
def sign(key, message):
    n_bytes = key["size"]
    msg1 = message[: n_bytes - 22]                       # the part that goes inside
    block = b"\x6A" + msg1 + sha1(message) + b"\xBC"     # header 6A, data, 20-byte hash, trailer BC
    return to_bytes(pow(int.from_bytes(block, "big"), key["d"], key["n"]), n_bytes)

def recover(key, signature):
    """What the terminal does: one public-key operation, then read the block."""
    return to_bytes(pow(int.from_bytes(signature, "big"), key["e"], key["n"]), key["size"])
The same in C#
C#
// Chain.cs: Sign() and Recover()
static byte[] Sign(RsaKey key, byte[] message)
{
    byte[] msg1 = message[..(key.Size - 22)];                // the part that goes inside
    byte[] block = [0x6A, .. msg1, .. Sha1(message), 0xBC];  // header 6A, data, 20-byte hash, trailer BC
    return ToBytes(BigInteger.ModPow(Num(block), key.D, key.N), key.Size);
}

// What the terminal does: one public-key operation, then read the block.
static byte[] Recover(RsaKey key, byte[] signature) =>
    ToBytes(BigInteger.ModPow(Num(signature), key.E, key.N), key.Size);

The block is exactly the length of the key: one header byte (6A), as much of the message as fits, a 20-byte SHA-1 hash of the whole message, and one trailer byte (BC). That's 22 bytes of overhead, which is why N โˆ’ 22 appears throughout Book 2.

This has a useful side effect. Open a signature with the wrong key and you get noise back, and noise almost never starts with 6A and ends with BC. Those two bytes tell the terminal straight away whether it used the right key.

Step 3: the issuer certificate (tag 90)

The first layer comes from the card scheme. The bank generates an RSA key pair in its hardware security module (HSM) and sends the public half to the scheme in a certification request. The scheme's CA signs it and sends back a response, and the certificate in that response goes on every card in the programme as tag 90.

What the CA signs is laid out in Book 2, Table 10:

Python
# chain.py: issuer_certificate()
def issuer_certificate(ca, issuer, iin, expiry_mmyy, serial):
    leftmost, remainder = split_modulus(modulus(issuer), ca["size"] - 36)
    exp = exponent_bytes(issuer["e"])
    data = (b"\x02"                  # certificate format: issuer
            + pad_f(iin, 4)          # the bank's card number prefix, e.g. 476173FF
            + bcd(expiry_mmyy)       # valid until the end of this month
            + serial                 # chosen by the CA
            + b"\x01" + b"\x01"      # SHA-1, RSA
            + bytes([issuer["size"], len(exp)])
            + leftmost + remainder + exp)
    return {"90": sign(ca, data), "92": remainder, "9F32": exp}
The same in C#
C#
// Chain.cs: IssuerCertificate()
static (byte[] Cert, byte[] Remainder, byte[] Exponent) IssuerCertificate(
    RsaKey ca, RsaKey issuer, string iin, string expiryMmyy, byte[] serial)
{
    var (leftmost, remainder) = SplitModulus(ToBytes(issuer.N, issuer.Size), ca.Size - 36);
    byte[] exp = ExponentBytes(issuer.E);
    byte[] data = [0x02,                                   // certificate format: issuer
                   .. PadF(iin, 4),                        // the bank's card number prefix, e.g. 476173FF
                   .. Convert.FromHexString(expiryMmyy),   // valid until the end of this month
                   .. serial,                              // chosen by the CA
                   0x01, 0x01,                             // SHA-1, RSA
                   (byte)issuer.Size, (byte)exp.Length,
                   .. leftmost, .. remainder, .. exp];
    return (Sign(ca, data), remainder, exp);               // tags 90, 92, 9F32
}

The remainder, and why tag 92 exists

The certificate is the same length as the CA's key, and after the 22 bytes of signature overhead and 14 bytes of certificate fields, there's room for NCA โˆ’ 36 bytes of the bank's key (Book 2, section 6.1).

If the bank's key is longer than that, the part that doesn't fit, the remainder, goes on the card separately as tag 92, with the key's exponent as 9F32. The hash inside the certificate covers both, so neither can be swapped.

The script uses a common pair of sizes: a 1408-bit CA key (176 bytes) and a 1152-bit bank key (144 bytes). 176 โˆ’ 36 = 140, so 4 bytes don't fit:

Output
  90   issuer certificate  176 bytes
  92   issuer remainder    4 bytes  (1152-bit key, room for 140 bytes)

So the scheme's response gives the bank four values to personalise: 8F (which CA key signed it), 90, 92 and 9F32. Leave out 92 and every card in the programme fails, as step 7 shows.

The certificate also has an expiry date, and so does the CA key that signed it. Banks need to request the next certificate well before the current one runs out.

Step 4: the chip's certificate (tag 9F46)

The second layer comes from data preparation. For each card, the bank's HSM generates a key pair for the chip and signs the chip's public key with the bank's private key. The result is the ICC certificate, tag 9F46 (Book 2, Table 11), with the chip's exponent in 9F47 and any remainder in 9F48. The chip's private key goes into the chip, encrypted for that chip alone, the way part 2 described.

Two things set it apart from the issuer certificate:

  • It names one card: it carries the full card number (PAN) instead of a prefix.
  • Its hash also covers the card's data: the records the terminal reads and the card's AFL marks for authentication.
Python
# chain.py: icc_certificate()
data = (b"\x04" + pad_f(pan, 10) + bcd(expiry_mmyy) + serial
        + b"\x01" + b"\x01" + bytes([icc["size"], len(exp)]) + leftmost + remainder + exp
        + static_data)   # the signed records are in the hash: change one byte and this cert breaks
The same in C#
C#
// Chain.cs: IccCertificate()
byte[] data = [0x04, .. PadF(pan, 10), .. Convert.FromHexString(expiryMmyy), .. serial,
               0x01, 0x01, (byte)icc.Size, (byte)exp.Length, .. leftmost, .. remainder, .. exp,
               .. staticData];  // the signed records are in the hash: change one byte and this cert breaks

That last line matters more than it looks. The certificate doesn't just say "this key belongs to card 4761โ€ฆ". It says "this key belongs to the card with exactly this data on it". Change the expiry date, the card number or a risk setting in those records after the certificate is made, and the certificate no longer checks out.

The room here is NI โˆ’ 42 bytes: the bank key's length, minus 22 bytes of overhead, minus 20 bytes of fields. A 768-bit chip key is 96 bytes and the room is 102, so it fits whole and 9F48 stays empty.

Step 5: the live signature, and SDA vs DDA vs CDA

Everything so far is static: signed once, at the bank or the bureau, and copied onto the card. Static data has a basic weakness. Anyone who can read it can copy it. A cloned chip loaded with a genuine card's certificates would pass every check up to this point.

The fix is to have the chip sign something new on every payment. The terminal sends a random number, the Unpredictable Number (tag 9F37), which Book 2 requires in the data the chip signs (section 6.5.1). The chip signs it with its private key, which never leaves the chip:

Python
# chain.py: chip_signs(): Book 2 Table 15
def chip_signs(icc, icc_dynamic_number, terminal_data):
    dyn = bytes([len(icc_dynamic_number)]) + icc_dynamic_number
    data = (b"\x05" + b"\x01" + bytes([len(dyn)]) + dyn
            + b"\xBB" * (icc["size"] - len(dyn) - 25)   # padding up to the key's size
            + terminal_data)                             # the terminal's random number
    return sign(icc, data)
The same in C#
C#
// Chain.cs: ChipSigns(): Book 2 Table 15
static byte[] ChipSigns(RsaKey icc, byte[] iccDynamicNumber, byte[] terminalData)
{
    byte[] dyn = [(byte)iccDynamicNumber.Length, .. iccDynamicNumber];
    byte[] data = [0x05, 0x01, (byte)dyn.Length, .. dyn,
                   .. Enumerable.Repeat((byte)0xBB, icc.Size - dyn.Length - 25), // padding up to the key's size
                   .. terminalData];                                            // the terminal's random number
    return Sign(icc, data);
}

A copy of the card's data doesn't include the chip's private key, so a clone can't produce this signature. This is where the three methods differ:

MethodWhat the card provesLimit
SDA (static)The bank signed this data. One signature, tag 93, the same on every paymentCopyable: a clone passes
DDA (dynamic)The bank signed this data, and this chip holds the private key right nowThe signature is separate from the payment's cryptogram
CDA (combined)Everything DDA proves, and the signature also covers the cryptogram for this payment (Book 2, section 6.6)The strongest of the three

Terminals use the strongest method both they and the card support (Book 3, section 10.3).

Why CDA exists

With DDA, the chip proves it's genuine in one step and gives its answer for the payment, the cryptogram, in another. A device sitting between the card and the terminal could let the genuine proof through and then tamper with the answer that follows. CDA closes that gap by putting the cryptogram inside the signature, so the terminal knows the answer came from the same chip that passed.

The three layers opened, byte by byte. Tag 90, the issuer certificate opened with the scheme's CA key: 6A, 02, 476173FF, 1229, 000001, the bank's public key, SHA-1, BC. The bank's key opens tag 9F46, the ICC certificate: 6A, 04, the full card number, 1228, the chip's public key, SHA-1, BC. The chip's key checks tag 9F4B, the signature made just now: 6A, 05, 01, the chip's dynamic number, BB padding, SHA-1, BC.
What the terminal reads after opening each layer: every certificate gives up the key that opens the next one.

Step 6: the terminal's side

The verifier follows Book 2, sections 6.2 to 6.5, in order. Here's the first layer:

Python
# chain.py: verify(), first layer
# 6.2: find the CA key from the RID (first 5 bytes of the AID) and the index in tag 8F.
ca = terminal_ca_keys.get((card["RID"], card["8F"]))
check(ca is not None, f"no CA key {card['RID']}/{card['8F']} in this terminal")

# 6.3: open the issuer certificate with the CA key.
block = recover(ca, card["90"])
check(block[-1] == 0xBC, "issuer certificate: trailer is not BC (wrong CA key?)")
check(block[0] == 0x6A, "issuer certificate: header is not 6A")
check(block[1] == 0x02, "issuer certificate: format is not 02")
body, recovered_hash = block[1:-21], block[-21:-1]
check(sha1(body + card["92"] + card["9F32"]) == recovered_hash, "issuer certificate: hash mismatch")
iin = body[1:5].hex().upper().rstrip("F")
check(card["5A"].startswith(iin), "issuer identifier doesn't match the PAN")
check(not expired(body[5:7].hex(), today), f"issuer certificate expired {body[5:7].hex()}")
The same in C#
C#
// Chain.cs: Verify(), first layer
// 6.2: find the CA key from the RID (first 5 bytes of the AID) and the index in tag 8F.
Check(terminalCaKeys.TryGetValue((card.Rid, card.Index), out var ca), $"no CA key {card.Rid}/{card.Index} in this terminal");

// 6.3: open the issuer certificate with the CA key.
byte[] block = Recover(ca!, card.IssuerCert);
Check(block[^1] == 0xBC, "issuer certificate: trailer is not BC (wrong CA key?)");
Check(block[0] == 0x6A, "issuer certificate: header is not 6A");
Check(block[1] == 0x02, "issuer certificate: format is not 02");
byte[] body = block[1..^21], recoveredHash = block[^21..^1];
Check(Sha1(body, card.IssuerRemainder, card.IssuerExponent).SequenceEqual(recoveredHash), "issuer certificate: hash mismatch");
string iin = Hex(body[1..5]).TrimEnd('F');
Check(card.Pan.StartsWith(iin), "issuer identifier doesn't match the PAN");
Check(!Expired(Hex(body[5..7]), today), $"issuer certificate expired {Hex(body[5..7])}");

The bank's public key is then the part recovered from inside the certificate, joined to the remainder from 92. The chip's certificate and the live signature are checked the same way, each with the key the layer above just produced.

Every check either passes or ends offline authentication on the spot. There's no partial credit.

Step 7: breaking it on purpose

This is the part I enjoyed most. A chain like this is easiest to understand by watching it fail. The script builds one good card, then damages it in five ways:

Output
The terminal checks:
  genuine card                           DDA passed
  terminal lacks the CA key              FAILED: no CA key A000000003/7F in this terminal
  issuer remainder (92) missing          FAILED: issuer certificate: hash mismatch
  one signed record byte changed         FAILED: ICC certificate: hash mismatch (signed records changed?)
  same card, January 2030                FAILED: issuer certificate expired 1229
  replayed signature, new random number  FAILED: dynamic signature: hash mismatch

Four of these five aren't attacks. They're the kind of data mistakes that happen while a card programme is being set up, and the cryptography is unforgiving about them:

  • The terminal lacks the CA key. Schemes retire CA keys on published dates, and acquirers remove them from terminals (Book 2, section 11.2.4). A card whose 8F points at a retired key fails everywhere. The same failure happens when 8F holds the wrong index, for example a test key's index left over from development.
  • Tag 92 missing. The profile leaves out the remainder. The certificate opens, but the terminal can't rebuild the bank's full key, so the hash doesn't match.
  • A signed record changed. A value in the card data is edited after the chip certificates were generated. The ICC certificate's hash no longer matches.
  • Expired. The issuer certificate runs out while cards that depend on it are still in use.
  • Replay. A signature captured from an earlier payment, played back against a new random number. This is the clone case, and it's what DDA is there to stop.

What the terminal does with a failure

None of this shows up as an error on the screen. The terminal records it in the Terminal Verification Results (tag 95), which has bits for "SDA failed", "DDA failed", "CDA failed" and "offline data authentication was not performed" (Book 3, Annex C5). The terminal's and the issuer's action codes then decide what happens: go online, or decline.

Book 3 adds a point here that I found striking. It strongly recommends configuring terminals to go online when these bits are set, because otherwise a fraudulent card could be built to approve itself offline (Book 3, section 10.7, footnote 15). The cryptography only protects you if the configuration acts on it.

Running it yourself

Pick the language you prefer. Both versions build the same chain and print the same results.

Python needs version 3.9 or newer and nothing else:

Bash
python3 chain.py

C# needs .NET 10 or newer, which runs a single .cs file directly, with no project file:

Bash
dotnet run Chain.cs

Every key is generated fresh on each run. The CA index 7E is made up, the card number is invented, and nothing here is a real scheme or bank key. To experiment, try a 1984-bit CA key, an exponent of 3, or change a different byte of the records.

The full Python script (chain.py)
Python
"""
Three signatures deep: build a TEST EMV certificate chain (CA -> issuer -> chip) and verify it the way a terminal
does, using nothing but Python's built-ins. Every key is generated fresh on each run; nothing here is a real key.

References are to EMV 4.3 Book 2 (Security and Key Management) unless marked Book 3.
Run: python3 chain.py
"""
import hashlib
import secrets
from datetime import date

# ---------------------------------------------------------------------------------------------------------------
# Part 1: RSA from scratch. EMV only needs the raw operation x^e mod n; the padding is EMV's own (Annex A2.1).
# ---------------------------------------------------------------------------------------------------------------

def is_probable_prime(n, rounds=40):
    """Miller-Rabin: a composite survives one round with probability at most 1/4, so 40 rounds is plenty."""
    if n < 2:
        return False
    for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):
        if n % p == 0:
            return n == p
    d, r = n - 1, 0
    while d % 2 == 0:
        d //= 2
        r += 1
    for _ in range(rounds):
        x = pow(secrets.randbelow(n - 3) + 2, d, n)
        if x in (1, n - 1):
            continue
        for _ in range(r - 1):
            x = pow(x, 2, n)
            if x == n - 1:
                break
        else:
            return False
    return True


def random_prime(bits, e):
    while True:
        # Set the top two bits so p*q has exactly 2*bits bits: Book 2 6.1 wants the modulus's leftmost bit to be 1.
        p = secrets.randbits(bits) | (0b11 << (bits - 2)) | 1
        if is_probable_prime(p) and (p - 1) % e != 0:
            return p


def make_key(bits, e=65537):
    """A TEST RSA key pair. EMV allows only two public exponents: 3 or 2^16 + 1 (Book 2 6.1)."""
    p, q = random_prime(bits // 2, e), random_prime(bits // 2, e)
    n = p * q
    d = pow(e, -1, (p - 1) * (q - 1))
    return {"n": n, "e": e, "d": d, "size": bits // 8}


def to_bytes(x, size):
    return x.to_bytes(size, "big")


def exponent_bytes(e):
    return b"\x03" if e == 3 else b"\x01\x00\x01"


def modulus(key):
    return to_bytes(key["n"], key["size"])


def sha1(data):
    return hashlib.sha1(data).digest()  # Hash Algorithm Indicator '01' is SHA-1 (Book 2 11.2.2)


# ---------------------------------------------------------------------------------------------------------------
# Part 2: the signature scheme (Annex A2.1, ISO/IEC 9796-2 with message recovery).
# The signer keeps the leftmost N - 22 bytes of the message INSIDE the signature, so the verifier gets them back.
# ---------------------------------------------------------------------------------------------------------------

def sign(key, message):
    n_bytes = key["size"]
    msg1 = message[: n_bytes - 22]                       # recoverable part
    block = b"\x6A" + msg1 + sha1(message) + b"\xBC"     # header 6A, data, 20-byte hash, trailer BC
    assert len(block) == n_bytes
    return to_bytes(pow(int.from_bytes(block, "big"), key["d"], key["n"]), n_bytes)


def recover(key, signature):
    """What the terminal does: one public-key operation, then read the block."""
    return to_bytes(pow(int.from_bytes(signature, "big"), key["e"], key["n"]), key["size"])


# ---------------------------------------------------------------------------------------------------------------
# Part 3: the issuer side. What the scheme CA and the bank's data preparation put on the card.
# ---------------------------------------------------------------------------------------------------------------

def bcd(digits):
    return bytes.fromhex(digits)


def pad_f(digits, size):
    """Numeric digits padded to the right with F nibbles, e.g. the IIN 476173 -> 476173FF."""
    return bytes.fromhex(digits.ljust(size * 2, "F"))


def split_modulus(mod, room):
    """If the key doesn't fit in the room the certificate has, the rest travels separately as the 'remainder'."""
    if len(mod) <= room:
        return mod + b"\xBB" * (room - len(mod)), b""
    return mod[:room], mod[room:]


def issuer_certificate(ca, issuer, iin, expiry_mmyy, serial):
    """Book 2 Table 10: the issuer's public key, signed by the CA. Goes on the card as tag 90 (+ 92, 9F32)."""
    leftmost, remainder = split_modulus(modulus(issuer), ca["size"] - 36)
    exp = exponent_bytes(issuer["e"])
    data = (b"\x02" + pad_f(iin, 4) + bcd(expiry_mmyy) + serial
            + b"\x01" + b"\x01" + bytes([issuer["size"], len(exp)]) + leftmost + remainder + exp)
    return {"90": sign(ca, data), "92": remainder, "9F32": exp}


def icc_certificate(issuer, icc, pan, expiry_mmyy, serial, static_data):
    """Book 2 Table 11: the chip's public key, signed by the issuer. Tag 9F46 (+ 9F48, 9F47)."""
    leftmost, remainder = split_modulus(modulus(icc), issuer["size"] - 42)
    exp = exponent_bytes(icc["e"])
    data = (b"\x04" + pad_f(pan, 10) + bcd(expiry_mmyy) + serial
            + b"\x01" + b"\x01" + bytes([icc["size"], len(exp)]) + leftmost + remainder + exp
            + static_data)  # the signed records are part of the hash, so changing any of them breaks this cert
    return {"9F46": sign(issuer, data), "9F48": remainder, "9F47": exp}


def chip_signs(icc, icc_dynamic_number, terminal_data):
    """Book 2 Table 15: what the chip signs for INTERNAL AUTHENTICATE (DDA). The result is tag 9F4B."""
    dyn = bytes([len(icc_dynamic_number)]) + icc_dynamic_number
    data = b"\x05" + b"\x01" + bytes([len(dyn)]) + dyn + b"\xBB" * (icc["size"] - len(dyn) - 25) + terminal_data
    return sign(icc, data)


# ---------------------------------------------------------------------------------------------------------------
# Part 4: the terminal side. Every check below is a numbered step in Book 2 6.2-6.5.
# ---------------------------------------------------------------------------------------------------------------

class Failed(Exception):
    pass


def check(ok, why):
    if not ok:
        raise Failed(why)


def expired(mmyy, today):
    month, year = int(mmyy[:2]), 2000 + int(mmyy[2:])
    # Valid to the END of the named month (Book 2 6.3 step 9).
    return (year, month) < (today.year, today.month)


def verify(card, terminal_ca_keys, terminal_data, today):
    # 6.2: find the CA key from the RID (first 5 bytes of the AID) and the index in tag 8F.
    ca = terminal_ca_keys.get((card["RID"], card["8F"]))
    check(ca is not None, f"no CA key {card['RID']}/{card['8F']} in this terminal")

    # 6.3: open the issuer certificate with the CA key.
    cert = card["90"]
    check(len(cert) == ca["size"], "issuer certificate is not the CA key's length")
    block = recover(ca, cert)
    check(block[-1] == 0xBC, "issuer certificate: trailer is not BC (wrong CA key?)")
    check(block[0] == 0x6A, "issuer certificate: header is not 6A")
    check(block[1] == 0x02, "issuer certificate: format is not 02")
    body, recovered_hash = block[1:-21], block[-21:-1]
    check(sha1(body + card["92"] + card["9F32"]) == recovered_hash, "issuer certificate: hash mismatch")
    iin = body[1:5].hex().upper().rstrip("F")                 # 3-8 digits, padded with F
    check(card["5A"].startswith(iin), "issuer identifier doesn't match the PAN")
    check(not expired(body[5:7].hex(), today), f"issuer certificate expired {body[5:7].hex()}")
    ni = body[12]
    issuer = {"n": int.from_bytes((body[14:] + card["92"])[:ni], "big"),
              "e": int.from_bytes(card["9F32"], "big"), "size": ni}

    # 6.4: open the chip's certificate with the issuer key just recovered.
    cert = card["9F46"]
    check(len(cert) == issuer["size"], "ICC certificate is not the issuer key's length")
    block = recover(issuer, cert)
    check(block[-1] == 0xBC and block[0] == 0x6A, "ICC certificate: bad header or trailer")
    check(block[1] == 0x04, "ICC certificate: format is not 04")
    body, recovered_hash = block[1:-21], block[-21:-1]
    check(sha1(body + card["9F48"] + card["9F47"] + card["records"]) == recovered_hash,
          "ICC certificate: hash mismatch (signed records changed?)")
    check(body[1:11].hex().upper().rstrip("F") == card["5A"], "ICC certificate is for another PAN")
    check(not expired(body[11:13].hex(), today), "ICC certificate expired")
    nic = body[18]
    icc = {"n": int.from_bytes((body[20:] + card["9F48"])[:nic], "big"),
           "e": int.from_bytes(card["9F47"], "big"), "size": nic}

    # 6.5.2: check the chip's live signature over the terminal's random number.
    check(len(card["9F4B"]) == icc["size"], "dynamic signature is not the chip key's length")
    block = recover(icc, card["9F4B"])
    check(block[-1] == 0xBC and block[0] == 0x6A and block[1] == 0x05, "dynamic signature: bad format")
    check(sha1(block[1:-21] + terminal_data) == block[-21:-1], "dynamic signature: hash mismatch")
    return "DDA passed"


# ---------------------------------------------------------------------------------------------------------------
# Part 5: build one card, then break it in the ways cards break in the field.
# ---------------------------------------------------------------------------------------------------------------

if __name__ == "__main__":
    RID, INDEX = "A000000003", "7E"     # Visa's RID, but 7E is a made-up index: this CA key is ours, not Visa's
    PAN = "4761730000001233"            # a made-up TEST PAN (valid check digit)

    print("Generating TEST keys (CA 1408-bit, issuer 1152-bit, chip 768-bit)...")
    ca, issuer, icc = make_key(1408), make_key(1152), make_key(768)

    records = bytes.fromhex("5A08" + PAN + "5F24032912315F3401019F0702FF00")  # stand-in for the signed records
    card = {"RID": RID, "8F": INDEX, "5A": PAN, "records": records}
    card |= issuer_certificate(ca, issuer, "476173", "1229", b"\x00\x00\x01")
    card |= icc_certificate(issuer, icc, PAN, "1228", b"\x00\x00\x01", records)

    print(f"  90   issuer certificate  {len(card['90'])} bytes")
    print(f"  92   issuer remainder    {len(card['92'])} bytes  (1152-bit key, room for {1408 // 8 - 36} bytes)")
    print(f"  9F46 ICC certificate     {len(card['9F46'])} bytes")
    print(f"  9F48 ICC remainder       {len(card['9F48'])} bytes  (768-bit key fits in {1152 // 8 - 42})")

    terminal = {(RID, INDEX): {"n": ca["n"], "e": ca["e"], "size": ca["size"]}}  # public half only
    unpredictable_number = secrets.token_bytes(4)                                  # tag 9F37, fresh per payment
    card["9F4B"] = chip_signs(icc, secrets.token_bytes(4), unpredictable_number)

    def attempt(label, card, terminal=terminal, today=date(2026, 11, 4), un=unpredictable_number):
        try:
            result = verify(card, terminal, un, today)
        except Failed as e:
            result = f"FAILED: {e}"
        print(f"  {label:<38} {result}")

    print("\nThe terminal checks:")
    attempt("genuine card", card)
    attempt("terminal lacks the CA key", {**card, "8F": "7F"})
    attempt("issuer remainder (92) missing", {**card, "92": b""})
    attempt("one signed record byte changed", {**card, "records": records[:-1] + b"\x01"})
    attempt("same card, January 2030", card, today=date(2030, 1, 1))
    attempt("replayed signature, new random number", card, un=secrets.token_bytes(4))
The full C# program (Chain.cs)
C#
// Three signatures deep: build a TEST EMV certificate chain (CA -> issuer -> chip) and verify it the way a terminal
// does, using nothing but .NET's built-ins. Every key is generated fresh on each run; nothing here is a real key.
//
// References are to EMV 4.3 Book 2 (Security and Key Management) unless marked Book 3.
// Run: dotnet run Chain.cs   (.NET 10 or newer)
using System.Numerics;
using System.Security.Cryptography;

// ---------------------------------------------------------------------------------------------------------------
// Part 5: build one card, then break it in the ways cards break in the field. (Parts 1-4 are below.)
// ---------------------------------------------------------------------------------------------------------------

const string Rid = "A000000003", Index = "7E"; // Visa's RID, but 7E is a made-up index: this CA key is ours, not Visa's
const string Pan = "4761730000001233";         // a made-up TEST PAN (valid check digit)

Console.WriteLine("Generating TEST keys (CA 1408-bit, issuer 1152-bit, chip 768-bit)...");
RsaKey ca = MakeKey(1408), issuer = MakeKey(1152), icc = MakeKey(768);

byte[] records = Convert.FromHexString("5A08" + Pan + "5F24032912315F3401019F0702FF00"); // stand-in for the signed records
var card = new Card { Rid = Rid, Index = Index, Pan = Pan, Records = records };
(card.IssuerCert, card.IssuerRemainder, card.IssuerExponent) = IssuerCertificate(ca, issuer, "476173", "1229", [0x00, 0x00, 0x01]);
(card.IccCert, card.IccRemainder, card.IccExponent) = IccCertificate(issuer, icc, Pan, "1228", [0x00, 0x00, 0x01], records);

Console.WriteLine($"  90   issuer certificate  {card.IssuerCert.Length} bytes");
Console.WriteLine($"  92   issuer remainder    {card.IssuerRemainder.Length} bytes  (1152-bit key, room for {1408 / 8 - 36} bytes)");
Console.WriteLine($"  9F46 ICC certificate     {card.IccCert.Length} bytes");
Console.WriteLine($"  9F48 ICC remainder       {card.IccRemainder.Length} bytes  (768-bit key fits in {1152 / 8 - 42})");

var terminal = new Dictionary<(string, string), RsaKey> { [(Rid, Index)] = ca with { D = 0 } }; // public half only
byte[] unpredictableNumber = RandomNumberGenerator.GetBytes(4);                                // tag 9F37, fresh per payment
card.DynamicSignature = ChipSigns(icc, RandomNumberGenerator.GetBytes(4), unpredictableNumber);

void Attempt(string label, Card c, DateOnly? today = null, byte[]? un = null)
{
    string result;
    try { result = Verify(c, terminal, un ?? unpredictableNumber, today ?? new DateOnly(2026, 11, 4)); }
    catch (FailedException e) { result = $"FAILED: {e.Message}"; }
    Console.WriteLine($"  {label,-38} {result}");
}

Console.WriteLine("\nThe terminal checks:");
Attempt("genuine card", card);
Attempt("terminal lacks the CA key", card with { Index = "7F" });
Attempt("issuer remainder (92) missing", card with { IssuerRemainder = [] });
Attempt("one signed record byte changed", card with { Records = [.. records[..^1], 0x01] });
Attempt("same card, January 2030", card, today: new DateOnly(2030, 1, 1));
Attempt("replayed signature, new random number", card, un: RandomNumberGenerator.GetBytes(4));

// ---------------------------------------------------------------------------------------------------------------
// Part 1: RSA from scratch. EMV only needs the raw operation x^e mod n; the padding is EMV's own (Annex A2.1).
// ---------------------------------------------------------------------------------------------------------------

static BigInteger Num(byte[] b) => new(b, isUnsigned: true, isBigEndian: true);

static byte[] ToBytes(BigInteger x, int size)
{
    byte[] b = x.ToByteArray(isUnsigned: true, isBigEndian: true);
    return [.. new byte[size - b.Length], .. b]; // left-pad with zeros to the key's length
}

static BigInteger RandomBits(int bits) => Num(RandomNumberGenerator.GetBytes(bits / 8));

// Miller-Rabin: a composite survives one round with probability at most 1/4, so 40 rounds is plenty.
static bool IsProbablePrime(BigInteger n, int rounds = 40)
{
    if (n < 2) return false;
    foreach (int p in new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 })
        if (n % p == 0) return n == p;
    BigInteger d = n - 1;
    int r = 0;
    while (d.IsEven) { d >>= 1; r++; }
    for (int i = 0; i < rounds; i++)
    {
        BigInteger x = BigInteger.ModPow(RandomBits((int)n.GetBitLength()) % (n - 3) + 2, d, n);
        if (x == 1 || x == n - 1) continue;
        bool composite = true;
        for (int j = 0; j < r - 1 && composite; j++)
        {
            x = BigInteger.ModPow(x, 2, n);
            if (x == n - 1) composite = false;
        }
        if (composite) return false;
    }
    return true;
}

static BigInteger RandomPrime(int bits, int e)
{
    while (true)
    {
        // Set the top two bits so p*q has exactly 2*bits bits: Book 2 6.1 wants the modulus's leftmost bit to be 1.
        BigInteger p = RandomBits(bits) | (BigInteger.One << (bits - 1)) | (BigInteger.One << (bits - 2)) | 1;
        if (IsProbablePrime(p) && (p - 1) % e != 0) return p;
    }
}

// The private exponent: the inverse of e modulo phi, by the extended Euclidean algorithm.
static BigInteger ModInverse(BigInteger a, BigInteger m)
{
    (BigInteger oldR, BigInteger r) = (a, m);
    (BigInteger oldS, BigInteger s) = (1, 0);
    while (r != 0)
    {
        BigInteger q = oldR / r;
        (oldR, r) = (r, oldR - q * r);
        (oldS, s) = (s, oldS - q * s);
    }
    return (oldS % m + m) % m;
}

// A TEST RSA key pair. EMV allows only two public exponents: 3 or 2^16 + 1 (Book 2 6.1).
static RsaKey MakeKey(int bits, int e = 65537)
{
    BigInteger p = RandomPrime(bits / 2, e), q = RandomPrime(bits / 2, e);
    return new RsaKey(p * q, e, ModInverse(e, (p - 1) * (q - 1)), bits / 8);
}

static byte[] ExponentBytes(BigInteger e) => e == 3 ? [0x03] : [0x01, 0x00, 0x01];

static byte[] Sha1(params byte[][] parts) => SHA1.HashData(parts.SelectMany(p => p).ToArray()); // Hash Algorithm Indicator '01' (Book 2 11.2.2)

// ---------------------------------------------------------------------------------------------------------------
// Part 2: the signature scheme (Annex A2.1, ISO/IEC 9796-2 with message recovery).
// The signer keeps the leftmost N - 22 bytes of the message INSIDE the signature, so the verifier gets them back.
// ---------------------------------------------------------------------------------------------------------------

static byte[] Sign(RsaKey key, byte[] message)
{
    byte[] msg1 = message[..(key.Size - 22)];                // recoverable part
    byte[] block = [0x6A, .. msg1, .. Sha1(message), 0xBC];  // header 6A, data, 20-byte hash, trailer BC
    return ToBytes(BigInteger.ModPow(Num(block), key.D, key.N), key.Size);
}

// What the terminal does: one public-key operation, then read the block.
static byte[] Recover(RsaKey key, byte[] signature) => ToBytes(BigInteger.ModPow(Num(signature), key.E, key.N), key.Size);

// ---------------------------------------------------------------------------------------------------------------
// Part 3: the issuer side. What the scheme CA and the bank's data preparation put on the card.
// ---------------------------------------------------------------------------------------------------------------

// Numeric digits padded to the right with F nibbles, e.g. the IIN 476173 -> 476173FF.
static byte[] PadF(string digits, int size) => Convert.FromHexString(digits.PadRight(size * 2, 'F'));

// If the key doesn't fit in the room the certificate has, the rest travels separately as the 'remainder'.
static (byte[] Leftmost, byte[] Remainder) SplitModulus(byte[] mod, int room) =>
    mod.Length <= room ? ([.. mod, .. Enumerable.Repeat((byte)0xBB, room - mod.Length)], []) : (mod[..room], mod[room..]);

// Book 2 Table 10: the issuer's public key, signed by the CA. Goes on the card as tag 90 (+ 92, 9F32).
static (byte[] Cert, byte[] Remainder, byte[] Exponent) IssuerCertificate(RsaKey ca, RsaKey issuer, string iin, string expiryMmyy, byte[] serial)
{
    var (leftmost, remainder) = SplitModulus(ToBytes(issuer.N, issuer.Size), ca.Size - 36);
    byte[] exp = ExponentBytes(issuer.E);
    byte[] data = [0x02, .. PadF(iin, 4), .. Convert.FromHexString(expiryMmyy), .. serial,
                   0x01, 0x01, (byte)issuer.Size, (byte)exp.Length, .. leftmost, .. remainder, .. exp];
    return (Sign(ca, data), remainder, exp);
}

// Book 2 Table 11: the chip's public key, signed by the issuer. Tag 9F46 (+ 9F48, 9F47).
static (byte[] Cert, byte[] Remainder, byte[] Exponent) IccCertificate(RsaKey issuer, RsaKey icc, string pan, string expiryMmyy, byte[] serial, byte[] staticData)
{
    var (leftmost, remainder) = SplitModulus(ToBytes(icc.N, icc.Size), issuer.Size - 42);
    byte[] exp = ExponentBytes(icc.E);
    byte[] data = [0x04, .. PadF(pan, 10), .. Convert.FromHexString(expiryMmyy), .. serial,
                   0x01, 0x01, (byte)icc.Size, (byte)exp.Length, .. leftmost, .. remainder, .. exp,
                   .. staticData]; // the signed records are part of the hash, so changing any of them breaks this cert
    return (Sign(issuer, data), remainder, exp);
}

// Book 2 Table 15: what the chip signs for INTERNAL AUTHENTICATE (DDA). The result is tag 9F4B.
static byte[] ChipSigns(RsaKey icc, byte[] iccDynamicNumber, byte[] terminalData)
{
    byte[] dyn = [(byte)iccDynamicNumber.Length, .. iccDynamicNumber];
    byte[] data = [0x05, 0x01, (byte)dyn.Length, .. dyn,
                   .. Enumerable.Repeat((byte)0xBB, icc.Size - dyn.Length - 25), // padding up to the key's size
                   .. terminalData];                                            // the terminal's random number
    return Sign(icc, data);
}

// ---------------------------------------------------------------------------------------------------------------
// Part 4: the terminal side. Every check below is a numbered step in Book 2 6.2-6.5.
// ---------------------------------------------------------------------------------------------------------------

static void Check(bool ok, string why)
{
    if (!ok) throw new FailedException(why);
}

// Valid to the END of the named month (Book 2 6.3 step 9).
static bool Expired(string mmyy, DateOnly today)
{
    int month = int.Parse(mmyy[..2]), year = 2000 + int.Parse(mmyy[2..]);
    return (year, month).CompareTo((today.Year, today.Month)) < 0;
}

static string Hex(byte[] b) => Convert.ToHexString(b);

static string Verify(Card card, Dictionary<(string, string), RsaKey> terminalCaKeys, byte[] terminalData, DateOnly today)
{
    // 6.2: find the CA key from the RID (first 5 bytes of the AID) and the index in tag 8F.
    Check(terminalCaKeys.TryGetValue((card.Rid, card.Index), out var ca), $"no CA key {card.Rid}/{card.Index} in this terminal");

    // 6.3: open the issuer certificate with the CA key.
    Check(card.IssuerCert.Length == ca!.Size, "issuer certificate is not the CA key's length");
    byte[] block = Recover(ca, card.IssuerCert);
    Check(block[^1] == 0xBC, "issuer certificate: trailer is not BC (wrong CA key?)");
    Check(block[0] == 0x6A, "issuer certificate: header is not 6A");
    Check(block[1] == 0x02, "issuer certificate: format is not 02");
    byte[] body = block[1..^21], recoveredHash = block[^21..^1];
    Check(Sha1(body, card.IssuerRemainder, card.IssuerExponent).SequenceEqual(recoveredHash), "issuer certificate: hash mismatch");
    string iin = Hex(body[1..5]).TrimEnd('F');                   // 3-8 digits, padded with F
    Check(card.Pan.StartsWith(iin), "issuer identifier doesn't match the PAN");
    Check(!Expired(Hex(body[5..7]), today), $"issuer certificate expired {Hex(body[5..7])}");
    int ni = body[12];
    byte[] issuerModulus = [.. body[14..], .. card.IssuerRemainder];  // recovered part + remainder, minus any BB padding
    var issuer = new RsaKey(Num(issuerModulus[..ni]), Num(card.IssuerExponent), 0, ni);

    // 6.4: open the chip's certificate with the issuer key just recovered.
    Check(card.IccCert.Length == issuer.Size, "ICC certificate is not the issuer key's length");
    block = Recover(issuer, card.IccCert);
    Check(block[^1] == 0xBC && block[0] == 0x6A, "ICC certificate: bad header or trailer");
    Check(block[1] == 0x04, "ICC certificate: format is not 04");
    body = block[1..^21];
    recoveredHash = block[^21..^1];
    Check(Sha1(body, card.IccRemainder, card.IccExponent, card.Records).SequenceEqual(recoveredHash),
          "ICC certificate: hash mismatch (signed records changed?)");
    Check(Hex(body[1..11]).TrimEnd('F') == card.Pan, "ICC certificate is for another PAN");
    Check(!Expired(Hex(body[11..13]), today), "ICC certificate expired");
    int nic = body[18];
    byte[] iccModulus = [.. body[20..], .. card.IccRemainder];
    var icc = new RsaKey(Num(iccModulus[..nic]), Num(card.IccExponent), 0, nic);

    // 6.5.2: check the chip's live signature over the terminal's random number.
    Check(card.DynamicSignature.Length == icc.Size, "dynamic signature is not the chip key's length");
    block = Recover(icc, card.DynamicSignature);
    Check(block[^1] == 0xBC && block[0] == 0x6A && block[1] == 0x05, "dynamic signature: bad format");
    Check(Sha1(block[1..^21], terminalData).SequenceEqual(block[^21..^1]), "dynamic signature: hash mismatch");
    return "DDA passed";
}

record RsaKey(BigInteger N, BigInteger E, BigInteger D, int Size);

// What the terminal reads from the card, by tag.
record Card
{
    public required string Rid { get; init; }           // first 5 bytes of the AID
    public required string Index { get; init; }         // 8F  CA public key index
    public required string Pan { get; init; }           // 5A
    public required byte[] Records { get; init; }       // the records marked for offline data authentication
    public byte[] IssuerCert { get; set; } = [];        // 90
    public byte[] IssuerRemainder { get; set; } = [];   // 92
    public byte[] IssuerExponent { get; set; } = [];    // 9F32
    public byte[] IccCert { get; set; } = [];           // 9F46
    public byte[] IccRemainder { get; set; } = [];      // 9F48
    public byte[] IccExponent { get; set; } = [];       // 9F47
    public byte[] DynamicSignature { get; set; } = [];  // 9F4B
}

class FailedException(string message) : Exception(message);

As a cross-check, I ran the issuer certificate this script produces through a separate certificate checker I'd written earlier for real scheme files. It opened the certificate and passed every field and hash check. The two versions also check each other: the Python verifier accepts a card built by the C# program.

What I took from this

The terminal trusts very little of what it stores: a handful of keys per scheme. Everything else is proven at the counter, from the card, in a fraction of a second. That's a good answer to a hard question: how do you trust millions of cards from thousands of banks without a network?

The other lesson is about where failures come from. Offline authentication rarely fails because someone broke the cryptography. It fails because one byte of card data was wrong when the card was made, and that byte is the same on every card in the batch. That makes checking card data before it goes to the printer one of the most useful things an issuer can do.

Next in the series

Part 4 is about that checking: the card profile that describes what goes onto a chip, and how to catch the mistakes in this post, and others like them, before a single card is printed.

If you've chased an offline authentication failure in production, I'd like to hear what caused it. Tell me in the comments.