Search code examples
pythonnfcsmartcardapdu

How to use the send_apdu() command in nfcpy library?


I am trying to use the send_apdu() command given in the nfcpy library to interact with an android smartphone. What are the specific header files and procedure to use it. Please provide with in example if possible of the function in use. Here is the link to the function description: http://nfcpy.readthedocs.io/en/latest/modules/tag.html


Solution

  • There are no specific header files to use. Most of the arguments to send_apdu are direct matches of the ISO/IEC 7816-4 APDU syntax: Command Class (cla), Instruction Code (ins), Parameter 1 (p1), Parameter 2 (p2), Command Data (data), and Max Response Length (mrl). Only the check_status argument does not have an equivalent.

    To construct an APDU the caller must provide appropriate values. Below is an example that activates a specific application (the NDEF Application) using the AID "D2760000850101"h. The example assumes that a supported NFC Reader is connected through USB and an NFC Forum Type 4 Tag is placed on the reader.

    $ python
    >>> import nfc
    >>> clf = nfc.ContactlessFrontent("usb")
    >>> tag = clf.connect(rdwr={'on-connect': lambda tag: False})
    >>>
    >>> cla = 0x00  # last or only command, no secure messaging, channel zero
    >>> ins = 0xA4  # SELECT command
    >>> p1 = 0x04   # Select by DF name
    >>> p2 = 0x00   # First or only occurrence, Return FCI template
    >>> data = bytearray.fromhex("D2760000850101")  # NDEF AID
    >>>
    >>> tag.send_apdu(cla, ins, p1, p2, data, check_status=False)
    bytearray(b'\x90\x00')
    

    For this specific T4T the response data is just the two status bytes SW1 and SW2 and, because of check_status=False may or may not indicate an error (but in fact '9000'h means Success).