DUKPT Explained with examples

Derived Unique Key Per Transaction (DUKPT) process that’s described in Annex A of ANS X9.24-2004.

It’s generally considered to be complex, but I’ve simplified it slightly with the help of online resources.

Key Management

Here’s a basic outline of the technique:

  1. You’re given a Base Derivation Key (BDK), which you assign to a swiper (note that the same BDK can be assigned to multiple swipers).
  2. You’ll use the BDK along with the device’s own unique Key Serial Number (KSN) to generate an Initial PIN Encryption Key (IPEK) for the device.
  3. You’ll assign this IPEK to a swiper, which uses it to irreversibly generate a list of future keys, which it’ll use to encrypt its messages.
  4. The swiper’s KSN is used along with one of its future keys to encrypt a message, and after each swipe it’ll increment the value of its KSN.
  5. Whenever a swiper takes a card it formats the card’s information into a series of tracks, each track having a particular set of information (e.g. card number, holder’s name, expiration date).
  6. The swiper usually encrypts these tracks using one of its generated future keys (called the “Session Key”) along with its current KSN. It’ll then increment the value of its KSN and discard the future key it used.
  7. At this point you’ll probably have an encrypted track along with the KSN the swiper used to encrypt it.
  8. It’s your responsibility to determine what BDK was used to initialize this device, and from there you’ll use the BDK and KSN to rederive the IPEK, which is used to rederive the Session Key, which is finally used to decrypt the message.

There’s a lot of technical information to be said about key management, but this isn’t the place for that. In some cases your provider/manufacturer (e.g. MagTek) will supply you with swipers that need to be initialized with an IPEK, and your supplier will usually have a manual that walks you through that process. If you’re doing encryption/decryption through a third party who also supplies swipers, they may have already loaded the devices with that information; what’s more is they may not even given you the BDK that belongs to your device in order to reduce the risk of security threats.


Note: Key management is beyond the scope of this explanation. Whatever you do with your keys, just make sure it’s secure.


One methodology I’ve seen that’ll allow you to associate a particular KSN to a BDK is to take the current KSN you’ve been given, mask it to retrieve the Initial Key Serial Number (IKSN), and look up the BDK in a table that maps IKSNs to BDKs:

Example:

ksn = FFFF9876543210E00008
iksn = ksn & FFFFFFFFFFFFFFE00000 // FFFF9876543210E00000

You’d then have a table that looks like:

IKSN BDK
0xFFFF9876543210E00000 0123456789ABCDEFFEDCBA9876543210

From which you could easily grab the BDK 0123456789ABCDEFFEDCBA9876543210.

Algorithm


Note: Assume that all numeric values are hexadecimal numbers, or the representation of a sequence of bytes as a hexadecimal number.


The following are the BDK, KSN, and encrypted track message (cryptogram) we’ve been given:

bdk = 0123456789ABCDEFFEDCBA9876543210
ksn = FFFF9876543210E00008
cryptogram = C25C1D1197D31CAA87285D59A892047426D9182EC11353C051ADD6D0F072A6CB3436560B3071FC1FD11D9F7E74886742D9BEE0CFD1EA1064C213BB55278B2F12

Here’s an example of the unencrypted track 1 data (cryptogram above), and below that is its value in hex; this is what we’ll get after successfully decrypting the cryptogram:

%B5452300551227189^HOGAN/PAUL      ^08043210000000725000000?
2542353435323330303535313232373138395E484F47414E2F5041554C2020202020205E30383034333231303030303030303732353030303030303F00000000

Note: As you’re probably already aware, this algorithm is best described using big numbers, which can’t be represented as literals in some programming languages (like Java or C#). However, many languages have classes that allow you to represent big numbers in other ways (e.g., java.math.BigInteger, System.Numerics.BigInteger). It’s your job to adapt this algorithm so that it can be represented in your language of choice. Two small problems I encountered were ensuring the correct endianness and signedness were being used (this algorithm requires the byte order to be big endian and that unsigned integers are used). I made a utility class called BigInt to do this for me.


First, let’s define a few standard functions:

  • DES and Triple DES refer to their respective cryptographic algorithms. Most programming languages have access to some implementation of these ciphers either through OpenSSL or Bouncy Castle. These ciphers are initialized with a zeroed out IV of 8 bytes, they’re zero-padded, and use Cipher-Block Chaining (CBC). Let’s define the signatures for these standard functions that’ll be used throughout this algorithm:
    • DesEncrypt(key, message) -> returns cryptogram
    • DesDecrypt(key, cryptogram) -> returns message
    • TripleDesEncrypt(key, message) -> returns cryptogram
    • TripleDesDecrypt(key, cryptogram) -> returns message

First we must create the IPEK given then KSN and BDK:

CreateIpek(ksn, bdk) {
    return TripleDesEncrypt(bdk, (ksn & KsnMask) >> 16) << 64 
         | TripleDesEncrypt(bdk ^ KeyMask, (ksn & KsnMask) >> 16)
}

Now we can get the IPEK:

ipek = CreateIpek(ksn, bdk)
     = CreateIpek(FFFF9876543210E00008, 0123456789ABCDEFFEDCBA9876543210)
     = 6AC292FAA1315B4D858AB3A3D7D5933A

After that we need a way to get the Session Key (this one is more complicated):

CreateSessionKey(ipek, ksn) {
    return DeriveKey(ipek, ksn) ^ FF00000000000000FF
}

The DeriveKey method finds the IKSN and generates session keys until it gets to the one that corresponds to the current KSN. We define this method as:

DeriveKey(ipek, ksn) {
    ksnReg = ksn & FFFFFFFFFFE00000
    curKey = ipek
    for (shiftReg = 0x100000; shiftReg > 0; shiftReg >>= 1)
        if ((shiftReg & ksn & 1FFFFF) > 0)
            curKey = GenerateKey(curKey, ksnReg |= shiftReg)
    return curKey
}

Where the GenerateKey method looks like:

GenerateKey(key, ksn) {
    return EncryptRegister(key ^ KeyMask, ksn) << 64 
         | EncryptRegister(key, ksn)
}

And EncryptRegister looks like:

EncryptRegister(key, reg) {
    return (key & FFFFFFFFFFFFFFFF) ^ DesEncrypt((key & FFFFFFFFFFFFFFFF0000000000000000) >> 64, 
                                                  key & FFFFFFFFFFFFFFFF ^ reg)
}

Then you can generate the Session Key given the IPEK and KSN:

key = CreateSessionKey(ipek, ksn)
    = CreateSessionKey(6AC292FAA1315B4D858AB3A3D7D5933A, FFFF9876543210E00008)
    = 27F66D5244FF621EAA6F6120EDEB427F

Which can be used to decrypt the cryptogram:

message = TripleDesDecrypt(key, cryptogram)
        = TripleDesDecrypt(27F66D5244FF621EAA6F6120EDEB427F, C25C1D1197D31CAA87285D59A892047426D9182EC11353C051ADD6D0F072A6CB3436560B3071FC1FD11D9F7E74886742D9BEE0CFD1EA1064C213BB55278B2F12)
        = 2542353435323330303535313232373138395E484F47414E2F5041554C2020202020205E30383034333231303030303030303732353030303030303F00000000
        = %B5452300551227189^HOGAN/PAUL      ^08043210000000725000000?

That’s it, you’re done!

Advertisement

EFTPOS Initialisation using RSA Cryptography

Before you start with RSA, you should generate a public and private key pair using your HSM. These can be group keys or specific to the terminal you need to connect. Your terminal manufacturer will also provide its public key and modulus. Using these keys you will be able to calculate the TMK1 and TMK2 and also your session keys. The process is in fact very simple.

Here is an example of how to create these keys using a Thales HSM

Generating an 1536 bit RSA Key

Input

001-EI2153601

Output

001-EJ00
Public Key
3081C80281C0A0FAFB1789B87F6F075B04FE60B5F20AC9D658E6C9B9B4E82AD41FD748A5A00CAF0A5691D2D01726AB073AFB7B91810430F240244E0D4737A397C747FC67C622B12E3654DCDF4F58EE29241616AE7EBA08A1E16DB79E09529FB6CA92213F2DFAB3F677793BF977D640107FBF9833842A0BFBF5F871709E78EE5A152E0BBBBBDDED80D193BAC3033FE412B3C420532A8B309942E76F7A9FB4475B8EDEFDDADC4C101FF02F74BEE0261C681E314124654C39411E2CE56FE719A45CA7592B8431D30203010001
Private key length
0488
Private Key
4E79F95F16AFF16278A893722DA94C8EBFEB013126EC0E98C9CBCBD99DB6D4E82336BD33631CB859D0506D4C2B69DAB818AEE965E73417006774DD746033A6F6EEC1AE3C823E3E20561C84B26885D9D9AE66A552864C75E2B8759B6909DA13CFE70FCB31358A56711549FB2ECC20E4EC3227309D074AE85307C98CF234AF115183716461A701E9FF877F118A5187C27D96B33BE88851ED75D71760DF671CBBA15F1EA7F54CC6205B6997669B6ED9C7448C3D0F451E229E44CC5474462D161A5A89E3D6A473080A8C734E4D5440D2E2A6530D5A848B8B2A0EE637ECF8F604D89449EA9922E115885C8024F6B765C16285C2FC5631CC8C437885170E96CD1D2CB748E4B7FE7FC40517705BC96C22C278BD15CEB51E4D49A722C09237E164D5091EBE847629488180972A1EF6626619B7A16F720D725EFB5C1164E44F915024414BEBF6CE6D258275398D35F38FDC2354F16CEECB7DA77D0E5EC3317D05B351D6938C888A88A9B588C8E88518EFD7581075CD6AA206690E865CA528D5BED5151B9BCAB892CCA49F43349F9F28C5502FC8CA5D2B6D84E57169AAD665961F28797995891B6520822134DBC92ADE13F4D154F520B5BD6EBEBF3620C3CEF941CF7A2302431FEB68C0093A0EE7CF14433F2E9E1A403E545FA96B4BF580D4C17FC26C6E93DADC23738B37E917

Generate a MAC on 1536 RSA key

Input

002-EO01<3081C80281C0A0FAFB1789B87F6F075B04FE60B5F20AC9D658E6C9B9B4E82AD41FD748A5A00CAF0A5691D2D01726AB073AFB7B91810430F240244E0D4737A397C747FC67C622B12E3654DCDF4F58EE29241616AE7EBA08A1E16DB79E09529FB6CA92213F2DFAB3F677793BF977D640107FBF9833842A0BFBF5F871709E78EE5A152E0BBBBBDDED80D193BAC3033FE412B3C420532A8B309942E76F7A9FB4475B8EDEFDDADC4C101FF02F74BEE0261C681E314124654C39411E2CE56FE719A45CA7592B8431D30203010001>

Output

002-EP00<C905141E><3081C80281C0A0FAFB1789B87F6F075B04FE60B5F20AC9D658E6C9B9B4E82AD41FD748A5A00CAF0A5691D2D01726AB073AFB7B91810430F240244E0D4737A397C747FC67C622B12E3654DCDF4F58EE29241616AE7EBA08A1E16DB79E09529FB6CA92213F2DFAB3F677793BF977D640107FBF9833842A0BFBF5F871709E78EE5A152E0BBBBBDDED80D193BAC3033FE412B3C420532A8B309942E76F7A9FB4475B8EDEFDDADC4C101FF02F74BEE0261C681E314124654C39411E2CE56FE719A45CA7592B8431D30203010101>

This is a generic version of RSA encryption using POS pinheads, there are variations in the field. Please keep that in mind when reading this.

Now when a POS terminal logs on for the first time it shall always logon using a 9820 message with a network management information code of 191, containing the TCU public key signed by the manufacturer’s secret key, and the un-enciphered PPID.

The Financial Switch shall respond with a 9830 message with the same network management information code, communicating the public key of the sponsor host (PKsp), and a random number.

The PIN Pad shall then generate the KI and send a 9820 message with a network management information code of 192 to the Financial Switch, containing the KI, PPID, date & time stamp, the random number and user data enciphered under the Financial Switch’s public key (PKsp) and signed by the TCU’s secret key (SKtcu). You will need to extract this information using your HSM H8 command, example below:

Input Data:

001-H801<FDC694A6>
<30550250AB378F98E373BBC6FA5E698F4F095A6D693A851E53C35CC9633947399C09D70932776DBEA5F2F0F0C4DAB4693CACB4D07B19242FF0435C55E3D4E28EFD563457F7EBA31BE1123DEA78CEC1573716130B020103>
;990192
<99658789F42672E7C51CB6ECAF3F061BBABCD954D4113E1CD9BD7BD4DF1BD94E6CBC10F497E9AE68265E87F77BFF293AA2D9FDE9C1A8F12A04D9B4D8DB9F5EAEE4690883838DEF670174E70C79E674F97E2457DD85EEEB346A17DD1F39CB3E8B2D69949436051994F8687F0FEE6558F28180D5A63946CD60604B1C82F6AE14454F5824CBFDCEE07478D2F0239299B64CD900DFF7559423E98F0C7AB8229933E4DD5A5E0BD736F8172668676949493577E323FC8EC592437F6DF20EDB5FBB6E92>
;0080
<7C9DDD3AEFF1D50BAFD11DBAF240BE827BAA156F9E8BB555CC019E183B3708F26EBE6C94702A9AD7CC1D2159CF587437532969D113C70BD622EB81AFC06E9408F1B69F3ED838A9EADFB41FB0E6E4202E>
;1234567890123456;000

Response:

001-H900
H604A678C8C78E1B9CFD415220D418E76
U9912C5D8B113B5E9D6787D57EE9E43BA
1122334455
9876543210987654

 

The Financial Switch shall check the PPID and random number. If the check fails, it will respond with a 9830 with a response code of “63”.

Where the Financial Switch is satisfied with the contents of the second 9820 message, it shall respond with the KCA and the KMACH enciphered under KI and its AIIC in the clear. When the PIN Pad has deciphered KCA and KMACH, it shall erase KI.

At this time the PIN Pad shall calculate the KIA. When the KIA has been calculated, the PIN Pad shall erase KCA.

The POS terminal shall then generate a 9820 message with a network management information code of 193 to the Financial Switch containing the PPID and the Financial Switch shall respond with a 9830 response containing the two initial KEKs and the PPASN.

You can generate this using the C0/C1 HSM command.

The POS terminal shall validate the MAC on the two KEKs and the PPASN and, if the MAC is valid, shall install KEK1, KEK2 and the PPASN and shall calculate the single length DES key KMACI. These keys are the terminal initial keys, that will updated in the season key exchange.

Once this has been carried out, the PIN Pad shall erase the KIA.

When these tasks have been completed, the POS terminal shall carry out its normal logon and session key installation with the Financial Switch. As the processing (initial logon then normal logon and session key installation) completes, the POS terminal will move into the “Ready” state.

easy as pie!

ATM Pin encryption using 3DES

Introduction

Most modern ATM’s use a Triple Des algorithm to encrypt the pin and send it to a host server for processing. Once the host system receives the pin, it does a translation of the pin from one encryption key to another, and sends it to a bank. In this post I will attempt to explain the process and how it is done in the real world.

Overview of the Triple Data Encryption Standard

What we all call Triple DES is EDE (encrypt, decrypt, encrypt). The way that it works is that you take three 56-bit keys, and encrypt with K1, decrypt with K2 and encrypt with K3. There are two-key and three-key versions. Think of the two-key version as merely one where K1=K3. Note that if K1=K2=K3, then Triple DES is really Single DES.

Triple DES was created back when DES was getting a bit weaker than people were comfortable with. As a result, they wanted an easy way to get more strength. In a system dependent on DES, making a composite function out of multiple DESes is likely to be easier than bolting in a new cipher and sidesteps the political issue of arguing that the new cipher is better than DES.

As it turns out, when you compose a cipher into a new one, you can’t use a double enciphering. There is a class of attacks called meet-in-the-middle attacks, in which you encrypt from one end, decrypt from the other, and start looking for collisions (things that give you the same answer). With sufficient memory, Double DES (or any other cipher) would only be twice as strong as the base cipher — or one bit more in strength.

There’s more to it. If the cipher forms a group, then encrypting twice with two keys is equivalent to encrypting once with some key. Now, it’s not trivial to know what that other key is, but it means that a brute-force attack would find that third key as it tried all possible single-keys. So if the cipher’s a group, then multiple-ciphering is merely a waste of time.

Applying this encryption in Python is trivial as there are plenty of tested libraries that can provide the functionality like pyDes and Crypto :

import os
from Crypto.Cipher import DES3

def encrypt_file(in_filename, out_filename, chunk_size, key, iv):
    des3 = DES3.new(key, DES3.MODE_CFB, iv)

    with open(in_filename, 'r') as in_file:
        with open(out_filename, 'w') as out_file:
            while True:
                chunk = in_file.read(chunk_size)
                if len(chunk) == 0:
                    break
                elif len(chunk) % 16 != 0:
                    chunk += ' ' * (16 - len(chunk) % 16)
                out_file.write(des3.encrypt(chunk))

def decrypt_file(in_filename, out_filename, chunk_size, key, iv):
    des3 = DES3.new(key, DES3.MODE_CFB, iv)

    with open(in_filename, 'r') as in_file:
        with open(out_filename, 'w') as out_file:
            while True:
                chunk = in_file.read(chunk_size)
                if len(chunk) == 0:
                    break
                out_file.write(des3.decrypt(chunk))

 

ATM Internals and how they calculate the keys

When you have an ATM, you typically need to provide it with a set of encryption keys from your host, or HSM. These keys are clear text keys and it’s not encrypted in any way. Your host will link them to your terminal number, and when the ATM encrypts the pin; the host will know what keys are used so it can decrypt / translate them to the bank. The clear keys are never stored by the host, only the LMK encrypted keys.

Lets assume your host provides the following keys to you as the ‘ATM Encryption Key’ :

Clear component A: 67C4 A719 1ADA FD08 6432 CE0D D638 4AB
Key check value: 20D40B
Clear component B: 8A89 6D4C 4625 5E2A 1A75 2002 07A7 D35E
Key check value: 4EC801
Combined Check Value: 2B547D

Now typically you would enter the clear components into the ATM, as Encryption keys, and the ATM will combine them (Basically XOR Them) and derive the check value. If the check value match, then all is good.

What happens at your host end is the following:

Your host will also combine the keys and encrypt them under the LMK (Local Master Key). It will then use this key to encrypt all other keys that are sent to the ATM.

Now the ATM have a Terminal Master Key that it can use to decrypt all keys that are sent to it from the host.

ATM Configuration Request (Key Exchange)

Now when an ATM starts up, the first thing it does it send a configuration request to the host. This request is to get the Third key used in Triple DES.  The Host will generate a random Terminal Pin Key and encrypt it under the Terminal Master Key (TMK). Since the ATM has the Terminal Master Key, it can decrypt the encrypted TPK, and use all 3 Keys now for the Triple DES operations. (it actually uses 2)

The Host would generally execute the A0 Thales command to get this key. He would store the key in the key database to do the decryption / translation later.

 

Pin Encryption / Decryption

When a ATM gets ready to transmit a transaction it does the 3DES operation on the Pin only. the cypher text is now transmitted to the host. The host never knows the pin code, and only does a translation of the pin from the terminal keys to the bank keys.

The Host will have the following:

(ZPK) Zone Pin Key – from the Bank during Host to Bank Key exchange

(TPK) Terminal Pin Key – from Terminal using Terminal Configuration Request

(PAN) Account Number –  from Transaction transmitted.

With these values, the Host can translate the pin using a HSM, below is an example of the D4 Command.

 Res = KeyGenerator.TranslatePIN_TDES(TerminalPINKey=self.Crypto["TPK_LMK"], PINEncryptionKey=self.HostKeys["ZPK_LMK"], PINBlock=self.iso.getBit(52), AccountNumber=track2["PAN"][-13:-1])

def get_commandTPKPinBlock(self, TerminalPINKey, PINEncryptionKey, PINBlock, AccountNumber):

 command_code = 'D4'
 KTP = TerminalPINKey
 KPE = PINEncryptionKey
 PinBlock = PINBlock
 PAN = AccountNumber


 message = command_code
 message += KTP
 message += KPE
 message += PinBlock
 message += PAN
 return message
#transmit to HSM

The transaction can now be transmitted to the acquiring bank with the translated pin for processing.

Sometimes the ATM requires a Message Authentication Code, this will be covered in another post.

easy as pie