nfc.tag

class nfc.tag.Tag(clf, target)

Bases: object

The base class for all NFC Tags/Cards. The methods and attributes defined here are commonly available but some may, depending on the tag product, also return a None value is support is not available.

Direct subclasses are the NFC Forum tag types: Type1Tag, Type2Tag, Type3Tag, Type4Tag. Some of them are further specialized in vendor/product specific classes.

class NDEF(tag)

Bases: object

The NDEF object type that may be read from Tag.ndef.

This class presents the NDEF management information and the actual NDEF message by a couple of attributes. It is normally accessed from a Tag instance (further named tag) through the Tag.ndef attribute for reading or writing NDEF records.

if tag.ndef is not None:
    for record in tag.ndef.records:
        print(record)
    if tag.ndef.is_writeable:
        from ndef import TextRecord
        tag.ndef.records = [TextRecord("Hello World")]
tag

A readonly reference to the underlying tag object.

length

Length of the current NDEF message in bytes.

capacity

Maximum number of bytes for an NDEF message.

is_readable

True if the NDEF data are is readable.

is_writeable

True if the NDEF data area is writeable.

has_changed

The boolean attribute has_changed allows to determine whether the NDEF message on the tag is different from the message that was read or written at an earlier time in the session. This may for example be the case if the tag is build to dynamically present different content depending on some state.

Note that reading this attribute involves a complete update of the Tag.NDEF instance and it is possible that Tag.ndef is None after the update (e.g. tag gone during read or a dynamic tag that failed). A robust implementation should always verify the value of the Tag.ndef attribute.

if tag.ndef.has_changed and tag.ndef is not None:
    for record in tag.ndef.records:
        print(record)

The has_changed attribute can also be used to verify that NDEF records written to the tag are identical to the NDEF records stored on the tag.

from ndef import TextRecord
tag.ndef.records = [TextRecord("Hello World")]
if tag.ndef.has_changed:
    print("the tag data differs from what was written")
message

Read or write an nfc.ndef.Message.

Deprecated since version 0.12: Use records.

records

Read or write a list of NDEF Records.

New in version 0.12.

This attribute is a convinience wrapper for decoding and encoding of the NDEF message data octets. It uses the ndeflib module to return the list of ndef.Record instances decoded from the NDEF message data or set the message data from a list of records.

if tag.ndef is not None:
    for record in tag.ndef.records:
        print(record)
    import ndef
    tag.ndef.records = [ndef.TextRecord('Hello World')]

Decoding and encoding are performed with a relaxed error handling strategy that ignores minor errors in the NDEF data. The ndeflib does also support ‘strict’ and ‘ignore’ error handling which may be used like so:

from ndef import message_decoder, message_encoder
records = message_decoder(tag.ndef.octets, errors='strict')
octets = b''.join(message_encoder(records, errors='strict'))
tag.ndef.octets = octets
octets

Read or write NDEF message data octets.

New in version 0.12.

The octets attribute returns the NDEF message data octets as bytes. A bytes or bytearray sequence assigned to octets is immediately written to the NDEF message data area, unless the Tag memory is write protected or to small.

if tag.ndef is not None:
    print(hexlify(tag.ndef.octets))
Tag.identifier

The unique tag identifier.

Tag.ndef

An NDEF object if found, otherwise None.

Tag.is_present

True if the tag is within communication range.

Tag.is_authenticated

True if the tag was successfully authenticated.

Tag.dump()

The dump() method returns a list of strings describing the memory structure of the tag, suitable for printing with join(). The list format makes custom indentation a bit easier.

print("\n".join(["\t" + line for line in tag.dump]))
Tag.format(version=None, wipe=None)

Format the tag to make it NDEF compatible or erase content.

The format() method is highly dependent on the tag type, product and present status, for example a tag that has been made read-only with lock bits can no longer be formatted or erased.

format() creates the management information defined by the NFC Forum to describes the NDEF data area on the tag, this is also called NDEF mapping. The mapping may differ between versions of the tag specifications, the mapping to apply can be specified with the version argument as an 8-bit integer composed of a major version number in the most significant 4 bit and the minor version number in the least significant 4 bit. If version is not specified then the highest possible mapping version is used.

If formatting of the tag is possible, the default behavior of format() is to update only the management information required to make the tag appear as NDEF compatible and empty, previously existing data could still be read. If existing data shall be overwritten, the wipe argument can be set to an 8-bit integer that will be written to all available bytes.

The format() method returns True if formatting was successful, False if it failed for some reason, or None if the present tag can not be formatted either because the tag does not support formatting or it is not implemented in nfcpy.

Tag.protect(password=None, read_protect=False, protect_from=0)

Protect a tag against future write or read access.

protect() attempts to make a tag readonly for all readers if password is None, writeable only after authentication if a password is provided, and readable only after authentication if a password is provided and the read_protect flag is set. The password must be a byte or character sequence that provides sufficient key material for the tag specific protect function (this is documented separately for the individual tag types). As a special case, if password is set to an empty string the protect() method uses a default manufacturer value if such is known.

The protect_from argument sets the first memory unit to be protected. Memory units are tag type specific, for a Type 1 or Type 2 Tag a memory unit is 4 byte, for a Type 3 Tag it is 16 byte, and for a Type 4 Tag it is the complete NDEF data area.

Note that the effect of protecting a tag without password can normally not be reversed.

The return value of protect() is either True or False depending on whether the operation was successful or not, or None if the tag does not support custom protection (or it is not implemented).

Tag.authenticate(password)

Authenticate a tag with a password.

A tag that was once protected with a password requires authentication before write, potentially also read, operations may be performed. The password must be the same as the password provided to protect(). The return value indicates authentication success with True or False. For a tag that does not support authentication the return value is None.

exception nfc.tag.TagCommandError(errno)

Bases: exceptions.Exception

The base class for exceptions that are raised when a tag command has not returned the expected result or a a lower stack error was raised.

The errno attribute holds a reason code for why the command has failed. Error numbers greater than zero indicate a tag type specific error from one of the exception classes derived from TagCommandError (per tag type module). Error numbers below and including zero indicate general errors:

nfc.tag.TIMEOUT_ERROR  => unrecoverable timeout error
nfc.tag.RECEIVE_ERROR  => unrecoverable transmission error
nfc.tag.PROTOCOL_ERROR => unrecoverable protocol error

The TagCommandError exception populates the message attribute of the general exception class with the appropriate error description.

errno

Holds the error reason code.

class nfc.tag.TagEmulation

Bases: object

Base class for tag emulation classes.

Type 1 Tag

exception nfc.tag.tt1.Type1TagCommandError(errno)

Bases: nfc.tag.TagCommandError

Type 1 Tag specific exceptions. Sets errno to one of:

1 - CHECKSUM_ERROR
2 - RESPONSE_ERROR
3 - WRITE_ERROR
class nfc.tag.tt1.Type1Tag(clf, target)

Bases: nfc.tag.Tag

Implementation of the NFC Forum Type 1 Tag Operation specification.

The NFC Forum Type 1 Tag is based on the ISO 14443 Type A technology for frame structure and anticollision (detection) commands, and the Innovision (now Broadcom) Jewel/Topaz commands for accessing the tag memory.

dump()

Returns the tag memory blocks as a list of formatted strings.

dump() iterates over all tag memory blocks (8 bytes each) from block zero until the physical end of memory and produces a list of strings that is intended for line by line printing. Multiple consecutive memory block of identical content may be reduced to fewer lines of output, so the number of lines returned does not necessarily correspond to the number of memory blocks present.

Warning

For tags with more than 120 byte memory, the dump() method first overwrites the data block to verify that it is backed by physical memory, then restores the original data. This is necessary because Type 1 Tags do not indicate an error when reading beyond the physical memory space. Be cautious to not remove a tag from the reader when using dump() as otherwise your data may be corrupted.

protect(password=None, read_protect=False, protect_from=0)

The implementation of nfc.tag.Tag.protect() for a generic type 1 tag is limited to setting the NDEF data read-only for tags that are already NDEF formatted.

read_id()

Returns the 2 byte Header ROM and 4 byte UID.

read_all()

Returns the 2 byte Header ROM and all 120 byte static memory.

read_byte(addr)

Read a single byte from static memory area (blocks 0-14).

read_block(block)

Read an 8-byte data block at address (block * 8).

read_segment(segment)

Read one memory segment (128 byte).

write_byte(addr, data, erase=True)

Write a single byte to static memory area (blocks 0-14). The target byte is zero’d first if erase is True.

write_block(block, data, erase=True)

Write an 8-byte data block at address (block * 8). The target bytes are zero’d first if erase is True.

class nfc.tag.tt1_broadcom.Topaz(clf, target)

Bases: nfc.tag.tt1.Type1Tag

The Broadcom Topaz is a small memory tag that can hold up to 94 byte ndef message data.

format(version=None, wipe=None)

Format a Topaz tag for NDEF use.

The implementation of nfc.tag.Tag.format() for a Topaz tag creates a capability container and an NDEF TLV with length zero. Data bytes of the NDEF data area are left untouched unless the wipe argument is set.

protect(password=None, read_protect=False, protect_from=0)

In addtion to nfc.tag.tt1.Type1Tag.protect() this method tries to set the lock bits to irreversibly protect the tag memory. However, it appears that tags sold have the lock bytes write protected, so this additional effort most likely doesn’t have any effect.

class nfc.tag.tt1_broadcom.Topaz512(clf, target)

Bases: nfc.tag.tt1.Type1Tag

The Broadcom Topaz-512 is a memory enhanced version that can hold up to 462 byte ndef message data.

format(version=None, wipe=None)

Format a Topaz-512 tag for NDEF use.

The implementation of nfc.tag.Tag.format() for a Topaz-512 tag creates a capability container, a Lock Control and a Memory Control TLV, and an NDEF TLV with length zero. Data bytes of the NDEF data area are left untouched unless the wipe argument is set.

protect(password=None, read_protect=False, protect_from=0)

In addtion to nfc.tag.tt1.Type1Tag.protect() this method tries to set the lock bits to irreversibly protect the tag memory. However, it appears that tags sold have the lock bytes write protected, so this additional effort most likely doesn’t have any effect.

Type 2 Tag

exception nfc.tag.tt2.Type2TagCommandError(errno)

Bases: nfc.tag.TagCommandError

Type 2 Tag specific exceptions. Sets errno to one of:

1 - INVALID_SECTOR_ERROR
2 - INVALID_PAGE_ERROR
3 - INVALID_RESPONSE_ERROR
class nfc.tag.tt2.Type2Tag(clf, target)

Bases: nfc.tag.Tag

Implementation of the NFC Forum Type 2 Tag Operation specification.

The NFC Forum Type 2 Tag is based on the ISO 14443 Type A technology for frame structure and anticollision (detection) commands, and the NXP Mifare commands for accessing the tag memory.

dump()

Returns the tag memory pages as a list of formatted strings.

dump() iterates over all tag memory pages (4 bytes each) from page zero until an error response is received and produces a list of strings that is intended for line by line printing. Note that multiple consecutive memory pages of identical content may be reduced to fewer lines of output, so the number of lines returned does not necessarily correspond to the number of memory pages.

format(version=None, wipe=None)

Erase the NDEF message on a Type 2 Tag.

The format() method will reset the length of the NDEF message on a type 2 tag to zero, thus the tag will appear to be empty. Additionally, if the wipe argument is set to some integer then format() will overwrite all user date that follows the NDEF message TLV with that integer (mod 256). If an NDEF message TLV is not present it will be created with a length of zero.

Despite it’s name, the format() method can not format a blank tag to make it NDEF compatible. This is because the user data are of a type 2 tag can not be safely determined, also reading all memory pages until an error response yields only the total memory size which includes an undetermined number of special pages at the end of memory.

It is also not possible to change the NDEF mapping version, located in a one-time-programmable area of the tag memory.

protect(password=None, read_protect=False, protect_from=0)

Protect the tag against write access, i.e. make it read-only.

Type2Tag.protect() switches an NFC Forum Type 2 Tag to read-only state by setting all lock bits to 1. This operation can not be reversed. If the tag is not an NFC Forum Tag, i.e. it is not formatted with an NDEF Capability Container, the protect() method simply returns False.

A generic Type 2 Tag can not be protected with a password. If the password argument is provided, the protect() method does nothing else than return False. The read_protect and protect_from arguments are safely ignored.

read(page)

Send a READ command to retrieve data from the tag.

The page argument specifies the offset in multiples of 4 bytes (i.e. page number 1 will return bytes 4 to 19). The data returned is a byte array of length 16 or None if the block is outside the readable memory range.

Command execution errors raise Type2TagCommandError.

write(page, data)

Send a WRITE command to store data on the tag.

The page argument specifies the offset in multiples of 4 bytes. The data argument must be a string or bytearray of length 4.

Command execution errors raise Type2TagCommandError.

sector_select(sector)

Send a SECTOR_SELECT command to switch the 1K address sector.

The command is only send to the tag if the sector number is different from the currently selected sector number (set to 0 when the tag instance is created). If the command was successful, the currently selected sector number is updated and further read() and write() commands will be relative to that sector.

Command execution errors raise Type2TagCommandError.

transceive(data, timeout=0.1, retries=2)

Send a Type 2 Tag command and receive the response.

transceive() is a type 2 tag specific wrapper around the nfc.ContactlessFrontend.exchange() method. It can be used to send custom commands as a sequence of data bytes to the tag and receive the response data bytes. If timeout seconds pass without a response, the operation is aborted and TagCommandError raised with the TIMEOUT_ERROR error code.

Command execution errors raise Type2TagCommandError.

class nfc.tag.tt2.Type2TagMemoryReader(tag)

Bases: object

The memory reader provides a convenient way to read and write Type2Tag memory. Once instantiated with a proper type 2 tag object the tag memory can then be accessed as a linear sequence of bytes, without any considerations of sector or page boundaries. Modified bytes can be written to tag memory with synchronize().

clf = nfc.ContactlessFrontend(...)
tag = clf.connect(rdwr={'on-connect': None})
if isinstance(tag, nfc.tag.tt2.Type2Tag):
    tag_memory = nfc.tag.tt2.Type2TagMemoryReader(tag)
    tag_memory[16:19] = [0x03, 0x00, 0xFE]
    tag_memory.synchronize()
synchronize()

Write pages that contain modified data back to tag memory.

class nfc.tag.tt2_nxp.MifareUltralight(clf, target)

Bases: nfc.tag.tt2.Type2Tag

Mifare Ultralight is a simple type 2 tag with no specific features. It can store up to 46 byte NDEF message data. This class does not do much more than to provide the known memory size.

class nfc.tag.tt2_nxp.MifareUltralightC(clf, target)

Bases: nfc.tag.tt2.Type2Tag

Mifare Ultralight C provides more memory, to store up to 142 byte NDEF message data, and can be password protected.

protect(password=None, read_protect=False, protect_from=0)

Protect a Mifare Ultralight C Tag.

A Mifare Ultrlight C Tag can be provisioned with a custom password (or the default manufacturer key if the password is an empty string or bytearray).

A non-empty password must provide at least 128 bit key material, in other words it must be a string or bytearray of length 16 or more.

If password is not None, the first protected memory page can be specified with the protect_from integer argument. A memory page is 4 byte and the total number of pages is 48. A protect_from argument of 48 effectively disables memory protection. A protect_from argument of 3 protects all user data pages including the bitwise one-time-programmable page 3. Any value less than 3 or more than 48 is accepted but to the same effect as if 3 or 48 were specified. If effective protection starts at page 3 and the tag is formatted for NDEF, the protect() method does also modify the NDEF read/write capability byte.

If password is not None and read_protect is True then the tag memory content will also be protected against read access, i.e. successful authentication will be required to read protected pages.

The protect() method verifies a password change by authenticating with the new password after all modifications were made and returns the result of authenticate().

Warning

If protect is called without a password, the default Type 2 Tag protection method will set the lock bits to readonly. This process is not reversible.

authenticate(password)

Authenticate with a Mifare Ultralight C Tag.

autenticate() executes the Mifare Ultralight C mutual authentication protocol to verify that the password argument matches the key that is stored in the card. A new card key can be set with protect().

The password argument must be a string with either 0 or at least 16 bytes. A zero length password string indicates that the factory default card key be used. From a password with 16 or more bytes the first 16 byte are taken as card key, remaining bytes are ignored. A password length between 1 and 15 generates a ValueError exception.

The authentication result is True if the password was confirmed and False if not.

class nfc.tag.tt2_nxp.NTAG203(clf, target)

Bases: nfc.tag.tt2.Type2Tag

The NTAG203 is a plain memory Tag with 144 bytes user data memory plus a 16-bit one-way counter. It does not have any security features beyond the standard lock bit mechanism that permanently disables write access.

protect(password=None, read_protect=False, protect_from=0)

Set lock bits to disable future memory modifications.

If password is None, all memory pages except the 16-bit counter in page 41 are protected by setting the relevant lock bits (note that lock bits can not be reset). If valid NDEF management data is found in page 4, protect() also sets the NDEF write flag to read-only.

The NTAG203 can not be password protected. If a password argument is provided, the protect() method always returns False.

class nfc.tag.tt2_nxp.NTAG21x(clf, target)

Bases: nfc.tag.tt2.Type2Tag

Base class for the NTAG21x family (210/212/213/215/216). The methods and attributes documented here are supported for all NTAG21x products.

All NTAG21x products support a simple password protection scheme that can be configured to restrict write as well as read access to memory starting from a selected page address. A factory programmed ECC signature allows to verify the tag unique identifier.

signature

The 32-byte ECC tag signature programmed at chip production. The signature is provided as a string and can only be read.

The signature attribute is always loaded from the tag when it is accessed, i.e. it is not cached. If communication with the tag fails for some reason the signature attribute is set to a 32-byte string of all zeros.

protect(password=None, read_protect=False, protect_from=0)

Set password protection or permanent lock bits.

If the password argument is None, all memory pages will be protected by setting the relevant lock bits (note that lock bits can not be reset). If valid NDEF management data is found, protect() also sets the NDEF write flag to read-only.

All Tags of the NTAG21x family can alternatively be protected by password. If a password argument is provided, the protect() method writes the first 4 byte of the password string into the Tag’s password (PWD) memory bytes and the following 2 byte of the password string into the password acknowledge (PACK) memory bytes. Factory default values are used if the password argument is an empty string. Lock bits are not set for password protection.

The read_protect and protect_from arguments are only evaluated if password is not None. If read_protect is True, the memory protection bit (PROT) is set to require password verification also for reading of protected memory pages. The value of protect_from determines the first password protected memory page (one page is 4 byte) with the exception that the smallest set value is page 3 even if protect_from is smaller.

authenticate(password)

Authenticate with password to access protected memory.

An NTAG21x implements a simple password protection scheme. The reader proofs possession of a share secret by sending a 4-byte password and the tag proofs possession of a shared secret by returning a 2-byte password acknowledge. Because password and password acknowledge are transmitted in plain text special considerations should be given to under which conditions authentication is performed. If, for example, an attacker is able to mount a relay attack both secret values are easily lost.

The password argument must be a string of length zero or at least 6 byte characters. If the password length is zero, authentication is performed with factory default values. If the password contains at least 6 bytes, the first 4 byte are send to the tag as the password secret and the following 2 byte are compared against the password acknowledge that is received from the tag.

The authentication result is True if the password was confirmed and False if not.

class nfc.tag.tt2_nxp.NTAG210(clf, target)

Bases: nfc.tag.tt2_nxp.NTAG21x

The NTAG210 provides 48 bytes user data memory, password protection, originality signature and a UID mirror function.

class nfc.tag.tt2_nxp.NTAG212(clf, target)

Bases: nfc.tag.tt2_nxp.NTAG21x

The NTAG212 provides 128 bytes user data memory, password protection, originality signature and a UID mirror function.

class nfc.tag.tt2_nxp.NTAG213(clf, target)

Bases: nfc.tag.tt2_nxp.NTAG21x

The NTAG213 provides 144 bytes user data memory, password protection, originality signature, a tag read counter and a mirror function for the tag unique identifier and the read counter.

class nfc.tag.tt2_nxp.NTAG215(clf, target)

Bases: nfc.tag.tt2_nxp.NTAG21x

The NTAG215 provides 504 bytes user data memory, password protection, originality signature, a tag read counter and a mirror function for the tag unique identifier and the read counter.

class nfc.tag.tt2_nxp.NTAG216(clf, target)

Bases: nfc.tag.tt2_nxp.NTAG21x

The NTAG216 provides 888 bytes user data memory, password protection, originality signature, a tag read counter and a mirror function for the tag unique identifier and the read counter.

class nfc.tag.tt2_nxp.MifareUltralightEV1(clf, target, product)

Bases: nfc.tag.tt2_nxp.NTAG21x

Mifare Ultralight EV1

class nfc.tag.tt2_nxp.NT3H1101(clf, target)

Bases: nfc.tag.tt2_nxp.NTAGI2C

NTAG I2C 1K.

class nfc.tag.tt2_nxp.NT3H1201(clf, target)

Bases: nfc.tag.tt2_nxp.NTAGI2C

NTAG I2C 2K.

Type 3 Tag

class nfc.tag.tt3.ServiceCode(number, attribute)

A service code provides access to a group of data blocks located on the card file system. A service code is a 16-bit structure composed of a 10-bit service number and a 6-bit service attribute. The service attribute determines the service type and whether authentication is required.

pack()

Pack the service code for transmission. Returns a 2 byte string.

classmethod unpack(s)

Unpack and return a ServiceCode from a byte string.

class nfc.tag.tt3.BlockCode(number, access=0, service=0)

A block code indicates a data block within a service. A block code is a 16-bit or 24-bit structure composed of a length bit (1b if the block number is less than 256), a 3-bit access mode, a 4-bit service list index and an 8-bit or 16-bit block number.

pack()

Pack the block code for transmission. Returns a 2-3 byte string.

class nfc.tag.tt3.Type3Tag(clf, target)

Bases: nfc.tag.Tag

Implementation of the NFC Forum Type 3 Tag specification.

The NFC Forum Type 3 Tag is based on the Sony FeliCa protocol and command specification. An NFC Forum compliant Type 3 Tag responds to a FeliCa polling command with system code 0x12FC and was configured to support service code 0x000B for NDEF data read and service code 0x0009 for NDEF data write (the latter may not be present if the tag is read-only) without encryption.

dump()

Read all data blocks of an NFC Forum Tag.

For an NFC Forum Tag (system code 0x12FC) dump() reads all data blocks from service 0x000B (NDEF read service) and returns a list of strings suitable for printing. The number of strings returned does not necessarily reflect the number of data blocks because a range of data blocks with equal content is reduced to fewer lines of output.

dump_service(sc)

Read all data blocks of a given service.

dump_service() reads all data blocks from the service with service code sc and returns a list of strings suitable for printing. The number of strings returned does not necessarily reflect the number of data blocks because a range of data blocks with equal content is reduced to fewer lines of output.

format(version=None, wipe=None)

Format and blank an NFC Forum Type 3 Tag.

A generic NFC Forum Type 3 Tag can be (re)formatted if it is in either one of blank, initialized or readwrite state. By formatting, all contents of the attribute information block is overwritten with values determined. The number of user data blocks is determined by reading all memory until an error response. Similarily, the maximum number of data block that can be read or written with a single command is determined by sending successively increased read and write commands. The current data length is set to zero. The NDEF mapping version is set to the latest known version number (1.0), unless the version argument is provided and it’s major version number corresponds to one of the known major version numbers.

By default, no data other than the attribute block is modified. To overwrite user data the wipe argument must be set to an integer value. The lower 8 bits of that value are written to all data bytes that follow the attribute block.

polling(system_code=65535, request_code=0, time_slots=0)

Aquire and identify a card.

The Polling command is used to detect the Type 3 Tags in the field. It is also used for initialization and anti-collision.

The system_code identifies the card system to acquire. A card can have multiple systems. The first system that matches system_code will be activated. A value of 0xff for any of the two bytes works as a wildcard, thus 0xffff activates the very first system in the card. The card identification data returned are the Manufacture ID (IDm) and Manufacture Parameter (PMm).

The request_code tells the card whether it should return additional information. The default value 0 requests no additional information. Request code 1 means that the card shall also return the system code, so polling for system code 0xffff with request code 1 can be used to identify the first system on the card. Request code 2 asks for communication performance data, more precisely a bitmap of possible communication speeds. Not all cards provide that information.

The number of time_slots determines whether there’s a chance to receive a response if multiple Type 3 Tags are in the field. For the reader the number of time slots determines the amount of time to wait for a response. Any Type 3 Tag in the field, i.e. powered by the field, will choose a random time slot to respond. With the default time_slots value 0 there will only be one time slot available for all responses and multiple responses would produce a collision. More time slots reduce the chance of collisions (but may result in an application working with a tag that was just accidentially close enough). Only specific values should be used for time_slots, those are 0, 1, 3, 7, and 15. Other values may produce unexpected results depending on the tag product.

polling() returns either the tuple (IDm, PMm) or the tuple (IDm, PMm, additional information) depending on the response lengt, all as bytearrays.

Command execution errors raise TagCommandError.

read_without_encryption(service_list, block_list)

Read data blocks from unencrypted services.

This method sends a Read Without Encryption command to the tag. The data blocks to read are indicated by a sequence of BlockCode objects in block_list. Each block code must reference a ServiceCode object from the iterable service_list. If any of the blocks and services do not exist, the tag will stop processing at that point and return a two byte error status. The status bytes become the errno value of the TagCommandError exception.

As an example, the following code reads block 5 from service 16 (service type ‘random read-write w/o key’) and blocks 0 to 1 from service 80 (service type ‘random read-only w/o key’):

sc1 = nfc.tag.tt3.ServiceCode(16, 0x09)
sc2 = nfc.tag.tt3.ServiceCode(80, 0x0B)
bc1 = nfc.tag.tt3.BlockCode(5, service=0)
bc2 = nfc.tag.tt3.BlockCode(0, service=1)
bc3 = nfc.tag.tt3.BlockCode(1, service=1)
try:
    data = tag.read_without_encryption([sc1, sc2], [bc1, bc2, bc3])
except nfc.tag.TagCommandError as e:
    if e.errno > 0x00FF:
        print("the tag returned an error status")
    else:
        print("command failed with some other error")

Command execution errors raise TagCommandError.

read_from_ndef_service(*blocks)

Read block data from an NDEF compatible tag.

This is a convinience method to read block data from a tag that has system code 0x12FC (NDEF). For other tags this method simply returns None. All arguments are block numbers to read. To actually pass a list of block numbers requires unpacking. The following example calls would have the same effect of reading 32 byte data from from blocks 1 and 8.:

data = tag.read_from_ndef_service(1, 8)
data = tag.read_from_ndef_service(*list(1, 8))

Command execution errors raise TagCommandError.

write_without_encryption(service_list, block_list, data)

Write data blocks to unencrypted services.

This method sends a Write Without Encryption command to the tag. The data blocks to overwrite are indicated by a sequence of BlockCode objects in the parameter block_list. Each block code must reference one of the ServiceCode objects in the iterable service_list. If any of the blocks or services do not exist, the tag will stop processing at that point and return a two byte error status. The status bytes become the errno value of the TagCommandError exception. The data to write must be a byte string or array of length 16 * len(block_list).

As an example, the following code writes 16 * "\xAA" to block 5 of service 16, 16 * "\xBB" to block 0 of service 80 and 16 * "\xCC" to block 1 of service 80 (all services are writeable without key):

sc1 = nfc.tag.tt3.ServiceCode(16, 0x09)
sc2 = nfc.tag.tt3.ServiceCode(80, 0x09)
bc1 = nfc.tag.tt3.BlockCode(5, service=0)
bc2 = nfc.tag.tt3.BlockCode(0, service=1)
bc3 = nfc.tag.tt3.BlockCode(1, service=1)
sc_list = [sc1, sc2]
bc_list = [bc1, bc2, bc3]
data = 16 * "\xAA" + 16 * "\xBB" + 16 * "\xCC"
try:
    data = tag.write_without_encryption(sc_list, bc_list, data)
except nfc.tag.TagCommandError as e:
    if e.errno > 0x00FF:
        print("the tag returned an error status")
    else:
        print("command failed with some other error")

Command execution errors raise TagCommandError.

write_to_ndef_service(data, *blocks)

Write block data to an NDEF compatible tag.

This is a convinience method to write block data to a tag that has system code 0x12FC (NDEF). For other tags this method simply does nothing. The data to write must be a string or bytearray with length equal 16 * len(blocks). All parameters following data are interpreted as block numbers to write. To actually pass a list of block numbers requires unpacking. The following example calls would have the same effect of writing 32 byte zeros into blocks 1 and 8.:

tag.write_to_ndef_service(32 * "\0", 1, 8)
tag.write_to_ndef_service(32 * "\0", *list(1, 8))

Command execution errors raise TagCommandError.

send_cmd_recv_rsp(cmd_code, cmd_data, timeout, send_idm=True, check_status=True)

Send a command and receive a response.

This low level method sends an arbitrary command with the 8-bit integer cmd_code, followed by the captured tag identifier (IDm) if send_idm is True and the byte string or bytearray cmd_data. It then waits timeout seconds for a response, verifies that the response is correctly formatted and, if check_status is True, that the status flags do not indicate an error.

All errors raise a TagCommandError exception. Errors from response status flags produce an errno that is greater than 255, all other errors are below 256.

class nfc.tag.tt3.Type3TagEmulation(clf, target)

Bases: nfc.tag.TagEmulation

Framework for Type 3 Tag emulation.

class nfc.tag.tt3_sony.FelicaStandard(clf, target)

Bases: nfc.tag.tt3.Type3Tag

Standard FeliCa is a range of FeliCa OS based card products with a flexible file system that supports multiple applications and services on the same card. Services can individually be protected with a card key and all communication with protected services is encrypted.

request_service(service_list)

Verify existence of a service (or area) and get the key version.

Each service (or area) to verify must be given as a ServiceCode in the iterable service_list. The key versions are returned as a list of 16-bit integers, in the order requested. If a specified service (or area) does not exist, the key version will be 0xFFFF.

Command execution errors raise TagCommandError.

request_response()

Verify that a card is still present and get its operating mode.

The Request Response command returns the current operating state of the card. The operating state changes with the authentication process, a card is in Mode 0 after power-up or a Polling command, transitions to Mode 1 with Authentication1, to Mode 2 with Authentication2, and Mode 3 with any of the card issuance commands. The request_response() method returns the mode as an integer.

Command execution errors raise TagCommandError.

search_service_code(service_index)

Search for a service code that corresponds to an index.

The Search Service Code command provides access to the iterable list of services and areas within the activated system. The service_index argument may be any value from 0 to 0xffff. As long as there is a service or area found for a given service_index, the information returned is a tuple with either one or two 16-bit integer elements. Two integers are returned for an area definition, the first is the area code and the second is the largest possible service index for the area. One integer, the service code, is returned for a service definition. The return value is None if the service_index was not found.

For example, to print all services and areas of the active system:

for i in xrange(0x10000):
    area_or_service = tag.search_service_code(i)
    if area_or_service is None:
        break
    elif len(area_or_service) == 1:
        sc = area_or_service[0]
        print(nfc.tag.tt3.ServiceCode(sc >> 6, sc & 0x3f))
    elif len(area_or_service) == 2:
        area_code, area_last = area_or_service
        print("Area {0:04x}--{0:04x}".format(area_code, area_last))

Command execution errors raise TagCommandError.

request_system_code()

Return all system codes that are registered in the card.

A card has one or more system codes that correspond to logical partitions (systems). Each system has a system code that could be used in a polling command to activate that system. The system codes responded by the card are returned as a list of 16-bit integers.

for system_code in tag.request_system_code():
    print("System {0:04X}".format(system_code))

Command execution errors raise TagCommandError.

class nfc.tag.tt3_sony.FelicaMobile(clf, target)

Bases: nfc.tag.tt3_sony.FelicaStandard

Mobile FeliCa is a modification of FeliCa for use in mobile phones. This class does currently not implement anything specific beyond recognition of the Mobile FeliCa OS version.

class nfc.tag.tt3_sony.FelicaLite(clf, target)

Bases: nfc.tag.tt3.Type3Tag

FeliCa Lite is a version of FeliCa with simplified file system and security functions. The usable memory is 13 blocks (one block has 16 byte) plus a one block subtraction register. The tag can be configured with a card key to authenticate the tag and protect integrity of data reads.

protect(password=None, read_protect=False, protect_from=0)

Protect a FeliCa Lite Tag.

A FeliCa Lite Tag can be provisioned with a custom password (or the default manufacturer key if the password is an empty string or bytearray) to ensure that data retrieved by future read operations, after authentication, is genuine. Read protection is not supported.

A non-empty password must provide at least 128 bit key material, in other words it must be a string or bytearray of length 16 or more.

The memory unit for the value of protect_from is 16 byte, thus with protect_from=2 bytes 0 to 31 are not protected. If protect_from is zero (the default value) and the Tag has valid NDEF management data, the NDEF RW Flag is set to read only.

authenticate(password)

Authenticate a FeliCa Lite Tag.

A FeliCa Lite Tag is authenticated by a procedure that allows both the reader and the tag to calculate a session key from a random challenge send by the reader and a key that is securely stored on the tag and provided to authenticate() as the password argument. If the tag was protected with an earlier call to protect() then the same password should successfully authenticate.

After authentication the read_with_mac() method can be used to read data such that it can not be falsified on transmission.

format(version=16, wipe=None)

Format a FeliCa Lite Tag for NDEF.

read_without_mac(*blocks)

Read a number of data blocks without integrity check.

This method accepts a variable number of integer arguments as the block numbers to read. The blocks are read with service code 0x000B (NDEF).

Tag command errors raise TagCommandError.

read_with_mac(*blocks)

Read a number of data blocks with integrity check.

This method accepts a variable number of integer arguments as the block numbers to read. The blocks are read with service code 0x000B (NDEF). Along with the requested block data the tag returns a message authentication code that is verified before data is returned. If verification fails the return value of read_with_mac() is None.

A RuntimeError exception is raised if the tag was not authenticated before calling this method.

Tag command errors raise TagCommandError.

write_without_mac(data, block)

Write a data block without integrity check.

This is the standard write method for a FeliCa Lite. The 16-byte string or bytearray data is written to the numbered block in service 0x0009 (NDEF write service).

data = bytearray(range(16)) # 0x00, 0x01, ... 0x0F
try: tag.write_without_mac(data, 5) # write block 5
except nfc.tag.TagCommandError:
    print("something went wrong")

Tag command errors raise TagCommandError.

class nfc.tag.tt3_sony.FelicaLiteS(clf, target)

Bases: nfc.tag.tt3_sony.FelicaLite

FeliCa Lite-S is a version of FeliCa Lite with enhanced security functions. It provides mutual authentication were both the tag and the reader must demonstrate posession of the card key before data writes can be made. It is also possible to require mutual authentication for data reads.

protect(password=None, read_protect=False, protect_from=0)

Protect a FeliCa Lite-S Tag.

A FeliCa Lite-S Tag can be write and read protected with a custom password (or the default manufacturer key if the password is an empty string or bytearray). Note that the read_protect flag is only evaluated when a password is provided.

A non-empty password must provide at least 128 bit key material, in other words it must be a string or bytearray of length 16 or more.

The memory unit for the value of protect_from is 16 byte, thus with protect_from=2 bytes 0 to 31 are not protected. If protect_from is zero (the default value) and the Tag has valid NDEF management data, the NDEF RW Flag is set to read only.

authenticate(password)

Mutually authenticate with a FeliCa Lite-S Tag.

FeliCa Lite-S supports enhanced security functions, one of them is the mutual authentication performed by this method. The first part of mutual authentication is to authenticate the tag with FelicaLite.authenticate(). If successful, the shared session key is used to generate the integrity check value for write operation to update a specific memory block. If that was successful then the tag is ensured that the reader has the correct card key.

After successful authentication the read_with_mac() and write_with_mac() methods can be used to read and write data such that it can not be falsified on transmission.

write_with_mac(data, block)

Write one data block with additional integrity check.

If prior to calling this method the tag was not authenticated, a RuntimeError exception is raised.

Command execution errors raise TagCommandError.

class nfc.tag.tt3_sony.FelicaPlug(clf, target)

Bases: nfc.tag.tt3.Type3Tag

FeliCa Plug is a contactless communication interface module for microcontrollers.

Type 4 Tag

exception nfc.tag.tt4.Type4TagCommandError(errno)

Bases: nfc.tag.TagCommandError

Type 4 Tag exception class. Beyond the generic error values from TagCommandError this class covers ISO 7816-4 response APDU error codes.

class nfc.tag.tt4.Type4Tag(clf, target)

Bases: nfc.tag.Tag

Implementation of the NFC Forum Type 4 Tag operation specification.

The NFC Forum Type 4 Tag is based on ISO/IEC 14443 DEP protocol for Type A and B modulation and uses ISO/IEC 7816-4 command and response APDUs.

dump()

Returns tag data as a list of formatted strings.

The dump() method provides useful output only for NDEF formatted Type 4 Tags. Each line that is returned contains a hexdump of 16 octets from the NDEF data file.

format(version=None, wipe=None)

Erase the NDEF message on a Type 4 Tag.

The format() method writes the length of the NDEF message on a Type 4 Tag to zero, thus the tag will appear to be empty. If the wipe argument is set to some integer then format() will also overwrite all user data with that integer (mod 256).

Despite it’s name, the format() method can not format a blank tag to make it NDEF compatible; this requires proprietary information from the manufacturer.

transceive(data, timeout=None)

Transmit arbitrary data and receive the response.

This is a low level method to send arbitrary data to the tag. While it should almost always be better to use send_apdu() this is the only way to force a specific timeout value (which is otherwise derived from the Tag’s answer to select). The timeout value is expected as a float specifying the seconds to wait.

send_apdu(cla, ins, p1, p2, data=None, mrl=0, check_status=True)

Send an ISO/IEC 7816-4 APDU to the Type 4 Tag.

The 4 byte APDU header (class, instruction, parameter 1 and 2) is constructed from the first four parameters (cla, ins, p1, p2) without interpretation. The byte string data argument represents the APDU command data field. It is encoded as a short or extended length field followed by the data bytes. The length field is not transmitted if data is None or an empty string. The maximum acceptable number of response data bytes is given with the max-response-length mrl argument. The value of mrl is transmitted as the 7816-4 APDU Le field after appropriate conversion.

By default, the response is returned as a byte array not including the status word, a Type4TagCommandError exception is raised for any status word other than 9000h. Response status verification can be disabled with check_status set to False, the byte array will then include the response status word at the last two positions.

Transmission errors always raise a Type4TagCommandError exception.