Skip to content

Instantly share code, notes, and snippets.

@peplin
Created October 9, 2015 18:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peplin/919069d9e34f8b87e3e5 to your computer and use it in GitHub Desktop.
Save peplin/919069d9e34f8b87e3e5 to your computer and use it in GitHub Desktop.
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