def tuliskartu(nis): otentikasi = [0xFF, 0x88, 0x00, Mifare1k[0], 0x60, 0x00] r = readers() print "Available readers:", r reader = r[0] # print "Using:", reader connection = reader.createConnection() connection.connect() data, sw1, sw2 = connection.transmit(otentikasi) print data print "Select Applet: %02X %02X" % (sw1, sw2) # write cmd = [0xFF, 0xD6, 0x00, Mifare1k[0], 0x10] # nis = "123456789" + "1234567" for s in range(16): cmd.append(toASCIIBytes(nis[s])[0]) data, sw1, sw2 = connection.transmit(cmd) print toASCIIString(data) print "Select Applet: %02X %02X" % (sw1, sw2)
def _parse_item(self, item): item_type = item[1] item_value = item[2] if item_type == 0x55: # URL Type if not item_value[0] > 0x23: url = self._uri_lookup[item_value[0]] + toASCIIString(item_value[1:]) else: url = toASCIIString(item_value) self.items.append(["url", url])
def do_run(self, args, timeout=15): """ Command handler for running a command once. :param args: args passed into the command. expects a string of commands in hex separated by a `;` :param timeout: how long to wait for the chip before executing the commands """ _logger.debug('Entering NfcShell.do_run function.') # Connect to the reader connection = SmartCard.connect_to_chip(timeout=timeout) # Loop over each command commands = [util.toBytes(command) for command in args.split(";")] for command_bytes in commands: # Send command print(f'TX: "{util.toHexString(command_bytes)}"...') data, ok = ACR122.transmit_raw_command(command_bytes, connection) # Print output if ok: print(f'RX: (HEX)') print(util.toHexString(data)) print(f'RX: (ASCII)') print(util.toASCIIString(data)) else: print(f'"{util.toHexString(command_bytes)}" failed.') break
def dataToAscii(data): s = [] for c in data: if(c != 0): s.append(c) return toASCIIString(s)
def update(self, observable, actions): (addedcards, removedcards) = actions for card in addedcards: # print("+Inserted: ", toHexString(card.atr)) card.connection = card.createConnection() card.connection.connect() card.connection.addObserver(self.observer) cmdott = [0xFF, 0x88, 0x00, Mifare1k[0], 0x60, 0x00] cmdbaca = [0xFF, 0xB0, 0x00, Mifare1k[0], 0x10] response, sw1, sw2 = card.connection.transmit(cmdott) # print("Select Ott: %02X %02X" % (sw1, sw2)) if hex(sw1) == hex(144): # apdu = GET_RESPONSE + [sw2] data, sw1, sw2 = card.connection.transmit(cmdbaca) # print("Select Baca: %02X %02X" % (sw1, sw2)) if hex(sw1) == hex(144): self.getbaca = toASCIIString(data) self.getTap = "TP" # print(self.getbaca) # print (toASCIIString(data)) for card in removedcards: self.getTap = "" print("-Removed: ", toHexString(card.atr))
def Baca(blok): try: r = readers() print "Available readers:", r reader = r[0] connection = reader.createConnection() connection.connect() cmdott = [0xFF, 0x88, 0x00, blok, 0x60, 0x00] cmd = [0xFF, 0xB0, 0x00, blok, 0x10] dataott, sw1, sw2 = connection.transmit(cmdott) # print "Select Applet: %02X %02X" % (sw1, sw2) if hex(sw1) == hex(144): print "Ott Sukses" else: print "Ott Gagal" data, sw1, sw2 = connection.transmit(cmd) if hex(sw1) == hex(144): print "Baca Sukses" else: print "Baca Gagal" except smartcard.Exceptions.CardConnectionException as inst: print "Kartu Tidak di Temukan, Mohon Untuk Men Tap Kartu Pada Reader! " except: print "Ada Error/NFC Reader Belum Terhubung!" return toASCIIString(data)
def firmware_version(self): """Retreives the firmware version of the ACR122/Tikitag Reader""" resp, s1, s2 = self._connection.transmit(self._tiki_rfid_apdu_fwver) if not s1 == 99: return toASCIIString(resp) else: return None
def __get_fields(self, data): """Get fields in human readable format""" fields = self.__split_fields(data) for name, value in fields.items(): fields[name] = scard_util.toASCIIString(value) return fields
def convert_alpha_to_string(bytes=[]): """Convert the bytes array of Alpha Identifier to string (Ex: ADN, EF_SPN) >>> vals = [0x4D, 0x41, 0x49, 0x20, 0x54, 0x45, 0x53, 0x54, 0xFF, 0xFF] >>> convert_alpha_to_string(vals) 'MAI TEST' Todo: Should consider the SMS default 7-bit & UCS2 coding """ ret_content = "" try: ret_content = toASCIIString(bytes[:bytes.index(0xFF)]) except ValueError: ret_content = toASCIIString(bytes) return ret_content
def hello(): r = readers() # print "Available readers:", r reader = r[0] # print "Using:", reader connection = reader.createConnection() connection.connect() data, sw1, sw2 = connection.transmit(otentikasi) print data print "Select Applet: %02X %02X" % (sw1, sw2) data, sw1, sw2 = connection.transmit(bacadata) print toASCIIString(data) print "Select Applet: %02X %02X" % (sw1, sw2) return toASCIIString(data)
def encrypt_user_data(user_data): #TODO # binstring = HexListToBinString( user_data ) user_data=padd(toASCIIBytes(user_data),16) cipher = AES.new(key_as_binstring,AES.MODE_ECB ) encrypted_as_string = cipher.encrypt(toASCIIString(user_data)).encode('hex') decrypted_as_string = cipher.decrypt( encrypted_as_string ) print("ans",encrypted_as_string,decrypted_as_string) return toBytes(encrypted_as_string)
def bacakartu(): otentikasi = [0xFF, 0x88, 0x00, Mifare1k[0], 0x60, 0x00] bacadata = [0xFF, 0xB0, 0x00, Mifare1k[0], 0x10] r = readers() print "Available readers:", r reader = r[0] # print "Using:", reader connection = reader.createConnection() connection.connect() data, sw1, sw2 = connection.transmit(otentikasi) print data print "Select Applet: %02X %02X" % (sw1, sw2) data, sw1, sw2 = connection.transmit(bacadata) print toASCIIString(data) print "Select Applet: %02X %02X" % (sw1, sw2)
def sam_os(self): resp = self.send_to_sam(6, 0, 8) os = resp[:4] rest = resp[4:] return toASCIIString(os), rest
## Form the command to be sent to the card: DECRYPT_KEY = [0x88, 0x10, 0, 0, len(DATA)] + DATA + [0x10] GET_RESPONSE = [0x88, 0xc0, 0x00, 0x00, 0x10] ## First, we send the DECRYPT_KEY command. ## This triggers the decryption in the card. The blue ## light will flash, and the toggle output will show ## a spike. apdu = DECRYPT_KEY print 'sending ' + toHexString(apdu) response, sw1, sw2 = cardservice.connection.transmit( apdu ) print 'response: ', response, ' status words: ', "%x %x" % (sw1, sw2) ## There will be no response here, but the card answers with sw1=0x61, sw2=0x10, ## indicating that there are 16 (=0x10) bytes to read now. ## Now we fetch the decrypted chunk key using the GET_RESPONSE command: apdu = GET_RESPONSE print 'sending ' + toHexString(apdu) response, sw1, sw2 = cardservice.connection.transmit( apdu ) print 'response: ', response, ' status words: ', "%x %x" % (sw1, sw2) ## If we want to check if an assumed key is correct, we calculate the ## result for this assumed key and print it: ASSUMED_KEY = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] aes_device = Crypto.Cipher.AES.new( toASCIIString( ASSUMED_KEY ) , Crypto.Cipher.AES.MODE_ECB ) response = aes_device.decrypt( toASCIIString( DATA ) ) print 'assumed: ', bs2hl( response ) ## That's it.
def firmware_version(self): apdu = APDU(0xff, 0, 0x48) resp, sw1, sw2 = self.send(apdu) return toASCIIString(resp + [sw1, sw2])
def get_photo(self, filename=None): """Return or save photo from electronic ID""" header, data = self._card.read_file(CardFile.PHOTO) data = scard_util.toASCIIString(data[4:]) return data
def _read_value(self): length = self._read_bytes(0, 1) return_bytes = self._read_bytes(1, length[0]) self.card_value = toASCIIString(return_bytes)
bacadata = [0xFF, 0xB0, 0x00, Mifare1k[0], 0x10] # write cmd = [0xFF, 0xD6, 0x00, Mifare1k[0], 0x10] op = [] nis = "123456789" + "1234567" for s in range(16): cmd.append(toASCIIBytes(nis[s])[0]) r = readers() print "Available readers:", r reader = r[0] # print "Using:", reader connection = reader.createConnection() connection.connect() data, sw1, sw2 = connection.transmit(otentikasi) print data print "Select Applet: %02X %02X" % (sw1, sw2) # data, sw1, sw2 = connection.transmit(cmd) # print toASCIIString(data) # print "Select Applet: %02X %02X" % (sw1, sw2) data, sw1, sw2 = connection.transmit(bacadata) print toASCIIString(data) print "Select Applet: %02X %02X" % (sw1, sw2)
#!/usr/bin/python -u # -*- coding: utf-8 -*- import Crypto.Cipher.AES import sys from smartcard.util import toHexString, toBytes, toASCIIString, bs2hl, hl2bs import random ## This key is stored in the SmartCard: masterKey=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] masterCrypt=Crypto.Cipher.AES.new( toASCIIString( masterKey ), Crypto.Cipher.AES.MODE_ECB ) ## Amount of stream data to be encoded with the same key: blocksize=1024*128 preamble="SEC-"*16 def generateNewKey(): ## This is only a dummy function to ## generate random keys in the future. ## For now, this routine returns a constant ## 16 bytes key: retval = "" for i in range(16): retval += chr( random.randint(0,255) ) return retval #fi i=0 while 1: ## Generate a new stream key, and encrypt it. theKey=generateNewKey() theEncryptedKey=masterCrypt.encrypt( theKey )
from smartcard.CardConnection import CardConnection from smartcard.CardConnectionObserver import ConsoleCardConnectionObserver from smartcard.Exceptions import CardRequestTimeoutException from smartcard.util import toHexString from smartcard.util import toASCIIString COMMAND_HELLO_POS = [0xa0, 0x37, 0x00, 0x00, 0x01, 0x99, 0x00] SELECT_F00012345210 = [0x00, 0xa4, 0x04, 0x00, 0x06, 0xF0, 0x00, 0x12, 0x34, 0x52, 0x10, 0x00] cardtype = AnyCardType() try: print 'insert a card within 10s' cardrequest = CardRequest(timeout=10, cardType=cardtype) cardservice = cardrequest.waitforcard() observer = ConsoleCardConnectionObserver() cardservice.connection.addObserver(observer) cardservice.connection.connect() #response, sw1, sw2 = cardservice.connection.transmit(COMMAND_HELLO_POS) response, sw1, sw2 = cardservice.connection.transmit(SELECT_F00012345210) if sw1 == 0x90 and sw2 == 0x00: print toASCIIString(response) else: print 'bad response' except CardRequestTimeoutException: print 'time-out: no card inserted during last 10s' except: import sys print sys.exc_info()[1]
if hresult != SCARD_S_SUCCESS: raise EstablishContextException(hresult) hresult, readers = SCardListReaders(hcontext, []) if hresult != SCARD_S_SUCCESS: raise ListReadersException(hresult) print('PC/SC Readers:', readers) for reader in readers: hresult, hcard, dwActiveProtocol = SCardConnect(hcontext, reader, SCARD_SHARE_DIRECT, SCARD_PROTOCOL_ANY) if hresult != SCARD_S_SUCCESS: raise BaseSCardException(hresult) print("reader:", reader) for attribute in (SCARD_ATTR_VENDOR_IFD_SERIAL_NO, SCARD_ATTR_ATR_STRING): hresult, attrib = SCardGetAttrib(hcard, attribute) print(hex(attribute), end=' ') if hresult != SCARD_S_SUCCESS: print(SCardGetErrorMessage(hresult)) else: print(attrib, toHexString(attrib), toASCIIString(attrib)) hresult = SCardDisconnect(hcard, SCARD_LEAVE_CARD) if hresult != SCARD_S_SUCCESS: raise BaseSCardException(hresult) hresult = SCardReleaseContext(hcontext) if hresult != SCARD_S_SUCCESS: raise ReleaseContextException(hresult)
def get_photo(self): """Return or save photo from electronic ID""" data = self._card.read_file(CardFile.PHOTO)[1] data = scard_util.toASCIIString(data[4:]) return data
raise EstablishContextException(hresult) hresult, readers = SCardListReaders(hcontext, []) if hresult != SCARD_S_SUCCESS: raise ListReadersException(hresult) print('PC/SC Readers:', readers) for reader in readers: hresult, hcard, dwActiveProtocol = SCardConnect(hcontext, reader, SCARD_SHARE_DIRECT, SCARD_PROTOCOL_ANY) if hresult != SCARD_S_SUCCESS: raise BaseSCardException(hresult) print("reader:", reader) for attribute in (SCARD_ATTR_VENDOR_IFD_SERIAL_NO, SCARD_ATTR_ATR_STRING): hresult, attrib = SCardGetAttrib(hcard, attribute) print(hex(attribute), end=' ') if hresult != SCARD_S_SUCCESS: print(SCardGetErrorMessage(hresult)) else: print(attrib, toHexString(attrib), toASCIIString(attrib)) hresult = SCardDisconnect(hcard, SCARD_LEAVE_CARD) if hresult != SCARD_S_SUCCESS: raise BaseSCardException(hresult) hresult = SCardReleaseContext(hcontext) if hresult != SCARD_S_SUCCESS: raise ReleaseContextException(hresult)
def execute(self, arg_connection, arg_parameter=""): self.__logging.debug("execute()") ret_content = "" raw_format = False dict_args = convert_arguments_to_dict(arg_parameter) for key, value in dict_args.items(): if key == "format" and value.lower() == "raw": raw_format = True # select EF_DIR response, sw1, sw2 = select_file_in_mf(arg_connection, USIM_FILE_ID.DIR.value) if sw1 == 0x90: record_count = get_record_count(response) data_length = get_data_length(response) for i in range(record_count): response, sw1, sw2 = arg_connection.read_record( i + 1, data_length) if sw1 == 0x90: if ret_content != "": ret_content += "\n" if raw_format: ret_content += "EF_DIR #%d - %s" % ( i + 1, toHexString(response)) else: aid_identifier = None aid_lable = None aid_identifier_content = search_fcp_content( response, TLV_TAG.APPLICATION_IDENTIFIER.value) if aid_identifier_content != None and len( aid_identifier_content) > 2: aid_identifier = toHexString( aid_identifier_content[2:], format=PACK) aid_label_content = search_fcp_content( response, TLV_TAG.APPLICATION_LABEL.value) if aid_label_content != None and len( aid_label_content) > 2: aid_lable = toASCIIString(aid_label_content[2:]) if aid_identifier == None: ret_content += "EF_DIR #%02d - [Empty Content]" % ( i + 1) elif aid_lable == None: ret_content += "EF_DIR #%02d - AID: %s" % ( i + 1, aid_identifier) else: ret_content += "EF_DIR #%02d - AID: %s, Label: %s" % ( i + 1, aid_identifier, aid_lable) if ret_content == "": ret_content = "Can't read the content from EF_DIR!" return ret_content
raise error( 'Unable to connect: ' + SCardGetErrorMessage(hresult)) print('Connected with active protocol', dwActiveProtocol) try: if 'winscard' == resourceManager: # IOCTL_SMARTCARD_GET_ATTRIBUTE = SCARD_CTL_CODE(2) hresult, response = SCardControl( hcard, SCARD_CTL_CODE(2), toBytes("%.8lx" % SCARD_ATTR_VENDOR_NAME)) if hresult != SCARD_S_SUCCESS: raise error( 'SCardControl failed: ' + SCardGetErrorMessage(hresult)) print('SCARD_ATTR_VENDOR_NAME:', toASCIIString(response)) elif 'pcsclite' == resourceManager: # get feature request hresult, response = SCardControl( hcard, SCARD_CTL_CODE(3400), []) if hresult != SCARD_S_SUCCESS: raise error( 'SCardControl failed: ' + SCardGetErrorMessage(hresult)) print('CM_IOCTL_GET_FEATURE_REQUEST:', toHexString(response)) finally: hresult = SCardDisconnect(hcard, SCARD_UNPOWER_CARD) if hresult != SCARD_S_SUCCESS: raise error(