Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generate a combined 3DES key for DUKPT from two components
from __future__ import print_function
from Crypto.Cipher import DES3
import os
import binascii
def xor_bytes(this, that):
return bytearray([ord(x) ^ ord(y) for x, y in zip(this, that)])
def generate_combined_key():
component_1 = binascii.unhexlify(os.environ['KEY_COMPONENT_1'])
component_1_check = binascii.unhexlify(os.environ['KEY_CHECK_1'])
component_2 = binascii.unhexlify(os.environ['KEY_COMPONENT_2'])
component_2_check = binascii.unhexlify(os.environ['KEY_CHECK_2'])
cipher = DES3.new(component_1)
check_value = cipher.encrypt(str(bytearray([0] * 8)))[:3]
if component_1_check != check_value:
raise ValueError("Component 1 check doesn't match")
print("Component 1 check: %s" % binascii.hexlify(check_value))
cipher = DES3.new(component_2)
check_value = cipher.encrypt(str(bytearray([0] * 8)))[:3]
if component_2_check != check_value:
raise ValueError("Component 2 check doesn't match")
print("Component 2 check: %s" % binascii.hexlify(check_value))
key = xor_bytes(component_1, component_2)
cipher = DES3.new(str(key))
check_value = cipher.encrypt(str(bytearray([0] * 8)))[:3]
print("Combined check: %s" % binascii.hexlify(check_value))
print("Combined key: %s" % binascii.hexlify(key))
if __name__ == '__main__':
generate_combined_key()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.