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




Public Key
Private key length
Private Key

Generate a MAC on 1536 RSA key





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:





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


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:
                elif len(chunk) % 16 != 0:
                    chunk += ' ' * (16 - len(chunk) % 16)

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:


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



Implementing AS2805 Part 6 Host to Host Encryption using a Thales 9000 and Python


The AS2805.6 Standard specifies communication security between two nodes during a financial transaction. These nodes needs to have a specific set of encryption algorithms, and needs to follow a specific process.

The specification is not very clear on what exactly needs to happen, so I intend to clarify the exact steps, with the HSM functions. Now in order to do this I will assume you have a Thales 9000 HSM, as well as you need to know how to properly operate it. All commands defined are in the 1270A547-015 Australian Standards LIC003 v2.3a.pdf Manual provided by Thales when purchasing the device.

Source Code

a Copy of this Manual can be found  here  [Thales 9000 Australian Standards LIC003 v2.3a]

a Copy of my AS2805  parser is located here

a Copy of my Thales commands class is located here

a Full version of a AS2805 Interchange Node is located here

KEK Process (Level 1)

For this process:

  1. you need to go to your HSM and generate 2 Clear components, you then need to form a KEKs key from these components. This can be done using the UI of the HSM manger, or with the FK console command.
  2. Store the KEKs formed from the clear components in your switch database.
  3. Your connecting node / host will then provide you with a set of clear components, you need to generate a key again, but in this case a KEKr
  4. You need to provide you host with your key components you generated in Step 1,so they can generate their corresponding KEKs.

Now you have a KEKr and a KEKs in your database as well as your host read,  for Level2

Session and MAC key Initialisation (Level 2)

This Level has 2 separate steps, the first step (Logon) validating the KEKr and KEKs so that both nodes know that the correct keys are being used. The second step (Key Exchange) is to create temporary keys that are changed every 60 minutes or 256 transactions.

Logon Process


During the logon process your HSM will need to generate 2 things:

  1. a Random Number (RN)
  2. an Inverted Random Number (~RN)

These numbers will be returned encrypted under the KEKr and KEKs, and you will need to validate them, this is also called end of proof point validation.

The Logon process is a 2 step process outlined in the image below.

Step 1

When you connect to your host you will receive a logon request, bit number 48 will be populated with a KRs from the host that you will need to validate with your KEKr.

Generating a KEKr Validation Response you would need your KRs received in this request, and you KEKr that you generated from your host components.

E2 Command Definition: To receive a random key (KRs) encrypted under a variant of a double length Key Encrypting Key (KEKr), compute from KRs another value, denoted KRr and encrypt it under another variant of the KEKr

Your HSM command will look as follows: >HEADE2{KEKr}{KRs} and you output will generate a KEKr. Your response to the host will need to include this value in bit number 48.

Step 2

You now need to send the host a logon request with bit 48 set with your KRs

E0 Command Definition:To generate a random key (KRs) and encrypt it with a variant of a double length Key Encrypting Key (KEKs). In addition, KRs is inverted (to form KRr) and the result encrypted with another variant of the KEKs.

Your HSM command will look as follows: >HEADE0{KEKs} and the output will generate a KRs.  Your host will validate this request, and return with a response.

Once both steps are complete, both you and the host has been validated that you are using the same keys.

An Example of this process is outlined below in Python:


 def __signon__Part1__(self):
 self.log.info("====Sign-On Process Started ====")
 cur = self.con_switch.cursor(MySQLdb.cursors.DictCursor)

 self.log.info("Waiting for 0800 Request")
 length_indicator = self.s.recv(2)
 if length_indicator == '':
 self.log.critical('Received a blank length indicator from switch... might be a disconnect')
 size = struct.unpack('!H', length_indicator)[0]
 payload = self.s.recv(size)
 payload = ByteUtils.ByteToHex(payload)
 d = datetime.now()
 self.log.info(" Getting Sign-On Request 0800 = [%s]" % payload)
 if payload == '':
 self.log.critical('Received a blank response from switch... might be a disconnect')
 iso_ans = AS2805(debug=False)

 self.__storeISOMessage(iso_ans, {"date_time_received": d.strftime("%Y-%m-%d %H:%M:%S")})
 if iso_ans.getMTI() == '0800':
 if iso_ans.getBit(70) == '001':
 #log.info("Logon Started with KEKr = %s, KEKs = %s" % ( self.KEKr, self.KEKs))
 KRs = iso_ans.getBit(48)
 #log.info("KRs %s Received from Host" % (KRs))
 #print "Generating a E0 Command with KEKr=%s, and KRs=%s" % (self.KEKr, KRs)
 self.ValidationResponse = KeyGenerator.Generate_KEKr_Validation_Response(KEKr=self.KEKr, KRs=KRs)
 #print self.ValidationResponse

 if self.ValidationResponse["ErrorCode"] == '00':
 #log.info("KRs Validation Response %s generated" % (self.ValidationResponse["KRr"]))
 d = datetime.now()
 iso_resp = AS2805(debug=False)
 iso_resp.setBit(7, d.strftime("%m%d%H%M%S"))
 iso_resp.setBit(11, iso_ans.getBit(11))
 iso_resp.setBit(33, self.Switch_IIN)
 iso_resp.setBit(39, '303')
 iso_resp.setBit(48, self.ValidationResponse["KRr"])
 iso_resp.setBit(70, '0001')
 iso_resp.setBit(100, self.Switch_IIN)

 iso_send = iso_resp.getNetworkISO()
 iso_send_hex = ByteUtils.HexToByte(iso_send[2:])
 self.log.info("Sending Sign-On Response 0810 [%s]" % ReadableAscii(iso_send))
 self.__storeISOMessage(iso_resp, {"date_time_sent": d.strftime("%Y-%m-%d %H:%M:%S")})
 self.log.error("0810 KRr Response Code = %s, Login Failed" % (self.ValidationResponse["ErrorCode"],))
 #TODO: Send Decline to the Partner

 self.log.error("Could not login with 0810")

 except InvalidAS2805, ii:
 except socket.error as e:
 self.log.debug("nothing from host [%s]" % (e))

 def __signon_Part2__(self):

 self.ValidationRequest = KeyGenerator.Generate_KEKs_Validation_Request(KEKs=self.KEKs)
 d = datetime.now()
 iso_resp = AS2805(debug=False)
 iso_resp.setBit(7, d.strftime("%m%d%H%M%S"))
 iso_resp.setBit(11, self.__getNextStanNo())
 iso_resp.setBit(33, self.HostIIN)
 iso_resp.setBit(48, self.ValidationRequest["KRs"])
 iso_resp.setBit(70, '001')
 iso_resp.setBit(100, self.HostIIN)
 iso_send = iso_resp.getNetworkISO()
 iso_send_hex = ByteUtils.HexToByte(iso_send[2:])

 self.log.info("Sending Sign-On Request 0800 [%s]" % ReadableAscii(iso_send))
 self.__storeISOMessage(iso_resp, {"date_time_sent": d.strftime("%Y-%m-%d %H:%M:%S")})

 self.log.info("Waiting for 0810 Response")
 a = self.s.recv(8192)
 payload = ByteUtils.ByteToHex(a[2:])
 d = datetime.now()
 self.log.info(" Getting Sign-On Response 0810 = [%s]" % payload)
 iso_ans = AS2805(debug=False)
 self.__storeISOMessage(iso_ans, {"date_time_received": d.strftime("%Y-%m-%d %H:%M:%S")})
 if iso_ans.getBit(39) == '3030':
 self.log.info("====Sign-On Sequence Completed Successfully====")
 self.log.error("Could not login with 0800")
 except InvalidAS2805, ii:
 except socket.error as e:
 self.log.info("nothing from host [%s]" % (e))


Key Exchange (Level 2)

In the Key Exchange process, you will generate session keys for your node as well as MAC keys. Now when generating these keys, you need to remember that they need to be the same type as you partner node. (simply ask your processor for a trace if you want to confirm)

So right after a successful logon, you would need to wait for a key exchange request, (0820 with field 30 as 303) this key exchange request will have  a ZAK and a ZPK in field 48, these are encrypted under the KEKr generated on your host from their components. You would need to translate these keys using your KEKr under your LMK and generate check values for verification.

The command will look like follows: >HEADOK{KEKr}21H{ZPK}1H{ZAK}0H11111111111111111111111111111111

These keys are known as your: RECEIVE KEYS

Where the KEKr is the KEKr generated from your components, ZPK and ZAK is the ZPK and ZAK received. This will output the following:

def Translate_a_Set_of_Zone_Keys(KEKr, ZPK, ZAK, ZEK):
 response = KeyClass.execute_Translate_a_Set_of_Zone_Keys(KEKr, ZPK, ZAK, ZEK)
 #print response
 TranslatedZoneKeys = {}
 TranslatedZoneKeys["Header"] = response[2:6]
 TranslatedZoneKeys["ResponseCode"] = response[6:8]
 TranslatedZoneKeys["ErrorCode"] = response[8:10]
 if TranslatedZoneKeys["ErrorCode"] == '00':
 TranslatedZoneKeys["KCV Processing Flag"] = response[10:11]
 TranslatedZoneKeys["ZPK(LMK)"] = response[11:44]
 TranslatedZoneKeys["ZPK Check Value"] = response[44:50]
 TranslatedZoneKeys["ZAK(LMK)"] = response[50:83]
 TranslatedZoneKeys["ZAK Check Value"] = response[83:89]
 TranslatedZoneKeys["ZEK(LMK)"] = response[89:122]
 TranslatedZoneKeys["ZEK Check Value"] = response[122:128]
 return TranslatedZoneKeys

In other words, you need to generate the same keys, but under your LMK and store them in your key database

Now whenever you get a request from your host with a mac you can validate the mac using the ZAK(LMK), and when you get encrypted values from your host you can translate the values using the ZPK(LMK)

So, when you respond to the key exchange process you put the check values in field 40. Your host will validate the check values, and then wait for you to send a request using your KEKs.

Here is an implementation using Python:

def __key_exchange_listen(self):
 self.log.info("===== Key Exchange process Started =======")
 length_indicator = self.s.recv(2)
 if length_indicator == '':
 self.log.critical('Received a blank length indicator from switch... might be a disconnect')
 size = struct.unpack('!H', length_indicator)[0]
 payload = self.s.recv(size)
 payload = ByteUtils.ByteToHex(payload)
 d = datetime.now()
 self.log.info(" Receiving Key Exchange Request = [%s]" % payload)
 if payload == '':
 self.log.critical('Received a blank response from switch... might be a disconnect')
 iso_ans = AS2805(debug=False)
 iso_ans.setIsoContent("%s" % (payload))

 self.__storeISOMessage(iso_ans, {"date_time_received": d.strftime("%Y-%m-%d %H:%M:%S")})
 if iso_ans.getMTI() == '0820' and iso_ans.getBit(70) == '0101':
 Value = iso_ans.getBit(48)
 self.ZAK = Value[:32]
 self.ZPK = Value[32:]

 self.node_number = iso_ans.getBit(53)
 log.info("Recieve Keys under ZMK : ZAK= %s, ZPK = %s" % (self.ZAK, self.ZPK ))

 self.ZoneKeySet2 = KeyGenerator.Translate_a_Set_of_Zone_Keys(self.KEKr,ZPK=self.ZPK, ZAK=self.ZAK, ZEK='11111111111111111111111111111111')
 cur = self.con_switch.cursor(MySQLdb.cursors.DictCursor)
 sql = """UPDATE sessions_as2805 set
 ZPK_LMK = '%s',
 ZPK_ZMK = '%s',
 ZPK_Check ='%s',
 ZAK_LMK = '%s' ,
 ZAK_ZMK = '%s',
 ZAK_Check = '%s',
 ZEK_LMK = '%s',
 ZEK_Check = '%s',
 keyset_number = '%s'
 WHERE host_id = '%s' and keyset_description = 'Recieve' """ %\
 self.ZoneKeySet2["ZPK Check Value"],
 self.ZoneKeySet2["ZAK Check Value"],
 self.ZoneKeySet2["ZEK Check Value"],
 log.info("Recieve Keys under LMK : ZAK= %s, ZAK Check Value: %s ZPK = %s, ZPK Check Value: %s" % (self.ZoneKeySet2["ZAK(LMK)"], self.ZoneKeySet2["ZAK Check Value"], self.ZoneKeySet2["ZPK(LMK)"], self.ZoneKeySet2["ZPK Check Value"]))
 self.log.debug("Records=%s" % (cur.rowcount,))
 iso_req = AS2805(debug=False)
 iso_req.setBit(7, iso_ans.getBit(7))
 iso_req.setBit(11, iso_ans.getBit(11))
 iso_req.setBit(33, iso_ans.getBit(33))
 iso_req.setBit(39, '303')
 iso_req.setBit(48, self.ZoneKeySet2["ZAK Check Value"] + self.ZoneKeySet2["ZPK Check Value"])
 iso_req.setBit(53, iso_ans.getBit(53))
 iso_req.setBit(70, iso_ans.getBit(70))
 iso_req.setBit(100, iso_ans.getBit(100))
 self.__storeISOMessage(iso_req, {"date_time_sent": d.strftime("%Y-%m-%d %H:%M:%S")})

 iso_send = iso_req.getNetworkISO()
 iso_send_hex = ByteUtils.HexToByte(iso_send[2:])

 self.log.info("Sending Key Exchange Response = [%s]" % ReadableAscii(iso_send))
 self.node_number = iso_ans.getBit(53)



These Keys are known as your SEND KEYS

So when you send a key exchange request you would need to generate a set of zone keys, this command on your HSM would look like this;


Where the KEKs is the KEKs that you generated from your components, and your output will be the following:

def Generate_a_Set_of_Zone_Keys(KEKs):
 response = KeyClass.execute_get_a_Set_of_Zone_Keys(KEKs)
 #print response
 ZoneKeys = {}
 ZoneKeys["Header"] = response[2:6]
 ZoneKeys["ResponseCode"] = response[6:8]
 ZoneKeys["ErrorCode"] = response[8:10]
 if ZoneKeys["ErrorCode"] == '00':
 ZoneKeys["ZPK(LMK)"] = response[10:43]
 ZoneKeys["ZPK(ZMK)"] = response[43:76]
 ZoneKeys["ZPK Check Value"] = response[76:82]
 ZoneKeys["ZAK(LMK)"] = response[82:115]
 ZoneKeys["ZAK(ZMK)"] = response[115:148]
 ZoneKeys["ZAK Check Value"] = response[148:154]
 ZoneKeys["ZEK(LMK)"] = response[154:187]
 ZoneKeys["ZEK(ZMK)"] = response[187:220]
 ZoneKeys["ZEK Check Value"] = response[220:226]
 return ZoneKeys

Now when sending your  0820 request, you need to set field 40 as ZAK(ZMK) + ZPK(ZMK). Your host will do a Validation request (same as you did in step 1) and send you the check values. you need to compare this to the check values generated by your OI command, and if they match then you have successfully exchanged keys.

Below is an implementation using Python:


 def __keyExchange__(self):


 cur = self.con_switch.cursor(MySQLdb.cursors.DictCursor)
 d = datetime.now()
 self.ZoneKeySet1 = {}
 self.ZoneKeySet2 = {}
 self.ZoneKeySet1 = KeyGenerator.Generate_a_Set_of_Zone_Keys(self.KEKs)

 iso_req = AS2805(debug=False)
 iso_req.setBit(7, d.strftime("%m%d%H%M%S"))
 iso_req.setBit(11, self.__getNextStan())
 iso_req.setBit(33, self.HostIIN)
 iso_req.setBit(48, self.ZoneKeySet1["ZAK(ZMK)"][1:] + self.ZoneKeySet1["ZPK(ZMK)"][1:])
 iso_req.setBit(53, self.node_number)
 iso_req.setBit(70, '101')
 iso_req.setBit(100, self.SwitchLink_IIN)
 self.__storeISOMessage(iso_req, {"date_time_sent": d.strftime("%Y-%m-%d %H:%M:%S")})
 log.info("Send Keys under LMK : ZAK= %s, ZAK Check Value: %s ZPK = %s, ZPK Check Value: %s" % (self.ZoneKeySet1["ZAK(LMK)"], self.ZoneKeySet1["ZAK Check Value"], self.ZoneKeySet1["ZPK(LMK)"], self.ZoneKeySet1["ZPK Check Value"]))


 # send the Send Keys
 iso_send = iso_req.getNetworkISO()
 iso_send_hex = ByteUtils.HexToByte(iso_send[2:])

 self.log.info("Sending Key Exchange Request = [%s]" % ReadableAscii(iso_send))

 length_indicator = self.s.recv(2)
 if length_indicator == '':
 self.log.critical('Received a blank length indicator from switch... might be a disconnect')
 size = struct.unpack('!H', length_indicator)[0]
 payload = self.s.recv(size)
 payload = ByteUtils.ByteToHex(payload)
 d = datetime.now()
 self.log.info(" Receiving Key Exchange Response = [%s]" % payload)
 if payload == '':
 self.log.critical('Received a blank response from switch... might be a disconnect')
 iso_ans = AS2805(debug=False)
 self.__storeISOMessage(iso_ans, {"date_time_received": d.strftime("%Y-%m-%d %H:%M:%S")})

 if iso_ans.getMTI() == '0830':
 if iso_ans.getBit(39) == '3030':

 Value = iso_ans.getBit(48)
 self.KMACs_KVC = Value[:6]
 self.KPEs_KVC = Value[6:]
 #self.log.info("KMACs_KVC = %s, KPEs_KVC = %s" % (self.KMACs_KVC, self.KPEs_KVC))
 if self.KMACs_KVC == self.ZoneKeySet1["ZAK Check Value"] and self.KPEs_KVC == self.ZoneKeySet1["ZPK Check Value"]:
 self.log.info("0820 Key Exchange successful: Check Values Match, ZAK Check Value= %s , ZPK Check Value = %s" % (self.ZoneKeySet1["ZAK Check Value"], self.ZoneKeySet1["ZPK Check Value"]))
 sql = """UPDATE sessions_as2805
 ZPK_LMK = '%s',
 ZPK_ZMK = '%s',
 ZPK_Check= '%s' ,
 ZAK_LMK= '%s',
 ZAK_ZMK = '%s',
 ZAK_Check ='%s',
 ZEK_LMK = '%s' ,
 ZEK_ZMK = '%s',
 ZEK_Check = '%s',
 keyset_number = '%s'
 WHERE host_id = '%s' and keyset_description = 'Send' """%\
 ( self.ZoneKeySet1["ZPK(LMK)"],
 self.ZoneKeySet1["ZPK Check Value"],
 self.ZoneKeySet1["ZAK Check Value"],
 self.ZoneKeySet1["ZEK Check Value"],

 self.log.debug("Records=%s" % (cur.rowcount,))

 self.log.info("==== Key Exchange Sequence Completed Successfully====")
 self.last_key_exchange = datetime.now()

 self.log.error("Generate_a_Set_of_Zone_Keys: KVC Check Failed!!")
 self.log.error("0820 Response Code = %s, Key Exchange Failed" % (iso_ans.getBit(39)))
 except InvalidAS2805, ii:
 self.s = None


Now that keys have successfully been exchanged, you can start submitting transactions.

When sending transactions encrypt data (pin / field) Send Keys, and when receiving data translate / decrypt using your receive keys, Generate MAC using Send MAC and Verify using Receive MAC.

  • TAK – Your key to generate and verify MACs
  • TEK – Your key to encrypt data and decrypt / translate

This concludes the implementation of Node to Node interfaces using AS2805 Standards.

Easy as Pie!

Typical Cryptography in AS2805 Explained

Key Management conforms to AS 2805 part 6.1.

KEK Establishment

Each interchange node contains an Interchange Send Key Encrypting Key (KEKs) and an Interchange Receive Key Encrypting Key (KEKr). The Interchange Send KEK is the same key as the Interchange Receive KEK in the partnering node, similarly the Interchange Receive KEK is the same as the Interchange Send KEK in the partnering node.

The Interchange Key Encrypting Keys are used to encipher and decipher the session keys when they are transmitted between the nodes and in the proof of end points process.

Interchange Key Encrypting Keys is statistically unique and shall be changed, at a minimum, once every two years.


Node A Node B
KEkr = KEKs

Session Keys

Each node keeps four sets of session keys, two send sets and two receive sets.

Each set of session keys consists of two keys, MAC Key, PIN Protect Key. Each session key is 128-bits long and stored in a secure manner.

The send session key sets are generated by the sending node and numbered “1” or “2”. The send session key sets are then forwarded to the receiving node to be used as the receive session key sets.

The receive session key sets are received in a 0820 Network Management Advice message with bit ‘070’ equal to 101 from the sending node. The set number of either “1” or “2” contained in bit 53 indicates the receive session key set used by the receiving node to verify the MAC, decipher the data and translate or verify the PIN.

One set of send session keys is used at a time and all Transactions sent from the sending node will generate the MAC and encipher the PIN, if present, using the MAC Generator Key and PIN Protect Key, respectively, from the same send session key set. The send session key set used is indicated by bit 53 (contains “1” or “2”) in each message. Session Keys must be statistically unique and replaced, at a minimum, once every hour or on every 256 Transactions, whichever occurs first.



Node A Node B
Send Session Keys Set 1 Receive Session Keys Set 1
MAC Key (KMACs1) = MAC Verification Key (KMACr1)
PIN Protect Key (KPEs1) = PIN Protect Key (KPEr1)
Send Session Keys Set 2 Receive Session Keys Set 2
MAC Key (KMACs2) = MAC Verification Key (KMACr2)
PIN Protect Key (KPEs2) = PIN Protect Key (KPEr2)
Receive Session Keys Set 1 Send Session Keys Set 1
MAC Verification Key (KMACr1) = MAC Key (KMACs1)
PIN Protect Key (KPEr1) = PIN Protect Key (KPEs1)
Receive Session Keys Set 2 Send Session Keys Set 2
MAC Verification Key (KMACr2) = MAC Key (KMACs2)
PIN Protect Key (KPEr2) = PIN Protect Key (KPEs2)


When enciphered for transmission, each session key type will use a unique variant of the Key Enciphering Key in accordance with AS 2805 part 6.1 request response (logon) from the other before starting any other message exchange. When ready to logon, a party should attempt to logon and continue to attempt to logon until a successful response has been received. Upon receipt of an unsolicited logon (i.e. receiving a logon message when in an assumed logged on state) or a message with a response code indicating an irrecoverable error, a party should send an immediate logoff message and attempts to logon should be made as soon as possible. All logon response messages should be inspected to ensure that the response code indicates a successful logon

Changing Session keys

While one set of send session keys is being used, the other send session key set is randomly generated by the sending node and their KVCs generated, the keys are then enciphered under the Interchange Send KEK and transmitted to the receiving node in a 0820 Network Management Advice message.

When a 0820 message is received by the receiving node, the session keys are deciphered using the Interchange Receive KEK. These deciphered keys are set up as the set of receive keys specified by the set number contained in bit 53 of the 0820 message. The Key Verification Codes (KVCs) are calculated by the receiving node and transmitted to the sending node in bit 48 of the 0830 message.

When the 0830 Network Management Advice response message is received at the node initiating the key change, the KVCs contained in the 0830 message are validated. If the KVCs are correct, the new send session key set can be used immediately. If the KVCs are invalid, new send session key set must be generated and the whole process is repeated.


Sign off

Either node may terminate the transmission of financial messages by sending a Sign Off Advice. A Sign Off is accomplished by the transmission of a 0820 Network Management Advice Message with a NMIC (Bit 70) equal to ‘002’.


Key change during normal processing

A session key change can occur at any time; each node independently initiates the change of their send keys. The sender will advise their sending session keys to the receiver using a 0820 Network Management Advice message with a NMIC equal to ‘101’ indicating key change. Once a valid response (0830 message) is received and the KVCs confirmed, the new keys can be used.

Thales 9000 with AS2805 Interchange & RSA EFTPOS Commands.

Interchange Cryptographic Keys 

Interchange keys are used to protect financial transactions initiated at Acquirer eftpos / ATM Terminals while in transit to the Issuer institution. Interchange keys may be either:

(a) PIN encrypting keys – used to protect the customer PIN from the point of origin to the point of authorisation. PIN encrypting keys are a specific instance of session keys;

(b) Session keys – used to secure, validate and protect the financial message. Session keys can be further qualified into those used in the terminal to Acquirer environment (terminal session keys) or on node to node links (interchange session keys);

(c) Key Encrypting Keys (KEK) – used to protect other keys (e.g. session keys) during exchange; or

(d) Transport Keys – used to protect keys (e.g. KEKs) during transport to the partner institution.

Cryptographic Algorithms 

DEA3 and DEA2 are the only approved algorithms for the protection of interchange information (full details of these algorithms may be found in the Australian standard AS 2805 part 5).

DEA3 keys are 128 bits in length (effectively 112 bits) and are generally referred to as triple DES or 3DES keys (the corresponding encryption algorithm is specified in AS 2805 part 5.4). Triple DES may also be acceptably implemented using a key length of 192 bits (effectively 168 bits).

DEA3 with a key length of 128 bits and DEA2 with key lengths equal to, or greater than 2048 bits are the minimum acceptable requirements for the effective protection of interchange information at the time of the issuance of this document.

In accordance with AS 2805 part 3, DEA3 must be used for PIN encipherment.

 Interchange Links 

For all Interchange Links, Issuers and Acquirers must ensure that:

(a) Security for Transactions processed over that Interchange Link complies with AS2805 Part 6;

(b) Message formats comply with AS2805 Part 2;

(c) Security of transactions from terminal to Acquirer and from Acquirer to Issuer complies with AS2805 Part 6;

(d) PIN security and encryption complies with AS2805 Parts 3 and 5.4;

(e) Key management practices comply with AS2805 Part 6.1;

In each case and as more particularly set out in Part 8:

(a) Message Authentication must apply to all Interchange Links;

(b) The Message Authentication Code (MAC) must be calculated using, as a minimum, a DEA 3 (128-bit) key, Triple DES and an algorithm conforming to AS2805 Part 4; and

(c) all interchange PIN and MAC cryptographic functions must be performed within a Tamper-responsive SCM

The Actual process using an Thales 9000 HSM (CECS Approved)

Now what we are clear on the actual requirements of CECS and APCA, lets  attempt to do this using  a Thales 9000.

Generate a Sponsor RSA key pair

This command is the first step as would be required to do this for all terminal commands.

  • This is done my using the HSM EI host Command, from the HSM base manual.
    • The input is the length of the RSA key set required,  and the length go the public key modulus.
  • The Public Key Verification Code should now be generated. This is done using the HSM H2 Command from the Australian Standards Support Manual.

The Public Key and the PVC are sent to your Interchange Partner via different paths, as per their direction. (lets call this OUR-Key and OUR-PVC)

Your Interchange partner will now do the same process and provide you with a Public Key and a PVC. (lets call this THEIR-Key and THEIR-PVC)

When we receive this Public Key from our Interchange Partner, the following should happen:

  • The PVC for the Key should be generated using the HSM H2 Command from the Australian Standards Support Manual.
  • The MAC for the Key should be generated using the HSM EO command from the HSM Base Manual.

We now have public keys exchanged and have them ready for use!!

Our Database should be looking like this:


Now we have the Public keys exchanged and ready for use, we can generate our KEKs & send to Interchange Partner, and receive our KEKr from Interchange Partner;

  • To send our KEKs we will use the H4 command from the Australian Standards support manual.
  • To receive our KEKr we will use the H6 command from the Australian Standards support manual.

Once these are decrypted and stored in our key database we can generate and exchange our session MAC and PIN keys.

    • To generate and store our send keys we use the OI command from the Australian Standards support manual.
    • To receive and store our receive keys we use the OK command from the Australian Standards support manual.

Now we have all the keys in place we can start to process transactions.

    • To generate the MAC on a message there are a number of commands available, however as we are using the AS2805 standards we always recommend our customers use the C2 command from the Australian Standards support manual. This provides all the options required for the Australian environment.

Similarly to verify the MAC on a message there are a number of commands available, however as we are using the AS2805 standards we always recommend our customers use the C4 command from the Australian Standards support manual. This provides all the options required for the Australian environment.

Terminal Commands

Terminal Manufacturer will be injecting into the PINpads their Manufacturer Public Key. The MPK will be transmitted to SPONSOR securely. The MPK validity should be checked by verifying the PVC, this is achieved by generating a Public Key Verification Code This is done using the H2 command from the Australian Standards support manual. And the two values compared.

  • We also need to generate a PPASN, this is achieved using the AS2805 PK command.
  • The host will now send the SPK to the PINpad, the PINpad will now generate the KI (also known as KTI), and send to the host. This is recovered using the AS2805 host H8 command, which also returns the KCA, the KCA is encrypted under the LMK and the KTI.
  • Now we have the MPK and have verified it is genuine, we now need to generate a MAC for the Public Key, this is achieved using the Host EO command, this is used in subsequent processing. Note: this command is only available when the HSM is in Authorised State. We can now recover the PINpad Public from the MSK. This is achieved using the AS2805 H0 host command.
  • KCA is now used to create the TMK1 and TMK2 (also known as KEK1 & KEK2). These are generated using the C0 command.
  • Now we have the TMK’s in place we can use the TMK update commands.

Updating the Keys

  • When updating only TMK1 the AS2805 OU command is used.
  • When updating both TMK1 and TMK2 then the OW command is used.

Now we have the TMK’s in place and able to be updated, we can generate the Session Keys to be used for the PIN, MAC & optional encryption keys if required.

This is achieved using the AS2805 PI command. The PI command will generate the PIN, MAC, and optional Encryption keys.

  • Now we can have the session keys in place we can Decrypt the data, verify the MAC & verify the pin. The decrypt data & verify MAC steps depend on how it has been handled by the terminal. Has the terminal done the MAC first then encrypted the required data or has the terminal encrypted the data & then done the MAC. We have assumed that the Encrypt was done first.
  • Verify the MAC’s on the transactions from the terminal using the AS2805 C4.
  • Once the MAC has been verified we can then decrypt the required data with the AS2805 host command PW.
  • Now we have the required decrypted data you will need to either verify the PIN or Translate the PIN, to translate the PIN assuming the transaction is a debit card transaction. This is achieved using the AS2805 PO host command. To verify the PIN will use one of the following F0 or F2.

If you have translated the PIN we can form the message and generate a MAC for the message to be sent to Interchange Partner, this is achieved using the C2 command as detailed above in the Interchange messages.

The biggest problem we see with this are around the KEKs & KEKr is people get them around the wrong way. Your KEKs becomes the remote KEKr & vice versa. The AS2805 commands are designed to swap them over automatically. 

The other gotcha is we split the terminal side & the interchange side of the HSM, TMK (terminal master key) is like a KEK (ZMK (Zone master key)) but used on the terminal side of the network where a ZMK (KEKs & KEKr) is used for interchange side of the network.

 easy as Pie!

Thales Key Exchange Examples and Troubleshooting

Judging from the searches done to locate this blog, it’s clear many of us share the following opinion: although Thales (formerly RACAL) is a market leader with its 7000 and 8000 series of HSM devices, their documentation falls painfully short in two areas: there are NO COMMAND EXAMPLES (!!!) in the manuals (an appalling omission); and the troubleshooting assistance is also distressingly thin. As a result, we had to lean heavily on our local Thales distributor for guidance on how commands really get pieced together. And, man, is it ever esoteric….see my earlier posts regarding the ‘KSN Descriptor’ for evidence of that. Moreover, our distributor provided us with some outstanding troubleshooting support to get us through the all important FA/FB key exhange. So, I’ll post our experience here in hopes that others can benefit from it.

The FA/FB is the command exchange to “Translate a ZPK from ZMK to LMK Encryption.” We had this working internally with some simulated stuff, but once we tried this command ‘for real’ with our Debit/EBT gateway partner , we consistently received parity errors back from our Thales 8000 HSM (i.e., the FB returned with some result code != 0).

There are three possible issues / resolution paths to explore in these situations:

Your switching partner has employed an Atalla HSM and you’ve not taken it into account. When a Thales/RACAL HSM ‘talks’ to an Atalla, your box commands must specify an Atalla Variant.

Your switching partner didn’t specify a Key Scheme in its ZPK creation, and the default is X9.17 (‘X’). If you specify the RACAL Scheme (‘U’) in your ‘FA’ and the ZPK under ZMK provided to the box was created via the X9.17 scheme, you’ll get a parity error.

You created the ZMK cryptogram internally using one key scheme and now are trying to employ it in the FA command specifying (inadvertantly) the other variant scheme.

You want to try to resolve each of these in turn.

The “test solution” path for Item #1 is as follows…

Let’s assume your FA command is constructed like so:


[NOTE: I’ve obscured the ZMK Cryptogram here for blogging purposes only. The actual value is a 32-position hexidecimal string.]

If you discover that the other side is using an Atalla, you need to specify an “Atalla Variant,” which you do by specifying a ‘1’ at the end of the ‘FA’ command string:


The “test solution” path for Item #2 is as follows…

We find some endpoint partners have no idea which Key Scheme (X9.17 or Racal Native) they employed to create their keys. So, you may have to experiment. This FA command string says that the ZMK and ZPK were created using the RACAL native scheme (‘U’):


To specify that the ZPK was created using the X9.17 scheme, you’d do the following:


The “test solution” path for Item #3 is as follows…

When you created your ZMK (probably during a key ceremony involving a reconstitution of key parts provided by your endpoint gateway), you specify (or otherwise let default) your ZMK Key Scheme. Again, this can be either the RACAL Native Scheme (‘U’) or X9.17 (‘X’). [I believe the default is X9.17.] For example, if you created the ZMK using the ‘X’ approach, and then submitted an ‘FA’ command that looks like this:


…it’s gonna fail. You absolutely must maintain consistency from the creation of the ZMK cryptogram through its subsequent usage. So, the command would change to look like this:


[NOTE: I’m not advocating ‘X’ over ‘U’ here…just showing you an example. In a recent concluded project, we assumed the incoming ZPK was of the RACAL native variety, but it arrived from the remote partner as created under the X9.17 scheme. Thing is, the gateway team had no idea they had done that and could not articulate the difference. So, be prepared to experiment with every permutation of what I’ve described herein before ‘unlocking’ the solution.]


Testing DUKPT

As an acquirer, you can validate that your PIN translation command is working correctly even if you haven’t yet established connectivity to your Debit/EBT endpoint (or if you’ve established connectivity but don’t yet have your test key parts).

Typically when we’re pressed into this situation, this is what we do if we’re working with the Key-Up II HSM from Ian Donnelly Systems (‘IDS’):

For simplicity’s sake, we use a weak double-length key part.

We enter it as a single part (again, at this point, we want to keep things simple).
Typically, we use 0123456789ABCDEFFEDCBA9876543210.

We take the Cryptogram obtained out of that exercise and we use that as our Key Exchange Key (“KEK”) input.

Now, in my reading of the Thales manuals, performing this exercise with the Thales device is quite a bit more complicated.

[I’ll use Thales language here so we’re all on the same page…]

GOAL: What you need to test PIN translation is a ZPK encrypted under your LMK. [Refer to my previous post for details on the CI/CJ PIN transalation request/response.]

Note specifically where I describe “PIN Length” on the CJ command output I say:

“Although this field is not used to build the 0200 message formatted for the processor gateway, a value like ‘04’ or ‘05’ here is a pretty good indication that the translation occurred successfully.”

So, we can validate the workability of this command without a working endpoint or ‘real’ key parts from them, but – in order to do so – we need to construct a valid ZPK under LMK cryptogram. This value will allow you to create a completely valid CI command, assuming that:

You’ve got one or more valid BDK cryptograms loaded in your encryption database.

You can generate PIN-enabled Debit purchases from a test point-of-sale location.

You have addressibility from your test server to the Thales.

STEPS: My reading of the Thales manual is that you’ll need to execute the following steps (this is sort of ugly – numbers refer to specific sections in the Operations and Installation manual):

6.1 to create at least two 32-positions ZMK components (or, alternatively, 6.3 if you want to use components of your own chosing).

6.4 to get a 32-position ZMK under LMK.

7.1 to generate random ZPK (uses 6.4 ZMK under LMK output as input here) and encrypt under ZMK and LMK. The goal is that second cryptogram that comes back, the one oddly named “ZPK encrypted for bank” in the Thales document. That’s the ZPK under the LMK that you need for your tests.

Obtaining this information should allow you to validate the critical part of your encryption infrastructure prior to getting connectivity to your Debit/EBT gateway partner. Of course, once formal inter-system testing is established you still need to transport the encrypted PIN block in an 0200 request to your endpoint. But doing the exercise I describe above here first will allow you to eliminate any self-doubt you may have about your internal PIN translation activities prior to getting an external party involved in the testing