Issue with NFC Tag (NTAG213) Becoming Unwritable Without Storing Desired URL Data

32 Views Asked by At

I've been working on a project involving NTAG213 NFC tags. My objective is to write a specific URL to these NFC tags and then lock them to prevent any further modification or overwriting. However, I'm encountering a peculiar issue: after executing my Python script, the NFC tags indeed become unrewritable, but the URL data I intended to store on them doesn't appear to be written. I'm looking for insights or solutions as to why this might be happening.

Here's the Python script I'm using:

from smartcard.System import readers
from smartcard.util import toBytes
from smartcard.Exceptions import NoCardException

def create_ndef_uri_record(url):
    # Create an NDEF record for the URL
    uri_prefix_code = 0x03  # 0x03 for 'http://'
    ndef_header = [0x03, len(url) + 5, 0xD1, 0x01, len(url) + 1, 0x55, uri_prefix_code]
    ndef_uri_field = [ord(c) for c in url]
    ndef_end = [0xFE]
    return ndef_header + ndef_uri_field + ndef_end

def write_to_card(connection, data, start_page=4):
    # Write data to the card
    for i in range(0, len(data), 4):
        page = start_page + i // 4
        command = [0xFF, 0xD6, 0x00, page, 4] + data[i:i+4]
        response, sw1, sw2 = connection.transmit(command)
        if sw1 != 0x90 or sw2 != 0x00:
            raise Exception(f"Error writing to card: SW1={sw1}, SW2={sw2}")

def lock_nfc_tag(connection):
    # Lock the card to prevent overwriting
    # For NTAG213, lock the card by setting lock bits and OTP
    lock_command = [0xFF, 0xD6, 0x00, 0x2A, 0x04, 0x00, 0x00, 0x0F, 0xE0]  # Example lock command
    otp_command = [0xFF, 0xD6, 0x00, 0x03, 0x04, 0xBD, 0x04, 0xBD, 0x04]  # Example OTP setting command

    # Send lock command
    response, sw1, sw2 = connection.transmit(lock_command)
    if sw1 != 0x90 or sw2 != 0x00:
        raise Exception(f"Error locking card: SW1={sw1}, SW2={sw2}")

    # Send OTP setting command
    response, sw1, sw2 = connection.transmit(otp_command)
    if sw1 != 0x90 or sw2 != 0x00:
        raise Exception(f"Error setting OTP: SW1={sw1}, SW2={sw2}")

    print("Card permanently locked and OTP set")

def main():
    url = "example.com"

    card_readers = readers()
    if not card_readers:
        print("No NFC card readers found")
        return

    reader = card_readers[0]
    connection = reader.createConnection()

    try:
        connection.connect()
        print("Connected to NFC card successfully")
        ndef_record = create_ndef_uri_record(url)
        write_to_card(connection, ndef_record)
        print("URL written to NFC card successfully")
        lock_nfc_tag(connection)

    except NoCardException:
        print("No NFC card found")
    except Exception as e:
        print(f"Error encountered: {e}")

if __name__ == "__main__":
    main()
0

There are 0 best solutions below