Skip to content

Instantly share code, notes, and snippets.

@dev-zzo
Last active November 1, 2016 11:18
Show Gist options
  • Save dev-zzo/87e0947f3ca0bb6d6baf78dd4d0ecb9c to your computer and use it in GitHub Desktop.
Save dev-zzo/87e0947f3ca0bb6d6baf78dd4d0ecb9c to your computer and use it in GitHub Desktop.
# http://adamsblog.aperturelabs.com/2013/02/atmel-sam7xc-crypto-co-processor-key.html
# https://ridrix.wordpress.com/2009/09/19/mifare-desfire-communication-example/#comment-27
from binascii import hexlify, unhexlify
from Crypto.Cipher import DES3
def xor(a, b):
x = ''
for i in xrange(8):
x += chr(ord(a[i]) ^ ord(b[i]))
return x
def do_desfire(key, ERndB, DRndA, DRndB, ERndA):
key = unhexlify(key)
cipher = DES3.new(key, DES3.MODE_ECB)
# PICC sends E(RndB)
ERndB = unhexlify(ERndB)
RndB = cipher.decrypt(ERndB)
print hexlify(RndB)
# PCD sends D(RndA|RndB')
DRndA = unhexlify(DRndA)
DRndB = unhexlify(DRndB)
print hexlify(cipher.encrypt(DRndA)), hexlify(xor(cipher.encrypt(DRndA), ERndB))
print hexlify(cipher.encrypt(DRndB)), hexlify(xor(cipher.encrypt(DRndB), DRndA))
# PICC sends E(RndA')
ERndA = unhexlify(ERndA)
RndA = cipher.decrypt(ERndA)
print hexlify(RndA), hexlify(xor(RndB, DRndB))
print "Adam's data:"
do_desfire("7d1248e4342fee541029e23fefda12b8", "8f21607314cf6f7a", "d51b8bfc70b8facf", "ce53718a1229528a", "09bbfe641aae71b6")
# Output:
# e6693f0715cc4e0b
# 74aecdea7908d13b fb8fad996dc7be41
# 370ad8dd5daf5138 e21153212d17abf7
# 3b7a053e07e008b3 f959a9574f8603b2
print "Ridrix's data:"
do_desfire("00000000000000000000000000000000", "a2becd03d846cb33", "b0ccbced8fc838c9", "08dce24d86caec3c", "7673d949713ff2d1")
# Output:
# 18dd24f92edb01ed
# 8ad2c042b780c746 286c0d416fc60c75
# 6de845c354c9d5d1 dd24f92edb01ed18
# d2c042b780c7468a 1001c6b4a811edd1
print "Doegox's data:"
do_desfire("00112233445566770011223344556677", "079163698cc81654", "fdd62db6b21f2d99", "268577f5d11b1e13", "487dae253a1455ca")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment