def testcase_ATRCardTypeWithoutMask(self): """Test smartcard.ATRCardType without mask.""" for reader in readers(): if [] != expectedATRinReader[str(reader)]: ct = ATRCardType(expectedATRinReader[str(reader)]) connection = reader.createConnection() connection.connect() self.assertEquals(True, ct.matches(connection.getATR())) self.assertEquals(True, ct.matches(connection.getATR(), reader)) connection.disconnect()
def testcase_ATRCardTypeWithoutMask(self): """Test smartcard.ATRCardType without mask.""" for reader in readers(): if [] != expectedATRinReader[str(reader)]: ct = ATRCardType(expectedATRinReader[str(reader)]) connection = reader.createConnection() connection.connect() self.assertEqual(True, ct.matches(connection.getATR())) self.assertEqual(True, ct.matches(connection.getATR(), reader)) connection.disconnect()
def testcase_ATRCardTypeMisMatchWithoutMask(self): """Test smartcard.ATRCardType mismatch without mask.""" for reader in readers(): if [] != expectedATRinReader[str(reader)]: atr = list(expectedATRinReader[str(reader)]) # change the last byte of the expected atr atr[-1] = 0xFF ct = ATRCardType(atr) connection = reader.createConnection() connection.connect() self.assertEquals(False, ct.matches(connection.getATR())) self.assertEquals(False, ct.matches(connection.getATR(), reader)) connection.disconnect()
def initialize(card_type=""): if card_type == "": cardtype = AnyCardType() # for accepting any type of card else: cardtype = ATRCardType(card_type) cardrequest = CardRequest(timeout=1, cardType=cardtype) # print("Waiting for card") cardservice = cardrequest.waitforcard() # print("Card found") # connecting to card cardservice.connection.connect() reader = cardservice.connection.getReader() print(f"Success: NFC Connection established on reader {reader}") # set up object nfc_connection = NFCconnection( cardservice=cardservice, metadata={}, ) # get metadata nfc_connection.get_card_atr_info() nfc_connection.get_card_uid() nfc_connection.get_card_size() uid = nfc_connection.metadata["UID"] size = nfc_connection.metadata["Size"] print(f"Success: NFC Connection identified as {uid} with size {size}") return nfc_connection
def testcase_CardRequestATRCardTypeTimeout(self): """Test smartcard.AnyCardType.""" for reader in expectedReaders: atr = expectedATRinReader[reader][:-1] ct = ATRCardType(atr) cr = CardRequest(timeout=1, readers=[reader], cardType=ct) self.assertRaises(CardRequestTimeoutException, cr.waitforcard)
def testcase_ATRCardTypeWithMaskMismatch(self): """Test smartcard.ATRCardType with mask and mismatch.""" for reader in readers(): if [] != expectedATRinReader[str(reader)]: mask = [0xFF for x in expectedATRinReader[str(reader)]] # don't look to the last byte mask[0] = mask[-1] = 0x00 ct = ATRCardType(expectedATRinReader[str(reader)], mask) connection = reader.createConnection() connection.connect() atr = connection.getATR() connection.disconnect() # change a bit in the :-2 byte atr[-2] = atr[-2] ^ 0xFF self.assertEqual(False, ct.matches(atr)) self.assertEqual(False, ct.matches(atr, reader))
def testcase_ATRCardTypeWithMask(self): """Test smartcard.ATRCardType with mask.""" for reader in readers(): if [] != expectedATRinReader[str(reader)]: mask = map(lambda x: 0xFF, expectedATRinReader[str(reader)]) # don't look to the last byte mask[-1] = 0x00 ct = ATRCardType(expectedATRinReader[str(reader)], mask) connection = reader.createConnection() connection.connect() atr = connection.getATR() connection.disconnect() # change a bit in the last byte atr[-1] = atr[-1] ^ 0xFF self.assertEquals(True, ct.matches(atr)) self.assertEquals(True, ct.matches(atr, reader))
def testcase_CardRequestATRCardTypeTimeoutAnyReader(self): """Test smartcard.AnyCardType.""" readers = smartcard.System.readers() atr = expectedATRs[0][:-1] ct = ATRCardType(atr) cr = CardRequest(timeout=1.5, readers=readers, cardType=ct) self.assertRaises(CardRequestTimeoutException, cr.waitforcard)
def testcase_CardRequestATRCardType(self): """Test smartcard.AnyCardType.""" for atr in expectedATRs: if [] != atr: ct = ATRCardType(atr) cr = CardRequest(timeout=10, cardType=ct) cs = cr.waitforcard() cs.connection.connect() self.assertEqual(atr, cs.connection.getATR()) self.assertEqual(cs.connection.getReader(), expectedReaderForATR[toHexString(atr)]) cs.connection.disconnect()
def requestByATR(atr): print('\n========== REQUEST BY ATR ==========\n') # example: ATR of German ID Card, only works with ISO 14443 devices # cardtype = ATRCardType(toBytes("3B 88 80 01 00 00 00 00 00 00 00 00 09")) cardtype = ATRCardType(toBytes(atr)) # also supports masks # cardtype = ATRCardType( toBytes( "3B 15 94 20 02 01 00 00 0F" ), toBytes( "00 00 FF FF FF FF FF FF 00" ) ) cardrequest = CardRequest(timeout=1, cardType=cardtype) try: cardservice = cardrequest.waitforcard() print('Card detected successfully') return True except smartcard.Exceptions.CardRequestTimeoutException: print('Wrong card type') return False cardservice.connection.connect() print(toHexString(cardservice.connection.getATR()))
def __init__(self, atr=None, *args, **kwargs): """ :param atr: If set, the backend will trigger events only for card(s) with the specified ATR(s). It can be either an ATR string (space-separated hex octects) or a list of ATR strings. Default: none (any card will be detected) """ super().__init__(*args, **kwargs) self.ATRs = [] if atr: if isinstance(atr, str): self.ATRs = [atr] elif isinstance(atr, list): self.ATRs = atr else: raise RuntimeError( "Unsupported ATR: \"{}\" - type: {}, " + "supported types: string, list".format(atr, type(atr))) self.cardtype = ATRCardType(*[toBytes(atr) for atr in self.ATRs]) else: self.cardtype = AnyCardType()
def readUID(self, ATR, apdu): cardtype = ATRCardType(toBytes(ATR)) cardrequest = CardRequest(timeout=None, cardType=cardtype) cardservice = cardrequest.waitforcard() try: cardservice.connection.connect() response, sw1, sw2 = cardservice.connection.transmit(apdu) except CardConnectionException: return None ## print toHexString(cardservice.connection.getATR()) print "%x %x" % (sw1, sw2) print "%x, %x, %x, %x" % (response[0], response[1], response[2], response[3]) if sw1 == 0x90 and sw2 == 0x00: #check if UID was read successfully UID = str(hex(response[0])) + str(hex(response[1])) + str( hex(response[2])) + str(hex(response[3])) return UID.replace("0x", "") return None
def testcase_CardRequestNewCardATRCardTypeInfiniteTimeOut(self): """Test smartcard.CardRequest for new card with given ATR without time-out.""" self.removeAllCards() count = 0 for i in range(0, 6): card = random.choice(cardz) cardtype = ATRCardType(card.atr) cardrequest = CardRequest( timeout=None, cardType=cardtype, newcardonly=True) print('re-insert card', toHexString(card.atr), 'into', card.reader) cardservice = cardrequest.waitforcard() print('ok') try: cardservice.connection.connect() self.assertEqual(cardservice.connection.getATR(), card.atr) except CardConnectionException: # card was removed too fast pass cardservice.connection.disconnect() count += 1 self.assertEqual(6, count)
def connect(self): cardtype=ATRCardType(toBytes("3B F8 18 00 FF 81 31 FE 45 4A 43 4F 50 76 32 34 31 43")) cardrequest=CardRequest(timeout=1, cardType=cardtype) self.cardservice=cardrequest.waitforcard() self.cardservice.connection.connect()
def createCardReq(cardAtrType): cardtype = ATRCardType(cardAtrType) cardrequest = CardRequest(timeout=None, cardType=cardtype) return cardrequest
########### COMANDOS PRECARGADOS #################### # | CLA | INS | P1 | P2 | LC | DATA ... selectIAS = [ 0x00, 0xA4, 0x04, 0x00, 0x0C, 0xA0, 0x00, 0x00, 0x00, 0x18, 0x40, 0x00, 0x00, 0x01, 0x63, 0x42, 0x00 ] verifyPIN = [0x00, 0x20, 0x00, 0x11, 0x0C] MSE_SET_DST = [0x00, 0x22, 0x41, 0xB6, 0x06] PSO_HASH = [0x00, 0x2A, 0x90, 0xA0, 0x20] PSO_CDS = [0x00, 0x2A, 0x9E, 0x9A, 0x00, 0xFF, 0x00] selectFile = [0x00, 0xA4, 0x00, 0x00, 0x02] getResponse = [0XA0, 0XC0, 0x00, 0x00] readBinary = [0x00, 0xB0, 0x00, 0x00] #################################################### cardtype = ATRCardType( toBytes("3B 7F 94 00 00 80 31 80 65 B0 85 03 00 EF 12 0F FF 82 90 00") ) # Solo eCI de UY #################################################### def enviarAPDU(cmd): print(cmd) data, sw1, sw2 = cardservice.connection.transmit(cmd) print(hex(sw1), hex(sw2)) return [data, sw1, sw2] def encrypt_string(hash_string): sha_signature = hashlib.sha256(hash_string.encode()).hexdigest() return sha_signature
"""The single instance of __CardNames__""" instance = None def __init__(self): """Constructor: create a single instance of __readergroups on first call""" if None == CardNames.instance: CardNames.instance = __CardNames__() def __getattr__(self, name): """All operators redirected to inner class.""" return getattr(self.instance, name) if __name__ == '__main__': from smartcard.CardType import ATRCardType # define a card by its ATR ct = ATRCardType([0x3B, 0x16, 0x94, 0x20, 0x02, 0x01, 0x00, 0x00, 0x0D]) # create CardName cn = CardNames() cn.add("Palmera Protect V2", ct) cn.dump() print cn.find([0x3B, 0x16, 0x94, 0x20, 0x02, 0x01, 0x00, 0x00, 0x0D]) print cn.find([0x3B, 0x16, 0x94, 0x20, 0x02, 0x01, 0x00, 0x00]) cn.delete("Palmera Protect V2") print '---------' cn.dump()
def fn(): r = readers() print(r) ['SchlumbergerSema Reflex USB v.2 0', 'Utimaco CardManUSB 0'] connection = r[0].createConnection() connection.connect() SELECT = [0x00, 0xA4, 0x00, 0x00, 0x00] SELECT2 = [0x00, 0xA4, 0x04, 0x04, 0x06] DF_TELECOM = [0x4d, 0x50, 0x43, 0x4f, 0x53, 0x31] data, sw1, sw2 = connection.transmit(SELECT2 + DF_TELECOM) print("%x %x" % (sw1, sw2)) print(len(data)) cardtype = ATRCardType(toBytes("3B 6A 00 00 80 65 A2 01 01 01 3D 72 D6 41")) cardrequest = CardRequest(timeout=1, cardType=cardtype) cardservice = cardrequest.waitforcard() cardservice.connection.connect() print(toHexString(cardservice.connection.getATR())) #00 A4 04 00 07 A0 00 00 00 04 10 10 00 Basic_Select = [0x00, 0xA4, 0x04, 0x00] Basic_Select2 = [0x00, 0xA4, 0x00, 0x00, 0x02, 0x00, 0x01] Sel_Len_Data_RespLen = [0x07, 0xD6, 0x16, 0x00, 0x00, 0x30, 0x01, 0x01] #Select1 = [0x00, 0xA4, 0x04, 0x00, 0x07, 0xA0, 0x00,0x00,0x00,0x04,0x10,0x10,0x00] SELECT2 = [0x00, 0xA4, 0x04, 0x04, 0x06] DF_TELECOM = [0x4d, 0x50, 0x43, 0x4f, 0x53, 0x31]
def wait(self): ATR = list(bytes.fromhex("3BDA18FF81B1FE751F030031C573C001400090000C")) cardtype = ATRCardType(ATR) cardrequest = CardRequest(timeout=self.timeout, cardType=cardtype) cardservice = cardrequest.waitforcard() self.connection = cardservice.connection
def main_menu(): global share_mode global disposition global devices_list_manager global card_manager menu_util.printShortMainMenu() choice_main = input("> ") if choice_main.lower() == 's': devices_list_manager.printCards() elif choice_main.lower() == 'r': devices_list_manager.printReaders() elif choice_main.lower() == 'm': printChooseShareMode() index = input("> ") try: if int(index) in SHARE_MODES.keys(): share_mode = int(index) else: raise Exception("Unknown share mode (wrong index)") except Exception as e: menu_util.printError(e) share_mode = SCARD_SHARE_SHARED elif choice_main.lower() == 'd': menu_util.printChooseDisposition() index = input("> ") try: if int(index) in DISPOSITIONS.keys(): disposition = int(index) else: raise Exception("Unknown disposition (wrong index)") except Exception as e: menu_util.printError(e) disposition = SCARD_LEAVE_CARD elif choice_main.lower() == 'c': leave_card_menu = False if devices_list_manager.noCardAvailable( ) or devices_list_manager.noReaderAvailable(): menu_util.printNoCardAvailable() leave_card_menu = True else: menu_util.printChooseCardToConnect(share_mode, disposition) devices_list_manager.printCards() index = input("> ") try: bytes_atr = toBytes( devices_list_manager.getAtrFromCardIndex(int(index))) card_manager.connect(card_type=ATRCardType(bytes_atr), share_mode=share_mode) except Exception as e: menu_util.printError(e) leave_card_menu = True if not leave_card_menu: menu_util.printCardMenu() while not leave_card_menu: leave_card_menu = not card_menu() elif choice_main.lower() == 'h': menu_util.printMainMenu() elif choice_main.lower() == 'q': return False else: menu_util.printWrongValue() return True