Part 3 followed a token all the way to the bank's door. This one is about what the bank checks once the tap gets there.
When you tap, the reader collects about a dozen values: the amount, the currency, the date, the country, and a random number it makes up on the spot. It hands them to the card. The card hands back eight bytes. Those eight bytes are the Authorisation Request Cryptogram, the ARQC, and nearly everything your bank decides about the tap rests on them.
The reader can't check them. It doesn't have the key and never will. Only your bank can, because only your bank can rebuild the key that made them.
In this post we build that key from scratch, sign a tap with it, check it the way an issuer's host does, and then break it five different ways. The code is the real EMV method with real Triple DES. Give it field 55 from a test log and it will check that too, as long as the card uses EMVCo's common core method.
Three keys, one after another
The key that signs your tap is the last of three.

The issuer master key belongs to the bank. It lives inside a hardware security module and doesn't come out. One key covers a whole range of cards.
The card master key is made from it at personalisation, using your card number and its sequence number, and written into the chip. Every card gets a different one. The bank doesn't keep a copy, and it doesn't need to: give the HSM the card number and it rebuilds the key in microseconds. A bank with two million cards stores one key.
The session key is made from the card master key on every transaction, using the transaction counter. It signs one tap and is never used again.
Each step only goes one way. A card master key tells you nothing about the issuer master key, so breaking into one chip gets you one card. A session key gets you one transaction.
The card's key
EMV calls the method Option A. Take the card number, put the sequence number after it and keep the rightmost 16 digits. Encrypt that under the issuer master key. Flip every bit and encrypt it again. The two results side by side are the card's key, once the last bit of each byte is set for DES parity.
def card_master_key(imk: bytes, pan: str, psn: str) -> bytes:
"""Option A: the rightmost 16 digits of PAN + PSN, enciphered as is and inverted (A1.4.1)."""
y = x((pan + psn)[-16:].rjust(16, "0"))
tdes = DES3.new(imk, DES3.MODE_ECB)
return odd_parity(tdes.encrypt(y) + tdes.encrypt(xor(y, b"\xFF" * 8)))
The same in C#
public static byte[] CardMasterKey(byte[] imk, string pan, string psn)
{
string digits = pan + psn;
var y = Convert.FromHexString(digits[Math.Max(0, digits.Length - 16)..].PadLeft(16, '0'));
return OddParity([.. Ecb3(imk, y), .. Ecb3(imk, [.. y.Select(b => (byte)~b)])]);
}
For the public test card 4761 7390 0101 0010 with sequence number 01, under the well-known test key 0123456789ABCDEF FEDCBA9876543210, that gives 2F02C8B0E9CBC7B0 5B5167F7A1CDE6E5.
The sequence number is the quiet part of that formula. It's two digits most people never look at, usually 00 or 01, and it tells a first card apart from its replacement. If data preparation used one value and the bank's card record holds another, the chip gets a perfectly good key that the bank will never rebuild. Every tap from that card fails, and from the outside it looks exactly like fraud.
The tap's key
The transaction counter, the ATC, goes up by one on every transaction the card makes. The session key is that counter, padded out to a block, encrypted twice under the card master key with one byte changed between the two halves:
def session_key(mk: bytes, atc: bytes) -> bytes:
"""The ATC, then F0 or 0F in the third byte, each enciphered under the card master key (A1.3.1)."""
tdes = DES3.new(mk, DES3.MODE_ECB)
return tdes.encrypt(atc + b"\xF0" + bytes(5)) + tdes.encrypt(atc + b"\x0F" + bytes(5))
The same in C#
public static byte[] SessionKey(byte[] mk, byte[] atc) =>
[.. Ecb3(mk, [atc[0], atc[1], 0xF0, 0, 0, 0, 0, 0]), .. Ecb3(mk, [atc[0], atc[1], 0x0F, 0, 0, 0, 0, 0])];
Counter 0001 gives DD43A16846223F21 CB1BCC7B0C0BC484. Counter 0002 gives a key that shares nothing with it.
What the card signs
The card doesn't sign the whole conversation. It signs a fixed list in a fixed order, and the bank has to rebuild exactly the same bytes. In EMV's common method that list has eleven values, eight from the reader and three from the card:
| Value | On this tap | From |
|---|---|---|
| Amount | 000000002500 ($25.00, in cents) | reader |
| Amount, other | 000000000000 | reader |
| Terminal country | 0840 (United States) | reader |
| Terminal verification results | 0000008000 | reader |
| Currency | 0840 (US dollar) | reader |
| Date | 261126 | reader |
| Transaction type | 00 (purchase) | reader |
| Unpredictable number | 8A41C2F0 | reader |
| Application interchange profile | 1980 | card |
| Transaction counter | 0001 | card |
| Issuer application data | 0FA501A030… (32 bytes) | card |
That's 65 bytes, and every one of them is there for a reason. The random number means a cryptogram can't be worked out in advance and saved for later. The counter means it can't be used twice. The amount means it can't be moved onto a bigger purchase. The terminal verification results are the reader's own verdict on the transaction so far, so the card is vouching for those too.
The issuer application data deserves a second look, because the bank reads it before anything else. Its second byte, A5, says which method made the cryptogram: format A, cryptogram version 5, EMV's common core. Its third byte is a key index, so a bank can change keys and still know which one a card holds. The five bytes after that are the card's own report on the transaction. Here they say it asked to go online and still has three PIN tries left.
The signature is a MAC, ISO 9797-1 algorithm 3. The data is padded with 80 and zeros to whole 8-byte blocks, chained through single DES under the left half of the session key, and the last block goes through the full key:
def mac(key: bytes, msg: bytes) -> bytes:
"""ISO/IEC 9797-1 Algorithm 3: single-DES CBC under the left key half, then Triple DES on the last block (A1.2.1)."""
msg += b"\x80" + bytes(-(len(msg) + 1) % 8) # pad: 80, then 00s to a whole number of 8-byte blocks
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(xor(msg[i:i + 8], block))
return left.encrypt(right.decrypt(block))
The same in C#
public static byte[] Mac(byte[] key, byte[] msg)
{
byte[] padded = [.. msg, 0x80, .. new byte[(8 - (msg.Length + 1) % 8) % 8]]; // 80, then 00s to whole blocks
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);
}
Here is the card's answer to the reader's GENERATE AC command for this tap, laid out:
77 37 response template, 55 bytes
9F27 01 80 this is an ARQC: ask the bank
9F36 02 0001 transaction counter
9F26 08 2007D63548109602 the cryptogram
9F10 20 0FA501A030000000… issuer application data, 32 bytes
How the bank checks it
The reader puts its own values and the card's into field 55 of the authorisation message, and that is what reaches the bank. The check is short, and the order matters:
- Read field 55 and refuse it if anything on the list is missing.
- Read the issuer application data. If the card used a method this host doesn't implement, stop there. Guessing at this step declines good cards.
- Rebuild the card master key from the card number and the sequence number on file, then the session key from the counter in the message.
- Recompute the cryptogram over the same 65 bytes and compare.
- Only then look at the counter. A cryptogram can be perfect and still be old.
mk = card_master_key(self.imk, pan, self.cards[pan])
sk = session_key(mk, t["9F36"])
expected = mac(sk, signed_data(t))
if not hmac.compare_digest(expected, t["9F26"]):
# No ARPC: an answer built on a cryptogram we couldn't verify would only help an attacker.
return Answer(False, f"cryptogram doesn't match (card sent {h(t['9F26'])}, expected {h(expected)})")
atc, last = int.from_bytes(t["9F36"], "big"), self.last_atc.get(pan, 0)
if atc <= last:
# Genuine, but old: someone is replaying it. Decline, and sign the decline so the card trusts it.
return Answer(False, f"counter {atc:04X} was already used (last seen {last:04X})",
mac(sk, t["9F26"] + self.DECLINE)[:4] + self.DECLINE)
self.last_atc[pan] = atc
return Answer(True, "approved", mac(sk, t["9F26"] + self.APPROVE)[:4] + self.APPROVE)
The same in C#
var mk = Emv.CardMasterKey(imk, pan, cards[pan]);
var sk = Emv.SessionKey(mk, t["9F36"]);
var expected = Emv.Mac(sk, Emv.SignedData(t));
if (!CryptographicOperations.FixedTimeEquals(expected, t["9F26"]))
// No ARPC: an answer built on a cryptogram we couldn't verify would only help an attacker.
return new(false, $"cryptogram doesn't match (card sent {Convert.ToHexString(t["9F26"])}, expected {Convert.ToHexString(expected)})", []);
int atc = (t["9F36"][0] << 8) | t["9F36"][1], last = LastAtc.GetValueOrDefault(pan);
if (atc <= last)
// Genuine, but old: someone is replaying it. Decline, and sign the decline so the card trusts it.
return new(false, $"counter {atc:X4} was already used (last seen {last:X4})", [.. Emv.Mac(sk, [.. t["9F26"], .. Decline])[..4], .. Decline]);
LastAtc[pan] = atc;
return new(true, "approved", [.. Emv.Mac(sk, [.. t["9F26"], .. Approve])[..4], .. Approve]);
The compare uses a constant-time function on purpose. An ordinary comparison stops at the first wrong byte, and a host that answers a little faster for a wrong first byte is leaking the answer one byte at a time.
For this tap the bank's own cryptogram comes out as 2007D63548109602, the same eight bytes the card sent. I also ran the inputs through the cryptogram calculator in Key Workbench, the tool I build for exactly this kind of checking, and it agrees at every step.
The answer goes back
Approving isn't the end of it. The bank sends back proof of its own, the Authorisation Response Cryptogram or ARPC, so the card can tell a real answer from a forged one. In the common method it's the same MAC again, over the ARQC and a four-byte Card Status Update that carries the bank's instructions: approved, reset your offline counters, or even block yourself. The first four bytes of that MAC, followed by the status update, go back to the card as tag 91:
91 = 1048D28A 00820000
ARPC card status update: approved, reset the offline counters
Only something holding this tap's session key could produce it, so a fake "approved" injected anywhere between the bank and the card is caught by the card itself.
Taps have a catch here. A contact card stays in the reader until the bank answers. A contactless card has usually left the field long before the answer comes back, so unless the reader asks you to hold the card or tap again, the ARPC never reaches it. That timing was half of part 1. The card doesn't forget, though: it notes that it never heard back and says so in its report on the next transaction.
Breaking it on purpose
The walk-through script runs one good tap and then five bad ones:
What goes wrong
tap 1's message sent again decline: counter 0001 was already used (last seen 0001)
amount changed after the tap decline: cryptogram doesn't match (card sent F96A58D1DCA3D934, expected 65390531C464142D)
card copied without its key decline: cryptogram doesn't match (card sent C593A034188AE1FB, expected 08115B1400553F69)
card personalised with PSN 00 decline: cryptogram doesn't match (card sent D61B7F589BF0D7E9, expected 77D325B4E833D58A)
tap 5, genuine answer approved; card says genuine
tap 5, a forged 'approved' card says FORGED
Replay. Tap 1's message goes in a second time, byte for byte. The cryptogram is genuine, which is exactly why the bank checks the counter separately. It has already seen 0001, so it declines, and it signs the decline so the card can trust that answer too.
Amount changed. Someone between the reader and the bank turns $25 into $250. The bank computes its cryptogram over the new amount, the card computed its own over the old one, and they don't match.
Card copied. A copy can have the card number, the expiry date, even the magstripe data. It can't have the key, because the key never leaves the chip. Its cryptogram is eight bytes that match nothing. This is why copying a chip is so much harder than copying a stripe, and why it matters that every online tap carries a cryptogram the bank actually checks.
Personalised with sequence number 00. The chip is genuine, and so is its key. It's just the wrong key. Nothing about the card looks faulty, and every single tap declines.
Forged answer. A fake approval with made-up ARPC bytes. The card recomputes the ARPC, gets something else, and refuses it.
What I'd watch as an issuer
- Know your cryptogram version. The issuer application data tells the host how the card signs. Cards from two bureaus or two applet versions can share a BIN and still sign differently, and a host that checks them all one way declines a whole batch while logging it as bad cryptograms.
- Keep the sequence number in one place. Data preparation, the card record and field 23 of the authorisation all have to agree. Check it when the cards are made, not after the complaints start.
- Watch the counter in both directions. A counter that repeats is a replay. A counter that jumps by hundreds overnight means the card has been busy with something: offline transactions, failed attempts, or a test rig.
- Never answer a cryptogram you couldn't verify. If the ARQC fails, decline without an ARPC. An ARPC computed over bytes an attacker chose hands them a valid MAC for nothing.
- Retire the tutorial keys.
0123456789ABCDEF FEDCBA9876543210is in every guide, this one included. Make sure nothing outside a test lab answers to it.
For the technical reader
- Card master key, Option A. Y is the rightmost 16 digits of PAN ‖ PSN, left-padded with zeros if shorter. MK = parity(DES3(IMK)[Y] ‖ DES3(IMK)[Y ⊕ FF…FF]). Card numbers longer than 16 digits use Option B, which hashes PAN ‖ PSN with SHA-1 and decimalises the result first.
- Session key, common session key derivation. R = ATC ‖ 00 00 00 00 00 00. SK = DES3(MK)[R with byte 3 set to F0] ‖ DES3(MK)[R with byte 3 set to 0F]. The spec doesn't adjust parity at this step. Many tools do, and show
DC43A16846233E20 CB1ACD7A0D0BC485for the same key. DES ignores the parity bits, so both encrypt identically. - ARQC. ISO/IEC 9797-1 MAC algorithm 3, padding method 2 (
80then00s), 8-byte result, over the 65 bytes in the table. Cryptogram version 6 does the same job with AES and CMAC. - ARPC, method 2. The first 4 bytes of the same MAC over ARQC ‖ CSU ‖ proprietary data (none here), and tag 91 = ARPC ‖ CSU. Method 1, the older one, encrypts the ARQC XOR the 2-byte response code instead.
- Scheme methods. Most scheme cards use cryptogram versions of their own. Some mix the reader's random number into the session key, some pad with zeros instead of
80, some sign a different list. The steps are the same and the details differ, which is why the script refuses anything that isn't common core version 5 rather than guess.
What's next
Those 65 bytes leave the reader inside field 55, and field 55 doesn't go straight to your bank. It travels from the terminal to the acquirer, through the switch, and only then to the issuer. In part 5 we follow that message hop by hop and look at what each one adds, checks, or can get wrong.
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 Arqc.cs.
Run either with no arguments for the walk-through. To check a cryptogram from a test log, give it the test key, the card and field 55. It checks cards that use the common core method and tells you if yours uses something else. This is tap 1's field 55, if you want to try it:
python arqc.py --imk 0123456789ABCDEFFEDCBA9876543210 --pan 4761739001010010 --psn 01 \
--de55 9F26082007D635481096029F2701809F10200FA501A03000000000000000000000000F0000000000000000000000000000009F37048A41C2F09F36020001950500000080009A032611269C01009F02060000000025005F2A020840820219809F1A0208409F0306000000000000
It prints each key, the signed data and the result, and exits with 1 when the cryptogram doesn't match, so you can use it in a test pipeline. Use test keys only. A live issuer key belongs in an HSM, never on a command line.
arqc.py (Python)
"""Check a tap's ARQC the way the card's bank does, and answer it with an ARPC the card can check.
The method is EMV's common one (EMV 4.3 Books 2 and 3, Common Core Definitions, Cryptogram Version 5):
- card master key = Triple DES of the PAN and PAN Sequence Number under the issuer master key ("Option A")
- session key = Triple DES of the Application Transaction Counter under the card master key
- ARQC = an ISO/IEC 9797-1 Algorithm 3 MAC over the transaction data, under the session key
- ARPC = the same MAC over the ARQC and the Card Status Update ("ARPC Method 2"), first 4 bytes
Each scheme also has cryptogram versions of its own, with other data and other session keys. The shape is the same.
Two ways to run it (TEST keys only, never a live issuer key):
python arqc.py the walk-through: a card, a reader, a bank
python arqc.py --imk KEY --pan PAN --psn 01 --de55 HEX check field 55 from a test log (common core cards only)
Needs pycryptodome: pip install pycryptodome
"""
import argparse
import hmac
import sys
from dataclasses import dataclass
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()
def xor(a: bytes, b: bytes) -> bytes:
return bytes(i ^ j for i, j in zip(a, b))
# ---------------------------------------------------------------- TLV (EMV Book 3, Annex B)
def tlv(tag: str, value: bytes) -> bytes:
"""Tag, length, value. Lengths of 128 and over take the long form: 81 xx, or 82 xx xx."""
n = len(value)
length = bytes([n]) if n < 0x80 else b"\x81" + bytes([n]) if n < 0x100 else b"\x82" + n.to_bytes(2, "big")
return x(tag) + length + value
def parse_tlv(data: bytes) -> dict[str, bytes]:
"""One level of TLV objects, as {tag: value}. Call it again on a template's value to go inside."""
out, i = {}, 0
while i < len(data):
if data[i] in (0x00, 0xFF): # filler bytes allowed between objects
i += 1
continue
start = i
i += 1
if data[start] & 0x1F == 0x1F: # low 5 bits all set: the tag has more bytes
while data[i] & 0x80: # b8 set: and another after this one
i += 1
i += 1
tag = h(data[start:i])
n = data[i]
i += 1
if n & 0x80: # long form: the low bits say how many length bytes follow
k = n & 0x7F
n = int.from_bytes(data[i:i + k], "big")
i += k
if i + n > len(data):
raise ValueError(f"tag {tag} says {n} bytes but only {len(data) - i} are left")
out[tag] = data[i:i + n]
i += n
return out
# ---------------------------------------------------------------- the three keys and the MAC (EMV Book 2, Annex A1)
def odd_parity(key: bytes) -> bytes:
"""DES keys carry a parity bit in each byte: set bit 1 so every byte has an odd number of 1s."""
return bytes((b & 0xFE) | (bin(b & 0xFE).count("1") % 2 == 0) for b in key)
def card_master_key(imk: bytes, pan: str, psn: str) -> bytes:
"""Option A: the rightmost 16 digits of PAN + PSN, enciphered as is and inverted (A1.4.1)."""
y = x((pan + psn)[-16:].rjust(16, "0"))
tdes = DES3.new(imk, DES3.MODE_ECB)
return odd_parity(tdes.encrypt(y) + tdes.encrypt(xor(y, b"\xFF" * 8)))
def session_key(mk: bytes, atc: bytes) -> bytes:
"""The ATC, then F0 or 0F in the third byte, each enciphered under the card master key (A1.3.1)."""
tdes = DES3.new(mk, DES3.MODE_ECB)
return tdes.encrypt(atc + b"\xF0" + bytes(5)) + tdes.encrypt(atc + b"\x0F" + bytes(5))
def mac(key: bytes, msg: bytes) -> bytes:
"""ISO/IEC 9797-1 Algorithm 3: single-DES CBC under the left key half, then Triple DES on the last block (A1.2.1)."""
msg += b"\x80" + bytes(-(len(msg) + 1) % 8) # pad: 80, then 00s to a whole number of 8-byte blocks
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(xor(msg[i:i + 8], block))
return left.encrypt(right.decrypt(block))
# What the card signs, in this order (EMV Book 2, Common Core Definitions, Table CCD 3).
SIGNED = [
("9F02", "amount"), ("9F03", "amount, other"), ("9F1A", "terminal country"), ("95", "terminal verification results"),
("5F2A", "currency"), ("9A", "date"), ("9C", "transaction type"), ("9F37", "unpredictable number"),
("82", "application interchange profile"), ("9F36", "application transaction counter"), ("9F10", "issuer application data"),
]
def signed_data(t: dict[str, bytes]) -> bytes:
return b"".join(t[tag] for tag, _ in SIGNED)
# ---------------------------------------------------------------- the card
class Card:
"""What the chip does: count, sign, and later check that the answer really came from its bank."""
AIP = x("1980") # application interchange profile: what this card supports
def __init__(self, mk: bytes):
self.mk = mk # written once at personalisation; never leaves the chip
self.atc = 0 # application transaction counter: +1 on every transaction
self.sk = b""
def iad(self) -> bytes:
"""Issuer application data, Common Core format 'A' (EMV Book 3, Annex C7): 32 bytes."""
cvr = x("A0 30 00 00 00") # ARQC asked for, no second GENERATE AC; PIN tries left: 3
return x("0F A5 01") + cvr + bytes(8) + x("0F") + bytes(15) # length, CCI (format A, version 5), key index
def generate_ac(self, terminal: dict[str, bytes]) -> bytes:
"""The response to GENERATE AC: template 77 with the cryptogram and what the bank needs to check it."""
self.atc += 1
atc = self.atc.to_bytes(2, "big")
self.sk = session_key(self.mk, atc) # a fresh key for this transaction only
t = dict(terminal, **{"82": self.AIP, "9F36": atc, "9F10": self.iad()})
arqc = mac(self.sk, signed_data(t))
# 9F27 = 80: "this is an ARQC, ask the bank". 9F26 is the cryptogram itself.
return tlv("77", tlv("9F27", x("80")) + tlv("9F36", atc) + tlv("9F26", arqc) + tlv("9F10", t["9F10"]))
def check_answer(self, arqc: bytes, tag91: bytes) -> bool:
"""Issuer authentication: recompute the ARPC; only the bank could have made it."""
arpc, csu = tag91[:4], tag91[4:8]
return hmac.compare_digest(mac(self.sk, arqc + csu)[:4], arpc) # constant time: no hints from timing
def field55(terminal: dict[str, bytes], card_response: bytes) -> bytes:
"""The reader passes the card's data and its own to the bank in ISO 8583 field 55, as TLV."""
card = parse_tlv(parse_tlv(card_response)["77"])
t = dict(terminal, **{"82": Card.AIP}, **card)
return b"".join(tlv(tag, t[tag]) for tag in ["9F26", "9F27", "9F10", "9F37", "9F36", "95", "9A", "9C",
"9F02", "5F2A", "82", "9F1A", "9F03"])
# ---------------------------------------------------------------- the bank
@dataclass
class Answer:
approved: bool
reason: str
tag91: bytes = b"" # issuer authentication data: ARPC + CSU, for the card
class Issuer:
APPROVE = x("00 82 00 00") # card status update: approved, reset the offline counters
DECLINE = x("00 00 00 00")
def __init__(self, imk: bytes, cards: dict[str, str]):
self.imk = imk # in real life this lives in the HSM and never comes out
self.cards = cards # PAN -> PAN sequence number, from the card record
self.last_atc: dict[str, int] = {}
def authorise(self, pan: str, f55: bytes, show=None) -> Answer:
t = parse_tlv(f55)
missing = [tag for tag, _ in SIGNED + [("9F26", ""), ("9F27", "")] if tag not in t]
if missing:
return Answer(False, "field 55 is missing " + " ".join(missing))
iad = t["9F10"]
if len(iad) != 32 or iad[:2] != x("0FA5"):
return Answer(False, f"not a Common Core version 5 cryptogram (IAD starts {h(iad[:2])})")
if t["9F27"][0] & 0xC0 != 0x80: # bits 8-7 = 10: ARQC
return Answer(False, "the card didn't ask to go online")
mk = card_master_key(self.imk, pan, self.cards[pan])
sk = session_key(mk, t["9F36"])
expected = mac(sk, signed_data(t))
if show:
show(mk, sk, signed_data(t), expected)
if not hmac.compare_digest(expected, t["9F26"]):
# No ARPC: an answer built on a cryptogram we couldn't verify would only help an attacker.
return Answer(False, f"cryptogram doesn't match (card sent {h(t['9F26'])}, expected {h(expected)})")
atc, last = int.from_bytes(t["9F36"], "big"), self.last_atc.get(pan, 0)
if atc <= last:
# Genuine, but old: someone is replaying it. Decline, and sign the decline so the card trusts it.
return Answer(False, f"counter {atc:04X} was already used (last seen {last:04X})",
mac(sk, t["9F26"] + self.DECLINE)[:4] + self.DECLINE)
self.last_atc[pan] = atc
return Answer(True, "approved", mac(sk, t["9F26"] + self.APPROVE)[:4] + self.APPROVE)
# ---------------------------------------------------------------- the walk-through
IMK = x("0123456789ABCDEF FEDCBA9876543210") # a well-known TEST key: never use it for real cards
PAN, PSN = "4761739001010010", "01" # a public test card number
def reader(amount_cents: int, un: str, date="261126") -> dict[str, bytes]:
"""What the reader puts in: amount in cents, 0840 (United States, US dollar) for country and currency, a fresh random number."""
return {"9F02": x(f"{amount_cents:012d}"), "9F03": bytes(6), "9F1A": x("0840"), "95": x("0000008000"),
"5F2A": x("0840"), "9A": x(date), "9C": x("00"), "9F37": x(un)}
def walk_through() -> None:
mk = card_master_key(IMK, PAN, PSN)
card, bank = Card(mk), Issuer(IMK, {PAN: PSN})
print("Making the card (once, at personalisation)")
print(f" issuer master key (test) {h(IMK)}")
print(f" PAN + sequence number {PAN} {PSN}")
print(f" card master key {h(mk)}")
print("\nTap 1: USD 25.00")
terminal = reader(2500, "8A41C2F0")
resp = card.generate_ac(terminal)
print(f" card's answer to GENERATE AC {h(resp)}")
f55 = field55(terminal, resp)
def show(mk_, sk, data, expected):
print(f" bank derives the session key {h(sk)} (counter {card.atc:04X})")
print(f" data the card signed ({len(data)} bytes) {h(data[:24])}")
for i in range(24, len(data), 24):
print(f" {h(data[i:i + 24])}")
print(f" bank's own cryptogram {h(expected)}")
first = bank.authorise(PAN, f55, show)
arqc = parse_tlv(f55)["9F26"]
print(f" cryptogram from the card {h(arqc)}")
print(f" bank {first.reason}, tag 91 = {h(first.tag91)}")
print(f" card checks the bank's answer {'genuine' if card.check_answer(arqc, first.tag91) else 'FORGED'}")
print("\nWhat goes wrong")
replay = bank.authorise(PAN, f55)
print(f" tap 1's message sent again decline: {replay.reason}")
tap2 = reader(2500, "1F07B3D9")
f55b = bytearray(field55(tap2, card.generate_ac(tap2)))
at = f55b.find(x("9F0206")) + 3
f55b[at:at + 6] = x("000000025000") # someone turns $25 into $250 on the way
print(f" amount changed after the tap decline: {bank.authorise(PAN, bytes(f55b)).reason}")
clone = Card(card_master_key(x("00112233445566778899AABBCCDDEEFF"), PAN, PSN)) # copied card, guessed key
clone.atc = card.atc
tap3 = reader(2500, "C4D29E61")
print(f" card copied without its key decline: {bank.authorise(PAN, field55(tap3, clone.generate_ac(tap3))).reason}")
misprep = Card(card_master_key(IMK, PAN, "00")) # data prep used sequence number 00, the bank has 01
tap4 = reader(2500, "5B8E0A17")
print(f" card personalised with PSN 00 decline: {bank.authorise(PAN, field55(tap4, misprep.generate_ac(tap4))).reason}")
tap5 = reader(2500, "E2A6F4C8")
f55c = field55(tap5, card.generate_ac(tap5))
good = bank.authorise(PAN, f55c)
forged = x("DEADBEEF") + Issuer.APPROVE
print(f" tap 5, genuine answer {good.reason}; card says "
f"{'genuine' if card.check_answer(parse_tlv(f55c)['9F26'], good.tag91) else 'FORGED'}")
print(f" tap 5, a forged 'approved' card says "
f"{'genuine' if card.check_answer(parse_tlv(f55c)['9F26'], forged) else 'FORGED'}")
def check_log(args) -> int:
"""Verify field 55 from a test log: prints each step, exits 1 on a mismatch."""
bank = Issuer(x(args.imk), {args.pan: args.psn})
bank.last_atc[args.pan] = args.last_atc
def show(mk, sk, data, expected):
print(f"card master key {h(mk)}\nsession key {h(sk)}\nsigned data {h(data)}\nexpected ARQC {h(expected)}")
answer = bank.authorise(args.pan, x(args.de55), show)
print(f"result {answer.reason}" + (f"\ntag 91 {h(answer.tag91)}" if answer.tag91 else ""))
return 0 if answer.approved else 1
if __name__ == "__main__":
if len(sys.argv) == 1:
walk_through()
else:
p = argparse.ArgumentParser(description="Verify an EMV Common Core (version 5) ARQC from ISO 8583 field 55.")
p.add_argument("--imk", required=True, help="issuer master key for cryptograms, 32 hex (TEST keys only)")
p.add_argument("--pan", required=True)
p.add_argument("--psn", default="00", help="PAN sequence number, 2 digits (default 00)")
p.add_argument("--de55", required=True, help="field 55 as hex")
p.add_argument("--last-atc", type=lambda s: int(s, 16), default=0, help="last counter seen, hex (default 0)")
sys.exit(check_log(p.parse_args()))
Arqc.cs (C#)
// Check a tap's ARQC the way the card's bank does, and answer it with an ARPC the card can check.
//
// The method is EMV's common one (EMV 4.3 Books 2 and 3, Common Core Definitions, Cryptogram Version 5):
// - card master key = Triple DES of the PAN and PAN Sequence Number under the issuer master key ("Option A")
// - session key = Triple DES of the Application Transaction Counter under the card master key
// - ARQC = an ISO/IEC 9797-1 Algorithm 3 MAC over the transaction data, under the session key
// - ARPC = the same MAC over the ARQC and the Card Status Update ("ARPC Method 2"), first 4 bytes
// Each scheme also has cryptogram versions of its own, with other data and other session keys. The shape is the same.
//
// Two ways to run it (.NET 10, TEST keys only, never a live issuer key):
// dotnet run Arqc.cs the walk-through: a card, a reader, a bank
// dotnet run Arqc.cs -- --imk KEY --pan PAN --psn 01 --de55 HEX check field 55 from a test log (common core cards only)
using System.Security.Cryptography;
byte[] Imk = X("0123456789ABCDEF FEDCBA9876543210"); // a well-known TEST key: never use it for real cards
const string Pan = "4761739001010010", Psn = "01"; // a public test card number
if (args.Length == 0)
WalkThrough();
else
return CheckLog(args);
return 0;
void WalkThrough()
{
var mk = Emv.CardMasterKey(Imk, Pan, Psn);
var card = new Card(mk);
var bank = new Issuer(Imk, new() { [Pan] = Psn });
Console.WriteLine("Making the card (once, at personalisation)");
Console.WriteLine($" issuer master key (test) {H(Imk)}");
Console.WriteLine($" PAN + sequence number {Pan} {Psn}");
Console.WriteLine($" card master key {H(mk)}");
Console.WriteLine("\nTap 1: USD 25.00");
var terminal = Reader(2500, "8A41C2F0");
var resp = card.GenerateAc(terminal);
Console.WriteLine($" card's answer to GENERATE AC {H(resp)}");
var f55 = Emv.Field55(terminal, resp);
void Show(byte[] _, byte[] sk, byte[] data, byte[] expected)
{
Console.WriteLine($" bank derives the session key {H(sk)} (counter {card.Atc:X4})");
Console.WriteLine($" data the card signed ({data.Length} bytes) {H(data[..24])}");
for (int i = 24; i < data.Length; i += 24)
Console.WriteLine($" {H(data[i..Math.Min(i + 24, data.Length)])}");
Console.WriteLine($" bank's own cryptogram {H(expected)}");
}
var first = bank.Authorise(Pan, f55, Show);
var arqc = Tlv.Parse(f55)["9F26"];
Console.WriteLine($" cryptogram from the card {H(arqc)}");
Console.WriteLine($" bank {first.Reason}, tag 91 = {H(first.Tag91)}");
Console.WriteLine($" card checks the bank's answer {(card.CheckAnswer(arqc, first.Tag91) ? "genuine" : "FORGED")}");
Console.WriteLine("\nWhat goes wrong");
Console.WriteLine($" tap 1's message sent again decline: {bank.Authorise(Pan, f55).Reason}");
var tap2 = Reader(2500, "1F07B3D9");
var f55b = Emv.Field55(tap2, card.GenerateAc(tap2));
int at = f55b.AsSpan().IndexOf(X("9F0206")) + 3;
X("000000025000").CopyTo(f55b, at); // someone turns $25 into $250 on the way
Console.WriteLine($" amount changed after the tap decline: {bank.Authorise(Pan, f55b).Reason}");
var clone = new Card(Emv.CardMasterKey(X("00112233445566778899AABBCCDDEEFF"), Pan, Psn)) { Atc = card.Atc };
var tap3 = Reader(2500, "C4D29E61"); // copied card, guessed key
Console.WriteLine($" card copied without its key decline: {bank.Authorise(Pan, Emv.Field55(tap3, clone.GenerateAc(tap3))).Reason}");
var misprep = new Card(Emv.CardMasterKey(Imk, Pan, "00")); // data prep used sequence number 00, the bank has 01
var tap4 = Reader(2500, "5B8E0A17");
Console.WriteLine($" card personalised with PSN 00 decline: {bank.Authorise(Pan, Emv.Field55(tap4, misprep.GenerateAc(tap4))).Reason}");
var tap5 = Reader(2500, "E2A6F4C8");
var f55c = Emv.Field55(tap5, card.GenerateAc(tap5));
var good = bank.Authorise(Pan, f55c);
byte[] forged = [.. X("DEADBEEF"), .. Issuer.Approve];
var arqc5 = Tlv.Parse(f55c)["9F26"];
Console.WriteLine($" tap 5, genuine answer {good.Reason}; card says {(card.CheckAnswer(arqc5, good.Tag91) ? "genuine" : "FORGED")}");
Console.WriteLine($" tap 5, a forged 'approved' card says {(card.CheckAnswer(arqc5, forged) ? "genuine" : "FORGED")}");
}
// Verify field 55 from a test log: prints each step, exits 1 on a mismatch.
int CheckLog(string[] a)
{
string Arg(string name, string? fallback = null) =>
Array.IndexOf(a, name) is var i and >= 0 && i + 1 < a.Length ? a[i + 1]
: fallback ?? throw new ArgumentException($"{name} is required");
string pan = Arg("--pan");
var bank = new Issuer(X(Arg("--imk")), new() { [pan] = Arg("--psn", "00") });
bank.LastAtc[pan] = Convert.ToInt32(Arg("--last-atc", "0"), 16);
var answer = bank.Authorise(pan, X(Arg("--de55")), (mk, sk, data, expected) => Console.WriteLine(
$"card master key {H(mk)}\nsession key {H(sk)}\nsigned data {H(data)}\nexpected ARQC {H(expected)}"));
Console.WriteLine($"result {answer.Reason}" + (answer.Tag91.Length > 0 ? $"\ntag 91 {H(answer.Tag91)}" : ""));
return answer.Approved ? 0 : 1;
}
// What the reader puts in: amount in cents, 0840 (United States, US dollar) for country and currency, a fresh random number.
static Dictionary<string, byte[]> Reader(long amountCents, string un, string date = "261126") => new()
{
["9F02"] = X(amountCents.ToString("D12")), ["9F03"] = new byte[6], ["9F1A"] = X("0840"), ["95"] = X("0000008000"),
["5F2A"] = X("0840"), ["9A"] = X(date), ["9C"] = X("00"), ["9F37"] = X(un),
};
static byte[] X(string s) => Convert.FromHexString(s.Replace(" ", ""));
static string H(byte[] b) => Convert.ToHexString(b);
// ---------------------------------------------------------------- TLV (EMV Book 3, Annex B)
static class Tlv
{
// Tag, length, value. Lengths of 128 and over take the long form: 81 xx, or 82 xx xx.
public static byte[] Make(string tag, byte[] value)
{
int n = value.Length;
byte[] len = n < 0x80 ? [(byte)n] : n < 0x100 ? [0x81, (byte)n] : [0x82, (byte)(n >> 8), (byte)n];
return [.. Convert.FromHexString(tag), .. len, .. value];
}
// One level of TLV objects, as tag -> value. Call it again on a template's value to go inside.
public static Dictionary<string, byte[]> Parse(byte[] data)
{
var o = new Dictionary<string, byte[]>();
int i = 0;
while (i < data.Length)
{
if (data[i] is 0x00 or 0xFF) { i++; continue; } // filler bytes allowed between objects
int start = i++;
if ((data[start] & 0x1F) == 0x1F) // low 5 bits all set: the tag has more bytes
{
while ((data[i] & 0x80) != 0) i++; // b8 set: and another after this one
i++;
}
string tag = Convert.ToHexString(data, start, i - start);
int n = data[i++];
if ((n & 0x80) != 0) // long form: the low bits say how many length bytes follow
{
int k = n & 0x7F;
n = 0;
for (int j = 0; j < k; j++) n = (n << 8) | data[i++];
}
if (i + n > data.Length) throw new FormatException($"tag {tag} says {n} bytes but only {data.Length - i} are left");
o[tag] = data[i..(i + n)];
i += n;
}
return o;
}
}
// ---------------------------------------------------------------- the three keys and the MAC (EMV Book 2, Annex A1)
static class Emv
{
// DES keys carry a parity bit in each byte: set bit 1 so every byte has an odd number of 1s.
static byte[] OddParity(byte[] key) =>
[.. key.Select(b => (byte)((b & 0xFE) | (System.Numerics.BitOperations.PopCount((uint)(b & 0xFE)) % 2 == 0 ? 1 : 0)))];
// EMV keys are double length (K1 K2). Some OpenSSL builds only take three parts, so pass K1 K2 K1: the same cipher.
static byte[] Ecb3(byte[] key, byte[] block)
{
using var t = TripleDES.Create();
t.Key = [.. key, .. key[..8]];
return t.EncryptEcb(block, PaddingMode.None);
}
// Option A: the rightmost 16 digits of PAN + PSN, enciphered as is and inverted (A1.4.1).
public static byte[] CardMasterKey(byte[] imk, string pan, string psn)
{
string digits = pan + psn;
var y = Convert.FromHexString(digits[Math.Max(0, digits.Length - 16)..].PadLeft(16, '0'));
return OddParity([.. Ecb3(imk, y), .. Ecb3(imk, [.. y.Select(b => (byte)~b)])]);
}
// The ATC, then F0 or 0F in the third byte, each enciphered under the card master key (A1.3.1).
public static byte[] SessionKey(byte[] mk, byte[] atc) =>
[.. Ecb3(mk, [atc[0], atc[1], 0xF0, 0, 0, 0, 0, 0]), .. Ecb3(mk, [atc[0], atc[1], 0x0F, 0, 0, 0, 0, 0])];
// ISO/IEC 9797-1 Algorithm 3: single-DES CBC under the left key half, then Triple DES on the last block (A1.2.1).
public static byte[] Mac(byte[] key, byte[] msg)
{
byte[] padded = [.. msg, 0x80, .. new byte[(8 - (msg.Length + 1) % 8) % 8]]; // 80, then 00s to whole blocks
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);
}
// What the card signs, in this order (EMV Book 2, Common Core Definitions, Table CCD 3).
public static readonly string[] Signed = ["9F02", "9F03", "9F1A", "95", "5F2A", "9A", "9C", "9F37", "82", "9F36", "9F10"];
public static byte[] SignedData(Dictionary<string, byte[]> t) => [.. Signed.SelectMany(tag => t[tag])];
// The reader passes the card's data and its own to the bank in ISO 8583 field 55, as TLV.
public static byte[] Field55(Dictionary<string, byte[]> terminal, byte[] cardResponse)
{
var t = new Dictionary<string, byte[]>(terminal) { ["82"] = Card.Aip };
foreach (var (k, v) in Tlv.Parse(Tlv.Parse(cardResponse)["77"])) t[k] = v;
return [.. new[] { "9F26", "9F27", "9F10", "9F37", "9F36", "95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03" }
.SelectMany(tag => Tlv.Make(tag, t[tag]))];
}
}
// ---------------------------------------------------------------- the card
// What the chip does: count, sign, and later check that the answer really came from its bank.
sealed class Card(byte[] mk) // mk: written once at personalisation; never leaves the chip
{
public static readonly byte[] Aip = [0x19, 0x80]; // application interchange profile: what this card supports
public int Atc { get; set; } // application transaction counter: +1 on every transaction
byte[] sk = [];
// Issuer application data, Common Core format 'A' (EMV Book 3, Annex C7): 32 bytes.
static byte[] Iad()
{
byte[] cvr = [0xA0, 0x30, 0, 0, 0]; // ARQC asked for, no second GENERATE AC; PIN tries left: 3
return [0x0F, 0xA5, 0x01, .. cvr, .. new byte[8], 0x0F, .. new byte[15]]; // length, CCI (format A, version 5), key index
}
// The response to GENERATE AC: template 77 with the cryptogram and what the bank needs to check it.
public byte[] GenerateAc(Dictionary<string, byte[]> terminal)
{
Atc++;
byte[] atc = [(byte)(Atc >> 8), (byte)Atc];
sk = Emv.SessionKey(mk, atc); // a fresh key for this transaction only
var t = new Dictionary<string, byte[]>(terminal) { ["82"] = Aip, ["9F36"] = atc, ["9F10"] = Iad() };
var arqc = Emv.Mac(sk, Emv.SignedData(t));
// 9F27 = 80: "this is an ARQC, ask the bank". 9F26 is the cryptogram itself.
return Tlv.Make("77", [.. Tlv.Make("9F27", [0x80]), .. Tlv.Make("9F36", atc), .. Tlv.Make("9F26", arqc), .. Tlv.Make("9F10", t["9F10"])]);
}
// Issuer authentication: recompute the ARPC; only the bank could have made it.
public bool CheckAnswer(byte[] arqc, byte[] tag91) =>
CryptographicOperations.FixedTimeEquals(Emv.Mac(sk, [.. arqc, .. tag91[4..8]])[..4], tag91[..4]);
}
// ---------------------------------------------------------------- the bank
sealed record Answer(bool Approved, string Reason, byte[] Tag91); // Tag91: ARPC + CSU, for the card
sealed class Issuer(byte[] imk, Dictionary<string, string> cards) // imk: in real life it never leaves the HSM
{ // cards: PAN -> PAN sequence number
public static readonly byte[] Approve = [0x00, 0x82, 0x00, 0x00]; // card status update: approved, reset offline counters
static readonly byte[] Decline = [0, 0, 0, 0];
public Dictionary<string, int> LastAtc { get; } = [];
public Answer Authorise(string pan, byte[] f55, Action<byte[], byte[], byte[], byte[]>? show = null)
{
var t = Tlv.Parse(f55);
var missing = Emv.Signed.Append("9F26").Append("9F27").Where(tag => !t.ContainsKey(tag)).ToList();
if (missing.Count > 0) return new(false, "field 55 is missing " + string.Join(' ', missing), []);
var iad = t["9F10"];
if (iad.Length != 32 || iad[0] != 0x0F || iad[1] != 0xA5)
return new(false, $"not a Common Core version 5 cryptogram (IAD starts {Convert.ToHexString(iad, 0, Math.Min(2, iad.Length))})", []);
if ((t["9F27"][0] & 0xC0) != 0x80) // bits 8-7 = 10: ARQC
return new(false, "the card didn't ask to go online", []);
var mk = Emv.CardMasterKey(imk, pan, cards[pan]);
var sk = Emv.SessionKey(mk, t["9F36"]);
var expected = Emv.Mac(sk, Emv.SignedData(t));
show?.Invoke(mk, sk, Emv.SignedData(t), expected);
if (!CryptographicOperations.FixedTimeEquals(expected, t["9F26"]))
// No ARPC: an answer built on a cryptogram we couldn't verify would only help an attacker.
return new(false, $"cryptogram doesn't match (card sent {Convert.ToHexString(t["9F26"])}, expected {Convert.ToHexString(expected)})", []);
int atc = (t["9F36"][0] << 8) | t["9F36"][1], last = LastAtc.GetValueOrDefault(pan);
if (atc <= last)
// Genuine, but old: someone is replaying it. Decline, and sign the decline so the card trusts it.
return new(false, $"counter {atc:X4} was already used (last seen {last:X4})", [.. Emv.Mac(sk, [.. t["9F26"], .. Decline])[..4], .. Decline]);
LastAtc[pan] = atc;
return new(true, "approved", [.. Emv.Mac(sk, [.. t["9F26"], .. Approve])[..4], .. Approve]);
}
}
What they print
Making the card (once, at personalisation)
issuer master key (test) 0123456789ABCDEFFEDCBA9876543210
PAN + sequence number 4761739001010010 01
card master key 2F02C8B0E9CBC7B05B5167F7A1CDE6E5
Tap 1: USD 25.00
card's answer to GENERATE AC 77379F2701809F360200019F26082007D635481096029F10200FA501A03000000000000000000000000F000000000000000000000000000000
bank derives the session key DD43A16846223F21CB1BCC7B0C0BC484 (counter 0001)
data the card signed (65 bytes) 000000002500000000000000084000000080000840261126
008A41C2F0198000010FA501A03000000000000000000000
000F000000000000000000000000000000
bank's own cryptogram 2007D63548109602
cryptogram from the card 2007D63548109602
bank approved, tag 91 = 1048D28A00820000
card checks the bank's answer genuine
What goes wrong
tap 1's message sent again decline: counter 0001 was already used (last seen 0001)
amount changed after the tap decline: cryptogram doesn't match (card sent F96A58D1DCA3D934, expected 65390531C464142D)
card copied without its key decline: cryptogram doesn't match (card sent C593A034188AE1FB, expected 08115B1400553F69)
card personalised with PSN 00 decline: cryptogram doesn't match (card sent D61B7F589BF0D7E9, expected 77D325B4E833D58A)
tap 5, genuine answer approved; card says genuine
tap 5, a forged 'approved' card says FORGED
Sources: EMV 4.3 Book 2, Security and Key Management (Annex A1, chapter 8 and the Common Core Definitions); EMV 4.3 Book 3, Application Specification (Annex B and the Common Core Definitions annexes). The keys and card number are public test values.


