Skip to content

API reference

This reference is generated from the docstrings in the source code, so it always matches the installed version. Everything below can be imported from the top-level package:

from mifarepy import (
    MifareReader, SectorAuth, CardInfo, layout,
    GNetPlusError, AuthenticationError, NoCardError, InvalidMessage,  # and the other errors below
    ReaderConnectionError, ReaderNotFoundError,
    AccessBits, KeyRing, UnsafeTrailerError, CardEvent,
    enable_wire_trace, disable_wire_trace,
    QueryMessage, ResponseMessage, Message, gencrc,
)
from mifarepy.access import build_trailer, decode_trailer, check_trailer
from mifarepy.keys import diversify_key
from mifarepy.schema import CardSchema, Field
from mifarepy.wallet import Wallet, InsufficientFundsError
from mifarepy.simulator import SimulatedCard, SimulatedReader
from mifarepy.discovery import find_ports

Reader

MifareReader

MifareReader(port: str = '/dev/ttyUSB0', baudrate: int = 19200, deviceaddr: int = 0, *, value_ops: ValueOps = 'auto', **kwargs: Any)

Class for interfacing with the RFID card reader.

Can be used as a context manager to ensure the serial port is closed:

with MifareReader('/dev/ttyUSB0') as reader:
    uid = reader.get_uid()

with MifareReader.auto() as reader:          # find the reader automatically
    uid = reader.get_uid()

Initialize the RFID reader connection.

Parameters:

Name Type Description Default
port str

Serial port name (e.g., '/dev/ttyUSB0').

'/dev/ttyUSB0'
baudrate int

Baudrate for interfacing with the device. Don't change this unless you know what you're doing.

19200
deviceaddr int

Device address (default: 0).

0
value_ops ValueOps

How value-block arithmetic is performed. 'auto' (default) increments and decrements by read-modify-write, and uses the native RESTORE / TRANSFER commands for transfer() / restore(), verifying the result and falling back to read-modify-write if they fail. 'native' uses only the native commands, including SET_VALUE for increment/decrement; 'software' uses only read-modify-write (the behaviour before 3.1).

'auto'
**kwargs Any

Extra keyword arguments passed to serial.Serial.

{}

Raises:

Type Description
ReaderConnectionError

If the serial port cannot be opened (a RuntimeError subclass whose message includes a fix hint).

from_serial classmethod

from_serial(serial_port: Any, *, deviceaddr: int = 0, value_ops: ValueOps = 'auto') -> MifareReader

Use an already-open serial port (or any object with the same interface).

The object needs read(n), write(data), a timeout attribute, and ideally reset_input_buffer(), close() and is_open. This is how simulated() plugs in a SimulatedReader.

Parameters:

Name Type Description Default
serial_port Any

An open serial.Serial or compatible object.

required
deviceaddr int

Device address (default: 0).

0
value_ops ValueOps

See the constructor.

'auto'

simulated classmethod

simulated(card: Any = None, *, empty: bool = False, **kwargs: Any) -> MifareReader

Create a reader connected to a mifarepy.simulator.SimulatedReader.

No hardware is needed: use it in tests, demos and CI. The simulator is available as reader.serial, so you can place and remove cards:

from mifarepy import MifareReader
from mifarepy.simulator import SimulatedCard

reader = MifareReader.simulated()            # a blank 1K card is in the field
reader.serial.place_card(SimulatedCard(uid='0x11223344', size='4K'))

Parameters:

Name Type Description Default
card Any

A SimulatedCard to put in the field. Defaults to a new blank 1K card.

None
empty bool

Start with no card in the field instead.

False
**kwargs Any

Passed to from_serial() (deviceaddr, value_ops).

{}

auto classmethod

auto(*, probe: bool = True, include_all: bool = False, **kwargs: Any) -> MifareReader

Find a connected reader and open it.

Looks for serial ports whose USB IDs match the bridge used in PROMAG readers (Prolific PL2303), and, with probe=True, checks that each one answers a GNetPlus POLLING command before returning it.

with MifareReader.auto() as reader:
    print(reader.port, reader.get_version())

Parameters:

Name Type Description Default
probe bool

Confirm each candidate answers before using it. Set to False to open the first matching port without sending anything.

True
include_all bool

Also try ports that don't look like a PROMAG reader, such as RS-232 adapters with other chips. Probing sends a few bytes to each port, so only use this when no other serial devices could be disturbed.

False
**kwargs Any

Passed to the constructor (baudrate, value_ops, timeout, ...).

{}

Raises:

Type Description
ReaderNotFoundError

If no reader was found. Its message lists the serial ports that were seen.

close

close() -> None

Reset auto mode then close the underlying serial port.

Disabling auto mode before closing ensures the reader is left in a clean, command-driven state so the next session does not receive spurious EVN events or NAK responses from a lingering event mode.

reconnect

reconnect(attempts: int = 1, interval: float = 1.0) -> None

Open the connection to the reader again, e.g. after the USB cable was unplugged.

A reader made with auto() is searched for again, because its port name may change; one opened by port name reopens that port. The reader must answer POLLING. Authentication is cleared.

try:
    uid = reader.get_uid()
except (serial.SerialException, OSError):
    reader.reconnect(attempts=10)

Parameters:

Name Type Description Default
attempts int

How many times to try.

1
interval float

Seconds between attempts.

1.0

Raises:

Type Description
ReaderConnectionError

If the reader could not be reached.

session

session() -> Iterator[MifareReader]

Hold the reader for a sequence of commands that must not be interrupted.

Every method already holds the reader's lock while it runs, so threads sharing one reader never mix up frames. Use a session when several calls belong together, such as authenticating a sector and then reading it, so another thread can't authenticate a different sector in between:

with reader.session():
    reader.authenticate_sector(1, key)
    data = reader.read_block(0)

card_events

card_events(interval: float = 0.25, *, removal_polls: int = 2, reconnect: bool = True, reconnect_interval: float = 1.0, stop: Optional[Event] = None) -> Iterator[CardEvent]

Yield a CardEvent each time a card arrives or leaves, polling the reader.

A card resting on the reader is reported once. If the reader stops answering (USB cable pulled), a 'disconnected' event is yielded and the reader is reopened every reconnect_interval seconds until it is back ('reconnected').

for event in reader.card_events():
    if event.kind == 'arrived':
        print('Card', event.uid)

Parameters:

Name Type Description Default
interval float

Seconds between polls.

0.25
removal_polls int

Polls in a row without the card before it counts as removed (default 2, so a flicker in the field is ignored).

2
reconnect bool

Reconnect after the reader is lost. If False, the serial error is raised instead.

True
reconnect_interval float

Seconds between reconnection attempts.

1.0
stop Optional[Event]

Optional threading.Event; set it to end the loop.

None

cards async

cards(interval: float = 0.25, *, removal_polls: int = 2, reconnect: bool = True, reconnect_interval: float = 1.0) -> AsyncIterator[CardEvent]

Async version of card_events(): serial I/O runs in a worker thread.

async for event in reader.cards():
    if event.kind == 'arrived':
        await handle(event.uid)

Stop by breaking out of the loop or cancelling the task. Arguments are as for card_events().

sendmsg

sendmsg(function: int, data: bytes = b'') -> None

Construct and send a QueryMessage to the RFID reader.

Parameters:

Name Type Description Default
function int

@see Message.function

required
data bytes

@see Message.data

b''

readmsg

readmsg(sink_events: bool = False) -> ResponseMessage

Read a message, optionally ignoring EVN (event) messages which are device-driven.

Parameters:

Name Type Description Default
sink_events bool

If True, silently discard EVN messages.

False

Returns:

Type Description
ResponseMessage

Constructed ResponseMessage instance.

Raises:

Type Description
GNetPlusError

If a NAK response is received.

get_sn

get_sn(endian: str = 'little', as_string: bool = True) -> Union[str, int]

Get the serial number of the card currently in the RF field.

Deprecated

Use get_uid() (returns '0xAABBCCDD' string) or get_uid_int() (returns unsigned integer) instead.

Parameters:

Name Type Description Default
endian str

'big' or 'little'. Selects byte order for the 4-byte UID from the ANTI_COLLISION response.

'little'
as_string bool

If True returns '0xAABBCCDD' hex string; otherwise an unsigned integer.

True

Returns:

Type Description
Union[str, int]

Card UID as hex string or integer.

get_uid

get_uid() -> str

Return the 4-byte UID of the card currently in the RF field as a zero-padded upper-case hex string (e.g. '0xEDCEF8C3').

Internally runs REQUEST → ANTI_COLLISION. Does not call SELECT; use scan_tag() or select_card() when you need the card to be in an active/authenticated state.

Returns:

Type Description
str

UID string like '0xAABBCCDD'.

Raises:

Type Description
GNetPlusError

If no card is present or the reader returns NAK.

get_uid_int

get_uid_int() -> int

Return the 4-byte UID of the card currently in the RF field as an unsigned 32-bit integer (little-endian byte order).

Returns:

Type Description
int

Unsigned 32-bit UID integer.

Raises:

Type Description
GNetPlusError

If no card is present or the reader returns NAK.

request_all

request_all(endian: str = 'little', as_string: bool = True) -> Union[str, int]

Enumerate all cards in field (REQUEST_ALL + ANTI_COLLISION), including cards in HALT state. Useful for multi-card scanning.

Parameters:

Name Type Description Default
endian str

'big' or 'little' byte order for the 4-byte UID.

'little'
as_string bool

If True returns hex string; otherwise integer.

True

Returns:

Type Description
Union[str, int]

Card UID as hex string or integer.

get_second_sn

get_second_sn(as_string: Literal[True]) -> str
get_second_sn(as_string: Literal[False]) -> bytes
get_second_sn(as_string: bool = ...) -> Union[str, bytes]
get_second_sn(as_string: bool = True) -> Union[str, bytes]

Retrieve the secondary serial number (7-byte UID for MIFARE UltraLight / DESFire and other ISO 14443-3 compliant cards).

Parameters:

Name Type Description Default
as_string bool

If True returns hex string; otherwise raw bytes.

True

Returns:

Type Description
Union[str, bytes]

Secondary serial number as hex string or bytes.

select_card

select_card() -> bytes

Run REQUEST → ANTI_COLLISION → SELECT_CARD to bring a card into the active state ready for authentication and block operations.

Called automatically by authenticate_sector() before every key-load / authenticate sequence, so you normally do not need to call this directly. It is still public for advanced multi-card workflows (see example 08).

Returns:

Type Description
bytes

ACK payload bytes from the SELECT_CARD response.

Raises:

Type Description
GNetPlusError

If any step returns a NAK.

card_type

card_type() -> Literal['1K', '4K', 'Ultralight', 'unknown']

Tell what kind of card is on the reader.

Uses the card's answer to REQUEST (ATQA) and SELECT (SAK): ATQA 44 00 is a MIFARE Ultralight, SAK 0x08 a Classic 1K and SAK 0x18 a Classic 4K. Clears the current authentication.

Returns:

Type Description
Literal['1K', '4K', 'Ultralight', 'unknown']

'1K', '4K', 'Ultralight' or 'unknown'.

Raises:

Type Description
NoCardError

If there is no card.

ping

ping() -> bool

Send a POLLING heartbeat to the reader and return True if it responds with ACK.

Use this to verify the serial connection is alive without interacting with any card. The reader responds even when no card is present.

Returns:

Type Description
bool

True if the reader acknowledged the POLLING command.

Raises:

Type Description
GNetPlusError

If the reader explicitly NAKs (unusual).

is_card_present

is_card_present() -> bool

Non-blocking check: send a single REQUEST and return whether any card responded.

Does not select or authenticate the card — use scan_tag() or select_card() for that.

Returns:

Type Description
bool

True if a card is in the RF field, False otherwise.

scan_tag

scan_tag() -> CardInfo

One-shot card detection: REQUEST → ANTI_COLLISION → SELECT_CARD.

Returns a CardInfo dataclass with the UID available in multiple representations. The card is left in the active state so you can immediately call authenticate_sector() / read_block() etc.

Usage example:

card = reader.scan_tag()
print(card)            # '0xEDCEF8C3'
print(card.uid_int)    # 3989956803

Returns:

Type Description
CardInfo

CardInfo with uid, uid_int, and uid_bytes.

Raises:

Type Description
GNetPlusError

If no card is present or any step fails.

wait_for_card

wait_for_card(timeout: float = 10.0) -> str

Check if a card is already present; if not, wait for a card-insert event.

Parameters:

Name Type Description Default
timeout float

Maximum time to wait in seconds (default: 10).

10.0

Returns:

Type Description
str

Card serial number string.

Raises:

Type Description
TimeoutError

If no card is detected within the timeout.

wait_for_card_async async

wait_for_card_async(timeout: float = 10.0) -> str

Async variant of wait_for_card. Does not block the event loop — serial I/O runs in a thread-pool executor.

Suitable for use inside asyncio-based applications (FastAPI, Django async views, automation scripts using asyncio.run).

Usage example:

import asyncio
from mifarepy import MifareReader

async def main():
    with MifareReader('/dev/ttyUSB0') as reader:
        uid = await reader.wait_for_card_async(timeout=15)
        print('Card:', uid)

asyncio.run(main())

Parameters:

Name Type Description Default
timeout float

Maximum seconds to wait (default: 10).

10.0

Returns:

Type Description
str

Card UID as hex string.

Raises:

Type Description
TimeoutError

If no card is detected within the timeout.

get_version

get_version() -> str

Get product version string.

Returns:

Type Description
str

Firmware/hardware version string from the connected reader.

set_auto_mode

set_auto_mode(enabled: bool = True) -> bytes

Toggle auto mode — whether the device emits EVN events when a card enters field.

Parameters:

Name Type Description Default
enabled bool

True to enable, False to disable.

True

Returns:

Type Description
bytes

Confirmed mode byte from the device.

Raises:

Type Description
GNetPlusError

If the device reports failure to set the mode.

halt

halt() -> None

Send HALT to deselect the current card and put it into HALT state.

The card will not respond to subsequent REQUEST commands (only REQUEST_ALL). Call this after finishing operations on a card in multi-card scenarios.

Raises:

Type Description
GNetPlusError

If the reader returns a NAK.

rf_power

rf_power(on: bool) -> None

Switch the RF field power on or off.

Turning the RF field off and back on can reset cards that are in an inconsistent state without physically removing them.

Parameters:

Name Type Description Default
on bool

True to power on the RF field, False to power it off.

required

Raises:

Type Description
GNetPlusError

If the reader returns a NAK.

authenticate_sector

authenticate_sector(sector: int, key: bytes, key_type: str = 'A', timeout: float = 1.0, flush: bool = True) -> None

Load a key into the reader and authenticate the specified MIFARE Classic sector.

Parameters:

Name Type Description Default
sector int

Sector number to authenticate (0-15 for 1K; 0-39 for 4K).

required
key bytes

6-byte authentication key.

required
key_type str

'A' for Key A (0x60) or 'B' for Key B (0x61).

'A'
timeout float

Timeout in seconds for reader responses.

1.0
flush bool

Whether to flush the input buffer before reading responses.

True

Raises:

Type Description
ValueError

If key_type is invalid or key length is not 6 bytes.

GNetPlusError

If the reader returns NAK during key load or authentication.

authenticate_sector_cached

authenticate_sector_cached(sector: int, key_type: Literal['A', 'B'] = 'A', timeout: float = 1.0) -> None

Authenticate a sector using the key the reader already stores for it.

The reader keeps one key per sector and key type. authenticate_sector() saves the key for that sector (SAVE_KEY, opcode 0x2B); this method skips that step and sends AUTHENTICATE (opcode 0x23), which uses the stored key. It saves about 50 ms per call.

reader.authenticate_sector(2, key)           # stores key for sector 2, key A
...
reader.authenticate_sector_cached(2)         # re-authenticates sector 2 later
Note

The key is stored per sector. Authenticating sector 1 does not store a key for sector 2, so authenticate_sector_cached(2) uses whatever key was saved for sector 2 before, if any. Call authenticate_sector() once for each sector first.

Parameters:

Name Type Description Default
sector int

Sector to authenticate (0-15 for 1K; 0-39 for 4K).

required
key_type Literal['A', 'B']

'A' for Key A (0x60) or 'B' for Key B (0x61).

'A'
timeout float

Timeout in seconds for the reader response.

1.0

Raises:

Type Description
ValueError

If key_type is invalid.

AuthenticationError

If the stored key does not match the card.

GNetPlusError

If the reader returns another NAK.

read_block

read_block(block: int, raw: Literal[True]) -> bytes
read_block(block: int, raw: Literal[False] = ...) -> str
read_block(block: int, raw: bool = ...) -> Union[bytes, str]
read_block(block: int, raw: bool = False) -> Union[bytes, str]

Read a single 16-byte block from the currently authenticated sector.

Parameters:

Name Type Description Default
block int

Block index relative to the authenticated sector (0-3).

required
raw bool

If True returns bytes; if False returns hex string.

False

Returns:

Type Description
Union[bytes, str]

Block data as bytes (raw=True) or hex string (raw=False).

Raises:

Type Description
GNetPlusError

If the read fails.

write_block

write_block(block: int, data: Union[str, bytes]) -> str

Write a 16-byte block to the currently authenticated sector.

Parameters:

Name Type Description Default
block int

Block index relative to the authenticated sector (0-3).

required
data Union[str, bytes]

Data to write -- exactly 16 bytes or a 32-character hex string.

required

Returns:

Type Description
str

Reader's echoed data in hex format.

Raises:

Type Description
ValueError

If data is not exactly 16 bytes.

GNetPlusError

If the write fails.

read_access

read_access(sector: Optional[int] = None) -> AccessBits

Read and decode the access bits of the authenticated sector.

reader.authenticate_sector(1, key)
print(reader.read_access().describe())

Parameters:

Name Type Description Default
sector Optional[int]

The sector, which must be the one authenticated last (default: that one).

None

Raises:

Type Description
ValueError

If no sector (or a different one) is authenticated.

UnsafeTrailerError

If the trailer holds invalid access bits.

GNetPlusError

If the read fails.

write_trailer

write_trailer(key_a: Union[bytes, str], key_b: Union[bytes, str], access: Union[AccessBits, bytes, None] = None, *, sector: Optional[int] = None, allow_permanent: bool = False, verify: bool = True) -> None

Change the keys and access bits of the authenticated sector.

The new trailer is checked first: invalid access bits are always refused, and access bits that can never be changed again are refused unless allow_permanent is True. With verify, the sector is then authenticated again with the new key and the access bits are read back.

from mifarepy.access import AccessBits

reader.authenticate_sector(1, bytes.fromhex('FFFFFFFFFFFF'))
reader.write_trailer(new_a, new_b, AccessBits.build(data='write-b', trailer='key-b'))
Note

Keep the new keys somewhere safe before calling this. A sector whose keys are lost cannot be opened again.

Parameters:

Name Type Description Default
key_a Union[bytes, str]

New Key A (6 bytes or 12 hex digits).

required
key_b Union[bytes, str]

New Key B.

required
access Union[AccessBits, bytes, None]

New access bits (AccessBits or 4 bytes). Default: keep the current ones (read from the card).

None
sector Optional[int]

The sector, which must be the one authenticated last (default: that one).

None
allow_permanent bool

Allow access bits that can never be changed.

False
verify bool

Re-authenticate with the new key and check the access bits.

True

Raises:

Type Description
UnsafeTrailerError

If the trailer would lock the sector.

ValueError

If no sector (or a different one) is authenticated, or a key is malformed.

AccessDeniedError

If the key in use may not change this trailer.

CardWriteError

If verification fails.

GNetPlusError

For other reader errors.

open_sector

open_sector(sector: int, keys: Union[KeyRing, list[bytes], tuple[bytes, ...], bytes, None] = None, key_type: Optional[str] = None) -> tuple[str, bytes]

Authenticate sector with the first key that works.

ring = KeyRing.load('keys.dic')
key_type, key = reader.open_sector(4, ring)

Parameters:

Name Type Description Default
sector int

Sector to open.

required
keys Union[KeyRing, list[bytes], tuple[bytes, ...], bytes, None]

A KeyRing, a list of keys, or one key (default: FFFFFFFFFFFF).

None
key_type Optional[str]

Only try 'A' or 'B' (default: Key A, then Key B).

None

Returns:

Type Description
tuple[str, bytes]

(key_type, key) that opened the sector.

Raises:

Type Description
AuthenticationError

If no key opened it (the error of the last attempt).

NoCardError

If there is no card.

store_keys

store_keys(keys: KeyRing, sectors: Optional[Union[int, list[int]]] = None) -> None

Save known keys in the reader, for authenticate_sector_cached().

For each sector, the sector's known Key A and Key B from keys are saved (SAVE_KEY); sectors without known keys get the ring's first general key, if any.

Parameters:

Name Type Description Default
keys KeyRing

The keys to store.

required
sectors Optional[Union[int, list[int]]]

Sectors to store keys for: a list, a count (16 for 1K, 40 for 4K), or None for 16.

None

read_value

read_value(block: int) -> int

Read a signed 32-bit value from a MIFARE value block.

Parameters:

Name Type Description Default
block int

Block index relative to the authenticated sector (0-2).

required

Returns:

Type Description
int

Signed 32-bit integer stored in the value block.

Raises:

Type Description
GNetPlusError

If the read fails.

write_value

write_value(block: int, value: int) -> None

Write a signed 32-bit value to a MIFARE value block.

Delegates to CREATE_VALUE_BLOCK (0x28) which both creates and updates value blocks and is universally supported across all GNetPlus firmware versions.

Parameters:

Name Type Description Default
block int

Block index relative to the authenticated sector (0-2).

required
value int

Signed 32-bit integer to store.

required

Raises:

Type Description
ValueError

If value is outside signed 32-bit range.

GNetPlusError

If the write fails.

create_value_block

create_value_block(block: int, initial_value: int = 0) -> None

Initialize a block as a MIFARE value block with the GNetPlus redundant format (value stored three times: twice normal, once inverted).

Must authenticate the sector before calling.

Parameters:

Name Type Description Default
block int

Block index relative to the authenticated sector (0-2).

required
initial_value int

Signed 32-bit starting value (default: 0).

0

Raises:

Type Description
ValueError

If initial_value is outside signed 32-bit range.

GNetPlusError

If the operation fails.

increment_value

increment_value(block: int, delta: int) -> None

Add delta to a MIFARE value block.

Reads the current value and writes the new one (read-modify-write). With value_ops='native' the reader's SET_VALUE command (increment + transfer) is sent instead and the result is read back to confirm it; a NAK or a wrong result raises GNetPlusError.

Parameters:

Name Type Description Default
block int

Block index relative to the authenticated sector.

required
delta int

Positive integer amount to add.

required

Raises:

Type Description
ValueError

If delta ≤ 0 or if the result overflows int32.

GNetPlusError

If the reader returns a NAK.

decrement_value

decrement_value(block: int, delta: int) -> None

Subtract delta from a MIFARE value block.

Reads the current value and writes the new one (read-modify-write), so the block's access conditions must allow writing. With value_ops='native' the reader's SET_VALUE command (decrement + transfer) is sent instead, which also works on decrement-only blocks (for example prepaid balances) if your reader's firmware computes it correctly; see increment_value().

Parameters:

Name Type Description Default
block int

Block index relative to the authenticated sector.

required
delta int

Positive integer amount to subtract.

required

Raises:

Type Description
ValueError

If delta ≤ 0 or if the result underflows int32.

GNetPlusError

If the reader returns a NAK.

transfer

transfer(source_block: int, dest_block: int) -> None

Copy the value in source_block to dest_block.

Uses the card's RESTORE (load source into the transfer buffer) and TRANSFER (write buffer to destination) commands, then verifies the destination. Both blocks must be value blocks in the authenticated sector.

Parameters:

Name Type Description Default
source_block int

Value block to copy from.

required
dest_block int

Value block to copy to.

required

Raises:

Type Description
GNetPlusError

If either block cannot be read or written.

restore

restore(block: int) -> None

Re-commit a value block: RESTORE it into the transfer buffer and TRANSFER it back, rewriting the block in valid value format.

Useful to repair a value block after an interrupted operation, as long as its value can still be read.

Parameters:

Name Type Description Default
block int

Value block relative to the authenticated sector.

required

Raises:

Type Description
GNetPlusError

If the reader returns a NAK.

read_sector

read_sector(sector: Optional[int] = None, raw: bool = False, combine: bool = False) -> Union[dict[int, Union[str, bytes]], Union[str, bytes]]

Read every data block of the authenticated sector (the trailer is skipped).

That is blocks 0-2 for sectors 0-31, and blocks 0-14 for the large sectors 32-39 of a MIFARE Classic 4K card.

Authenticate the sector with authenticate_sector before calling this.

Parameters:

Name Type Description Default
sector Optional[int]

Sector whose layout to use. Defaults to the sector most recently authenticated on this reader (or a 4-block sector if none has been). It does not authenticate for you.

None
raw bool

If True returns bytes; otherwise hex strings.

False
combine bool

If True concatenates all data blocks into a single value.

False

Returns:

Type Description
Union[dict[int, Union[str, bytes]], Union[str, bytes]]

Dict mapping relative block index to data, or the combined value.

Raises:

Type Description
GNetPlusError

If any block read fails.

write_sector

write_sector(data: Union[str, bytes, dict[int, Union[str, bytes]]], sector: Optional[int] = None) -> None

Write data blocks of the authenticated sector. The trailer is never written.

Supported data shapes (n = number of data blocks: 3, or 15 for 4K sectors 32-39): - 16 bytes / 32-char hex -- the same blob written to every data block. - 16 × k bytes (k ≤ n) -- split into 16-byte chunks for blocks 0 … k-1. - dict mapping data-block indices to 16-byte blobs or hex strings.

Parameters:

Name Type Description Default
data Union[str, bytes, dict[int, Union[str, bytes]]]

The data to write, in one of the shapes above.

required
sector Optional[int]

Sector whose layout to use. Defaults to the most recently authenticated sector.

None

Raises:

Type Description
ValueError

If data is an invalid size or a dict key is not a data block.

GNetPlusError

If any write fails.

write_sector_uniform

write_sector_uniform(data: Union[str, bytes], sector: Optional[int] = None) -> None

Write the same 16 bytes to every data block of the authenticated sector.

This is an explicit, intent-revealing alias for the 16-byte dispatch path of write_sector(). Use it when you deliberately want every data block in the sector to hold identical content (e.g. bulk wipe / factory-reset workflows).

Parameters:

Name Type Description Default
data Union[str, bytes]

Exactly 16 bytes or a 32-character hex string.

required
sector Optional[int]

Sector whose layout to use. Defaults to the most recently authenticated sector.

None

Raises:

Type Description
ValueError

If data is not exactly 16 bytes.

GNetPlusError

If any block write fails.

read_blocks

read_blocks(mapping: dict[int, list[int]], raw: bool = False, combine: bool = False, keys: Optional[Union[bytes, dict[int, bytes]]] = None, key_types: Union[str, dict[int, str]] = 'A', timeout: Union[float, dict[int, float]] = 1.0, flush: Union[bool, dict[int, bool]] = True, auth: Optional[dict[int, SectorAuth]] = None) -> Union[dict[int, dict[int, Union[str, bytes]]], Union[str, bytes]]

Read multiple blocks across sectors with optional per-sector authentication.

Authentication can be supplied two ways (mutually exclusive; auth takes precedence when both are given):

New style — auth dict of SectorAuth:

results = reader.read_blocks(
    {1: [0, 1], 2: [0]},
    auth={
        1: SectorAuth(key=bytes.fromhex('FFFFFFFFFFFF')),
        2: SectorAuth(key=bytes.fromhex('A0A1A2A3A4A5'), key_type='B'),
    },
)

Legacy style — keys + key_types + timeout + flush (still fully supported).

Parameters:

Name Type Description Default
mapping dict[int, list[int]]

{sector: [block, ...]} blocks to read per sector.

required
raw bool

True → bytes; False → hex strings.

False
combine bool

True → concatenate all results into one value.

False
keys Optional[Union[bytes, dict[int, bytes]]]

Global 6-byte key or {sector: key} per-sector.

None
key_types Union[str, dict[int, str]]

'A'/'B' globally or per-sector dict.

'A'
timeout Union[float, dict[int, float]]

Auth timeout globally or per-sector dict.

1.0
flush Union[bool, dict[int, bool]]

Buffer-flush flag globally or per-sector dict.

True
auth Optional[dict[int, SectorAuth]]

{sector: SectorAuth} — new-style per-sector auth.

None

Returns:

Type Description
Union[dict[int, dict[int, Union[str, bytes]]], Union[str, bytes]]

{sector: {block: data}} or combined bytes/hex string.

Raises:

Type Description
GNetPlusError

If authentication or any block read fails.

write_blocks

write_blocks(mapping: dict[int, Union[bytes, str, dict[int, Union[str, bytes]]]], keys: Optional[Union[bytes, dict[int, bytes]]] = None, key_types: Union[str, dict[int, str]] = 'A', timeout: Union[float, dict[int, float]] = 1.0, flush: Union[bool, dict[int, bool]] = True, auth: Optional[dict[int, SectorAuth]] = None) -> None

Write multiple blocks across sectors with optional per-sector authentication.

Authentication can be supplied two ways (mutually exclusive; auth takes precedence when both are given):

New style — auth dict of SectorAuth:

reader.write_blocks(
    {1: b'' * 48, 2: {0: b'ª' * 16}},
    auth={
        1: SectorAuth(key=bytes.fromhex('FFFFFFFFFFFF')),
        2: SectorAuth(key=bytes.fromhex('A0A1A2A3A4A5'), key_type='B'),
    },
)

Legacy style — keys + key_types + timeout + flush (still fully supported).

Parameters:

Name Type Description Default
mapping dict[int, Union[bytes, str, dict[int, Union[str, bytes]]]]

{sector: blob_or_dict} data to write per sector.

required
keys Optional[Union[bytes, dict[int, bytes]]]

Global 6-byte key or {sector: key} per-sector.

None
key_types Union[str, dict[int, str]]

'A'/'B' globally or per-sector dict.

'A'
timeout Union[float, dict[int, float]]

Auth timeout globally or per-sector dict.

1.0
flush Union[bool, dict[int, bool]]

Buffer-flush flag globally or per-sector dict.

True
auth Optional[dict[int, SectorAuth]]

{sector: SectorAuth} — new-style per-sector auth.

None

Raises:

Type Description
ValueError

If any block data is not exactly 16 bytes.

GNetPlusError

If authentication or any block write fails.

Data types

CardEvent dataclass

CardEvent(kind: EventKind, uid: Optional[str], time: datetime)

Something that happened at the reader, from MifareReader.card_events() / cards().

Attributes:

Name Type Description
kind EventKind

'arrived' (a card was placed), 'removed' (it was taken away), 'disconnected' (the reader stopped answering, e.g. the USB cable was pulled) or 'reconnected' (it is back).

uid Optional[str]

The card UID for arrived / removed, else None.

time datetime

When the event was seen.

SectorAuth dataclass

SectorAuth(key: bytes, key_type: Literal['A', 'B'] = 'A', timeout: float = 1.0, flush: bool = True)

Per-sector authentication configuration for read_blocks() and write_blocks().

Pass a dict[sector, SectorAuth] to the auth keyword argument of those methods to supply per-sector keys in a discoverable, IDE-friendly way instead of the legacy keys= / key_types= dict juggling.

Attributes:

Name Type Description
key bytes

6-byte MIFARE authentication key.

key_type Literal['A', 'B']

'A' (default) or 'B'.

timeout float

Per-sector auth timeout in seconds (default 1.0).

flush bool

Flush the serial input buffer before reading (default True).

Usage example:

from mifarepy import SectorAuth

reader.read_blocks(
    {1: [0, 1], 2: [0]},
    auth={
        1: SectorAuth(key=bytes.fromhex('FFFFFFFFFFFF')),
        2: SectorAuth(key=bytes.fromhex('A0A1A2A3A4A5'), key_type='B'),
    },
)

CardInfo dataclass

CardInfo(uid: str, uid_int: int, uid_bytes: bytes)

Information about a card detected and selected in the RF field.

Returned by scan_tag(). Provides the UID in multiple representations so callers can use whatever is most convenient without extra conversion.

Attributes:

Name Type Description
uid str

UID formatted as '0xAABBCCDD' (always uppercase, zero-padded).

uid_int int

Unsigned 32-bit integer.

uid_bytes bytes

Raw 4-byte response from ANTI_COLLISION (little-endian byte order).

Usage example:

card = reader.scan_tag()
print(card)                  # '0xEDCEF8C3'
print(card.uid_int)          # 3989956803
print(card.uid_bytes.hex())  # 'c3f8ceed'

Access bits

See Keys and access bits for a guide.

AccessBits dataclass

AccessBits(data: tuple[str, str, str] = ('000', '000', '000'), trailer: str = '001', gpb: int = 105)

Decoded access conditions of one sector.

Attributes:

Name Type Description
data tuple[str, str, str]

Conditions of the three data-block groups, as bit strings (C1 C2 C3). On 1K cards and the small sectors of 4K cards each group is one block; in 4K sectors 32-39 each group covers five blocks (0-4, 5-9, 10-14).

trailer str

Condition of the sector trailer.

gpb int

The general-purpose byte (byte 9 of the trailer). The card does not use it.

is_permanent property

is_permanent: bool

True if these access bits can never be changed once written.

key_b_readable property

key_b_readable: bool

True if Key B can be read, which also means it gives no access.

build classmethod

build(data: Union[str, int, Sequence[Union[str, int]]] = 'open', trailer: Union[str, int] = 'transport', gpb: int = 105) -> AccessBits

Make access conditions from preset names or bit strings.

Parameters:

Name Type Description Default
data Union[str, int, Sequence[Union[str, int]]]

One condition for all data blocks, or a list of three (one per block or block group). Each is a preset name from DATA_PRESETS, a bit string like '110', or an int 0-7.

'open'
trailer Union[str, int]

Trailer condition: a preset name from TRAILER_PRESETS, a bit string or an int 0-7.

'transport'
gpb int

General-purpose byte (0-255).

105

from_bytes classmethod

from_bytes(access: bytes) -> AccessBits

Decode the 4 access bytes (trailer bytes 6-9), or a whole 16-byte trailer.

Raises:

Type Description
UnsafeTrailerError

If the inverted copies of the bits do not match. A card with such a trailer blocks the sector.

to_bytes

to_bytes() -> bytes

Encode as the 4 trailer bytes 6-9 (access bits and general-purpose byte).

data_rights

data_rights(group: int) -> dict[str, str]

Who may read, write, increment and decrement data group group (0-2).

Values are 'A', 'B', 'A or B' or 'never'. Key B counts as 'never' when it is readable.

trailer_rights

trailer_rights() -> dict[str, str]

Who may change Key A, read and change the access bits, and read and change Key B.

allows

allows(operation: str, key_type: str, group: Optional[int] = None) -> bool

Whether key_type ('A' or 'B') may do operation.

Parameters:

Name Type Description Default
operation str

One of read, write, increment, decrement (with group), or one of the trailer operations write_key_a, read_access, write_access, read_key_b, write_key_b (without group).

required
key_type str

'A' or 'B'.

required
group Optional[int]

Data-block group 0-2 for data operations.

None

describe

describe(blocks_per_group: int = 1) -> str

Explain the conditions in plain language, one line per block group.

Parameters:

Name Type Description Default
blocks_per_group int

1 for 1K cards and 4K sectors 0-31; 5 for 4K sectors 32-39.

1

build_trailer

build_trailer(key_a: bytes, key_b: bytes, data: Union[str, int, Sequence[Union[str, int]]] = 'open', trailer: Union[str, int] = 'transport', gpb: int = 105, *, allow_permanent: bool = False) -> bytes

Build a 16-byte sector trailer: Key A, access bits, general-purpose byte, Key B.

# Key A can read, Key B can write and manage the sector:
trailer = build_trailer(key_a, key_b, data='write-b', trailer='key-b')

Parameters:

Name Type Description Default
key_a bytes

6-byte Key A.

required
key_b bytes

6-byte Key B.

required
data Union[str, int, Sequence[Union[str, int]]]

Data-block condition(s): see AccessBits.build().

'open'
trailer Union[str, int]

Trailer condition: see AccessBits.build().

'transport'
gpb int

General-purpose byte.

105
allow_permanent bool

Allow trailer conditions after which the access bits can never be changed.

False

Raises:

Type Description
ValueError

For wrong key lengths or unknown conditions.

UnsafeTrailerError

For permanent conditions without allow_permanent.

decode_trailer

decode_trailer(trailer: bytes) -> AccessBits

Decode a 16-byte trailer as read from the card (or its 4 access bytes).

check_trailer

check_trailer(trailer: bytes, *, allow_permanent: bool = False) -> AccessBits

Check a 16-byte trailer (or 4 access bytes) before it is written.

Returns:

Type Description
AccessBits

The decoded AccessBits.

Raises:

Type Description
UnsafeTrailerError

If the access bits are invalid (always), or can never be changed again and allow_permanent is False.

UnsafeTrailerError

Bases: ValueError

A sector trailer that would lock the sector, now or for good.

Raised for access bits whose inverted copies do not match (the card would block the whole sector permanently), and for trailer conditions after which the access bits can never be changed, unless allow_permanent=True was passed.

Keys

KeyRing

KeyRing(keys: Optional[Iterable[KeyLike]] = None, sectors: Optional[dict[int, dict[str, KeyLike]]] = None)

Keys to try when opening sectors.

Parameters:

Name Type Description Default
keys Optional[Iterable[KeyLike]]

Keys to try on every sector, in order. Defaults to the factory key FFFFFFFFFFFF. Pass [] for none.

None
sectors Optional[dict[int, dict[str, KeyLike]]]

Known keys per sector, as {sector: {'A': key, 'B': key}}. These are tried first for their sector.

None

add

add(key: KeyLike) -> None

Add a key to try on every sector (duplicates are ignored).

set

set(sector: int, key_a: Optional[KeyLike] = None, key_b: Optional[KeyLike] = None) -> None

Record the known Key A and/or Key B of sector.

get

get(sector: int, key_type: str = 'A') -> Optional[bytes]

The known key of key_type for sector, or None.

candidates

candidates(sector: int, key_type: Optional[str] = None) -> list[tuple[str, bytes]]

(key_type, key) pairs to try on sector, most likely first.

Known keys for the sector come first, then every general key as Key A and then as Key B (or only key_type if given).

merge

merge(other: KeyRing) -> KeyRing

Return a new ring with the keys of both (this ring's sector keys win).

load classmethod

load(path: Union[str, PathLike[str]]) -> KeyRing

Load a key list (one hex key per line) or a JSON key file.

Raises:

Type Description
ValueError

If a line or entry is not a valid key.

OSError

If the file cannot be read.

from_json classmethod

from_json(text: str) -> KeyRing

Parse the JSON key-file format.

to_json

to_json() -> str

Serialise in the JSON key-file format.

save

save(path: Union[str, PathLike[str]]) -> None

Save as JSON (.json) or as a key list (any other name; sector keys are added to the list).

diversify_key

diversify_key(master: bytes, uid: Union[str, bytes, int], sector: int = 0, key_type: str = 'A') -> bytes

Derive a 6-byte key for one card and sector from a master secret.

The key is the first 6 bytes of HMAC-SHA256(master, label + UID + sector + key type). Every card gets different keys, so reading the keys out of one card does not open the others. Keep the master secret off the cards and out of your source code.

This is a mifarepy pattern, not a standard: it is not NXP's AN10922 diversification, and other tools will not derive the same keys.

master = bytes.fromhex(os.environ['MIFARE_MASTER_KEY'])   # 16+ random bytes
uid = reader.get_uid()
key_a = diversify_key(master, uid, sector=1, key_type='A')
key_b = diversify_key(master, uid, sector=1, key_type='B')

Parameters:

Name Type Description Default
master bytes

Master secret, at least 16 bytes (os.urandom(16) makes one).

required
uid Union[str, bytes, int]

The card UID: a '0xAABBCCDD' string from MifareReader.get_uid(), an int from get_uid_int(), or the UID bytes in card order.

required
sector int

Sector number, so every sector gets its own key.

0
key_type str

'A' or 'B'.

'A'

Raises:

Type Description
ValueError

If the master secret is shorter than 16 bytes, or the other arguments are invalid.

parse_key

parse_key(key: KeyLike) -> bytes

Return key as 6 bytes. Accepts bytes or 12 hex digits (spaces and colons ignored).

Raises:

Type Description
ValueError

If the key is not 6 bytes / 12 hex digits.

Card schemas

See Building applications.

CardSchema

CardSchema(*fields: Field)

A set of Fields that describes the data on your cards.

Parameters:

Name Type Description Default
*fields Field

The fields. Names must be unique and fields may not overlap.

()

Raises:

Type Description
SchemaError

If a field is invalid, a name is repeated, or two fields overlap.

blocks property

blocks: list[tuple[int, int]]

(sector, block) pairs the schema uses, in order.

sectors property

sectors: list[int]

Sectors the schema uses, in order.

decode

decode(blocks: dict[tuple[int, int], bytes]) -> dict[str, Any]

Decode field values from {(sector, block): 16 bytes}.

encode

encode(values: dict[str, Any], base: Optional[dict[tuple[int, int], bytes]] = None) -> dict[tuple[int, int], bytes]

Encode values into the blocks they touch.

Parameters:

Name Type Description Default
values dict[str, Any]

{field name: value}; fields not given keep the bytes in base.

required
base Optional[dict[tuple[int, int], bytes]]

Current contents of the blocks (default: zeros).

None

Returns:

Type Description
dict[tuple[int, int], bytes]

{(sector, block): 16 bytes} for every block a given field is in.

Raises:

Type Description
SchemaError

For unknown field names or values that don't fit.

read

read(reader: MifareReader, keys: Keys = None) -> dict[str, Any]

Read every field from the card on reader.

Parameters:

Name Type Description Default
reader MifareReader

An open reader with the card in its field.

required
keys Keys

Keys to open the sectors: a KeyRing, a list, or one key (default FFFFFFFFFFFF).

None

write

write(reader: MifareReader, values: dict[str, Any], keys: Keys = None, verify: bool = True) -> None

Write the given fields to the card; other bytes in their blocks are kept.

Each block is read, patched and written, then read back when verify is True.

Raises:

Type Description
SchemaError

For unknown fields or values that don't fit (before anything is written).

CardWriteError

If a block reads back differently.

Field dataclass

Field(name: str, sector: int, block: int, offset: int = 0, type: FieldType = 'bytes', length: Optional[int] = None, encoding: str = 'utf-8', byteorder: Literal['little', 'big'] = 'little')

One named value stored on the card.

Parameters:

Name Type Description Default
name str

The name you read and write it by.

required
sector int

Sector that holds it.

required
block int

Data block, relative to the sector.

required
offset int

First byte inside the block (0-15).

0
type FieldType

One of the types in the module docs.

'bytes'
length Optional[int]

Size in bytes, for str and bytes (1-16).

None
encoding str

Text encoding for str.

'utf-8'
byteorder Literal['little', 'big']

'little' (default) or 'big' for integers.

'little'

size property

size: int

Number of bytes the field takes.

encode

encode(value: Any) -> bytes

Turn value into the field's bytes.

Raises:

Type Description
SchemaError

If the value has the wrong type or does not fit.

decode

decode(raw: bytes) -> Any

Turn the field's bytes back into a Python value.

SchemaError

Bases: ValueError

A schema or a value that does not fit it.

Wallet

See Building applications.

Wallet

Wallet(reader: MifareReader, sector: int, block: int = 0, backup_block: int = 1, keys: Union[KeyRing, list[bytes], bytes, None] = None, max_balance: int = MAX_BALANCE)

A balance stored on the card with a backup copy.

Parameters:

Name Type Description Default
reader MifareReader

An open reader.

required
sector int

Sector that holds the wallet.

required
block int

Data block for the main copy (relative to the sector).

0
backup_block int

Data block for the backup copy.

1
keys Union[KeyRing, list[bytes], bytes, None]

Keys to open the sector: a KeyRing, a list, or one key (default FFFFFFFFFFFF). The key used needs the write right.

None
max_balance int

Refuse top-ups above this.

MAX_BALANCE

Attributes:

Name Type Description
last_recovery Optional[Recovery]

What the most recent read repaired (a Recovery), or None.

create

create(balance: int = 0) -> None

Set up the wallet on a card, overwriting both blocks.

balance

balance() -> int

Read the balance, repairing a copy a pulled-away card left behind.

Raises:

Type Description
WalletError

If neither copy is a valid value block.

top_up

top_up(amount: int) -> int

Add amount and return the new balance.

Raises:

Type Description
ValueError

If amount is not positive or the result would exceed max_balance.

spend

spend(amount: int) -> int

Subtract amount and return the new balance.

Raises:

Type Description
ValueError

If amount is not positive.

InsufficientFundsError

If the balance is lower than amount (nothing is written).

InsufficientFundsError

InsufficientFundsError(balance: int, amount: int)

Bases: ValueError

Wallet.spend() was asked for more than the balance.

WalletError

WalletError(message: str, raw: bytes = b'', hint: Optional[str] = None)

Bases: GNetPlusError

Neither copy of the balance could be read as a valid value block.

encode_value_block

encode_value_block(value: int, address: int = 0) -> bytes

Encode a MIFARE value block: the value three times (once inverted) and an address byte four times.

Parameters:

Name Type Description Default
value int

Signed 32-bit value.

required
address int

The address byte (0-255). The card does not use it; the wallet stores its change counter there.

0

decode_value_block

decode_value_block(data: bytes) -> Optional[tuple[int, int]]

Decode a value block as (value, address), or None if data is not a valid one.

Card layout

layout

MIFARE Classic memory-layout helpers.

MIFARE Classic 1K has 16 sectors of 4 blocks. MIFARE Classic 4K has 40 sectors: 0-31 have 4 blocks each, 32-39 have 16 blocks each. The last block of every sector is its sector trailer (keys + access bits).

Block numbers passed to MifareReader.read_block() / write_block() are relative to the authenticated sector; these helpers translate between relative and absolute numbering and tell you which blocks hold data.

from mifarepy import layout

layout.blocks_in_sector(5)      # 4
layout.blocks_in_sector(35)     # 16
layout.data_blocks(35)          # range(0, 15)
layout.trailer_block(35)        # 15  (relative)
layout.absolute_block(35, 0)    # 176
layout.sector_of(176)           # (35, 0)

blocks_in_sector

blocks_in_sector(sector: int) -> int

Return how many blocks sector has (4, or 16 for 4K sectors 32-39).

trailer_block

trailer_block(sector: int) -> int

Return the relative block number of sector's trailer (3 or 15).

data_blocks

data_blocks(sector: int) -> range

Return the relative block numbers that hold data (excludes the trailer).

absolute_block

absolute_block(sector: int, block: int) -> int

Convert a relative block within sector to an absolute block number.

sector_of

sector_of(absolute: int) -> tuple[int, int]

Convert an absolute block number to (sector, relative_block).

is_trailer

is_trailer(sector: int, block: int) -> bool

Return True if relative block is the trailer of sector.

Errors

Reader NAKs raise a subclass of GNetPlusError; see error handling for which code raises which.

GNetPlusError

GNetPlusError(message: str, raw: bytes = b'', hint: Optional[str] = None)

Bases: Exception

Exception thrown when receiving a NAK (negative acknowledge) response.

NAKs raised by MifareReader use the more specific subclasses below (AuthenticationError, NoCardError, ...), so you can catch exactly the failure you care about. Catching GNetPlusError still catches them all.

Attributes:

Name Type Description
raw

Raw NAK payload bytes from the reader.

code_description str

Human-readable description of the NAK code if known.

nak_code int

Integer NAK code (raw[0]), or 0 when raw is not a single byte.

hint str

A short suggestion for fixing the problem, or ''.

NoCardError

NoCardError(message: str, raw: bytes = b'', hint: Optional[str] = None)

Bases: GNetPlusError

No card answered (NAK 0x1F no tag, or 0x03 empty).

The reader also returns 0x1F for block commands after a failed authentication, because the card drops back to its idle state.

AuthenticationError

AuthenticationError(message: str, raw: bytes = b'', hint: Optional[str] = None)

Bases: GNetPlusError

The card rejected the key.

PCR310U readers (firmware PGM0487) return NAK 0x09 for a wrong key; other GNetPlus readers may return 0x04. Both raise this class.

NotAuthenticatedError

NotAuthenticatedError(message: str, raw: bytes = b'', hint: Optional[str] = None)

Bases: GNetPlusError

A block was accessed without authenticating its sector.

PCR310U readers (firmware PGM0487) return NAK 0x0C for reads and 0x0A for writes.

AccessDeniedError

AccessDeniedError(message: str, raw: bytes = b'', hint: Optional[str] = None)

Bases: NotAuthenticatedError

The sector's access bits do not let the authenticated key do this.

A PCR310U (firmware PGM0487) answers a refused read with NAK 0x0C and a refused write with 0x0A, the same codes it uses when no sector is authenticated. MifareReader raises this subclass instead when a sector was authenticated, so except NotAuthenticatedError still catches it.

The card goes idle after a refused command: authenticate again before the next one.

CardReadError

CardReadError(message: str, raw: bytes = b'', hint: Optional[str] = None)

Bases: GNetPlusError

The card refused or failed a read (NAK 0x12).

CardWriteError

CardWriteError(message: str, raw: bytes = b'', hint: Optional[str] = None)

Bases: GNetPlusError

The card refused or failed a write (NAK 0x0F).

ValueBlockError

ValueBlockError(message: str, raw: bytes = b'', hint: Optional[str] = None)

Bases: GNetPlusError

A value-block operation failed (NAK 0x0E transfer, 0x10 increment, 0x11 decrement).

A PCR310U (firmware PGM0487) answers SET_VALUE with 0x06 when the access bits refuse it or the arithmetic fails.

CardTimeoutError

CardTimeoutError(message: str, raw: bytes = b'', hint: Optional[str] = None)

Bases: GNetPlusError

The card did not answer in time (NAK 0x1C), or stopped mid-command.

A PCR310U (firmware PGM0487) can answer 0x05 when the card leaves the field during a command.

ReaderProtocolError

ReaderProtocolError(message: str, raw: bytes = b'', hint: Optional[str] = None)

Bases: GNetPlusError

The reader rejected the frame or command itself (NAK 0x0B, 0x27, 0xE0–0xE6).

ReaderAccessError

ReaderAccessError(message: str, raw: bytes = b'', hint: Optional[str] = None)

Bases: GNetPlusError

The reader requires a logon or host key (NAK 0x2D, 0x2F, 0x33).

ReaderConnectionError

ReaderConnectionError(port: str, reason: str, hint: str = '')

Bases: RuntimeError

The serial port could not be opened.

Subclass of RuntimeError, which is what earlier versions raised.

Attributes:

Name Type Description
port

The port that failed to open.

hint

A short suggestion for fixing the problem.

ReaderNotFoundError

ReaderNotFoundError(message: str, ports: Optional[list[tuple[str, str]]] = None)

Bases: RuntimeError

MifareReader.auto() could not find a reader.

Attributes:

Name Type Description
ports

The serial ports that were seen, as (device, description) pairs.

error_for_nak

error_for_nak(raw: bytes, context: str = '') -> GNetPlusError

Build the most specific GNetPlusError subclass for a NAK payload.

Parameters:

Name Type Description Default
raw bytes

The NAK data bytes (normally a single error code).

required
context str

Optional text describing what was being done, e.g. 'sector 3, key A'.

''

Returns:

Type Description
GNetPlusError

An exception instance (not raised).

InvalidMessage

InvalidMessage(message: str, raw_bytes: bytes = b'')

Bases: Exception

Raised when an invalid message is received from the RFID reader.

Attributes:

Name Type Description
raw_bytes

The partial bytes that were read from the serial port before the error occurred. Useful for low-level debugging.

Dumps

See Command line for the dump and restore commands built on these.

CardDump dataclass

CardDump(uid: str, size: str, blocks: list[Optional[bytes]], keys: dict[int, tuple[Optional[bytes], Optional[bytes]]] = dict())

The contents of a MIFARE Classic card.

Attributes:

Name Type Description
uid str

UID as '0xAABBCCDD' (as MifareReader.get_uid() returns it).

size str

'1K' or '4K'.

blocks list[Optional[bytes]]

One entry per absolute block: 16 bytes, or None if unread.

keys dict[int, tuple[Optional[bytes], Optional[bytes]]]

{sector: (key_a, key_b)} for the keys that are known; either key may be None.

block

block(sector: int, block: int) -> Optional[bytes]

Return relative block of sector, or None if it was not read.

unread_sectors

unread_sectors() -> list[int]

Sectors whose blocks could not be read (no working key).

to_json

to_json() -> str

Serialise to mifarepy's JSON format.

to_bin

to_bin() -> bytes

Raw memory image; unread blocks become zeros.

to_mct

to_mct() -> str

MIFARE Classic Tool text format; unread blocks become dashes.

save

save(path: Union[str, Path]) -> None

Write the dump to path; the format follows the extension.

load classmethod

load(path: Union[str, Path]) -> CardDump

Read a dump saved by save() (or by Proxmark3 / MIFARE Classic Tool).

read_card

read_card(reader: MifareReader, keys: Keys = DEFAULT_KEYS, size: Optional[str] = None, progress: Optional[ProgressCallback] = None) -> CardDump

Read every sector the given keys can open.

When the access bits stop the opening key from reading a block, the other keys are tried for that block.

Parameters:

Name Type Description Default
reader MifareReader

An open reader with the card in its field.

required
keys Keys

Keys to try on each sector, as Key A and then Key B, or a KeyRing with known per-sector keys.

DEFAULT_KEYS
size Optional[str]

'1K' or '4K'; detected from the card when None.

None
progress Optional[ProgressCallback]

Called as progress(sector, total_sectors, key_type_or_None).

None

Returns:

Type Description
CardDump

A CardDump. Sectors no key opened have None blocks; see

CardDump

CardDump.unread_sectors().

write_card

write_card(reader: MifareReader, dump: CardDump, keys: Keys = DEFAULT_KEYS, sectors: Optional[Sequence[int]] = None, progress: Optional[ProgressCallback] = None) -> list[int]

Write the data blocks of dump to the card on the reader.

Sector trailers (keys and access bits) and the manufacturer block are never written, so this cannot lock a sector or change keys. Unread blocks (None) are skipped.

Parameters:

Name Type Description Default
reader MifareReader

An open reader with the target card in its field.

required
dump CardDump

What to write.

required
keys Keys

Keys to try on each sector of the target card (a list or a KeyRing). The keys stored in the dump are tried as well, and if the opening key may not write a block, the other keys are tried.

DEFAULT_KEYS
sectors Optional[Sequence[int]]

Only write these sectors (default: all in the dump).

None
progress Optional[ProgressCallback]

Called as progress(sector, total_sectors, key_type_or_None).

None

Returns:

Type Description
list[int]

The sectors that could not be opened with any key (not written).

Raises:

Type Description
ValueError

A sector in sectors is not in the dump.

GNetPlusError

If no key may write a block of an opened sector.

detect_size

detect_size(reader: MifareReader) -> str

Return '4K' or '1K' for the card on the reader.

Uses the card's answer to REQUEST (ATQA 02 00 is 4K) and SELECT (SAK 0x18 is 4K). Anything else is treated as 1K.

Finding readers

discovery

Find PROMAG / GNetPlus readers on the serial ports of this computer.

from mifarepy.discovery import find_ports

for port in find_ports():
    print(port.device, port.description, 'likely reader' if port.likely_reader else '')

MifareReader.auto() uses this to open the first reader it finds.

PortInfo dataclass

PortInfo(device: str, description: str, vid: Optional[int], pid: Optional[int], likely_reader: bool)

A serial port, and whether it looks like a PROMAG reader.

Attributes:

Name Type Description
device str

Name to pass to MifareReader, e.g. '/dev/ttyUSB0' or 'COM3'.

description str

Description reported by the operating system.

vid Optional[int]

USB vendor ID, or None for non-USB ports.

pid Optional[int]

USB product ID, or None for non-USB ports.

likely_reader bool

True if the USB IDs match a known reader bridge.

find_ports

find_ports(include_all: bool = False) -> list[PortInfo]

List serial ports, likely readers first.

Parameters:

Name Type Description Default
include_all bool

Also return ports that don't look like a reader.

False

Returns:

Type Description
list[PortInfo]

Ports sorted with likely readers first, then by device name.

Simulator

See Testing without hardware for a guide.

SimulatedCard

SimulatedCard(uid: Union[bytes, str] = b'4\xc6\x9b\xd3', size: str = '1K', keys: Optional[dict[int, tuple[bytes, bytes]]] = None)

Memory and state of one MIFARE Classic card.

Parameters:

Name Type Description Default
uid Union[bytes, str]

4-byte UID as bytes (card order) or a '0xAABBCCDD' string as returned by MifareReader.get_uid().

b'4\xc6\x9b\xd3'
size str

'1K' (16 sectors) or '4K' (40 sectors).

'1K'
keys Optional[dict[int, tuple[bytes, bytes]]]

Optional {sector: (key_a, key_b)} to start with non-default keys.

None

uid_str property

uid_str: str

The UID formatted like MifareReader.get_uid(), e.g. '0xD39BC634'.

read

read(sector: int, block: int) -> bytes

Return the 16 bytes of relative block in sector (no authentication).

write

write(sector: int, block: int, data: bytes) -> None

Set relative block in sector directly (no authentication).

set_trailer

set_trailer(sector: int, key_a: bytes = DEFAULT_KEY, key_b: bytes = DEFAULT_KEY, access: Union[bytes, AccessBits] = TRANSPORT_ACCESS) -> None

Set the keys (and optionally access bits: 4 bytes or AccessBits) of sector.

keys

keys(sector: int) -> tuple[bytes, bytes]

Return (key_a, key_b) of sector.

access

access(sector: int) -> Optional[AccessBits]

The access bits of sector, or None if they are invalid (the sector is blocked).

value

value(sector: int, block: int) -> Optional[int]

Decode relative block of sector as a value block, or None if it isn't one.

SimulatedReader

SimulatedReader(card: Optional[SimulatedCard] = None, version: str = 'SIM0001 V1.0 (mifarepy simulator)')

A serial-port stand-in that answers like a GNetPlus MIFARE reader.

Pass it to MifareReader.from_serial(), or use MifareReader.simulated() which creates one for you. Thread-safe: you can place_card() from another thread while wait_for_card() is waiting.

Parameters:

Name Type Description Default
card Optional[SimulatedCard]

Card to start with in the field, or None for an empty reader.

None
version str

Version string returned by GET_VERSION.

'SIM0001 V1.0 (mifarepy simulator)'

Attributes:

Name Type Description
card

The card currently in the field (None if none).

auto_mode

Whether the reader sends card-arrival events.

queries list[QueryMessage]

Every query frame received, as QueryMessage objects, for assertions.

place_card

place_card(card: SimulatedCard) -> None

Put card in the field (replacing any other). Sends an event in auto mode.

remove_card

remove_card() -> None

Take the card out of the field.

tear_next_write

tear_next_write(keep: int = 8) -> None

Make the next block write stop part-way, as if the card was pulled away mid-write.

The first keep bytes of the new data are written, the rest of the block keeps its old bytes, the card leaves the field, and the reader answers "no tag". Use it to test that your application recovers.

unplug

unplug() -> None

Act as if the USB cable was pulled: every read and write raises serial.SerialException.

replug

replug() -> None

Plug the reader back in. Like a real port, it must be opened again (open()).

open

open() -> None

Open the port again after replug() (serial.Serial.open()).

Frame tracing

enable_wire_trace

enable_wire_trace(stream: Optional[IO[str]] = None, show_keys: bool = False) -> Handler

Print every frame to stream (default: stderr).

Parameters:

Name Type Description Default
stream Optional[IO[str]]

Where to write the trace.

None
show_keys bool

Also print key bytes instead of **. Only use this on test cards: the output then contains secrets.

False

Returns:

Type Description
Handler

The handler that was added; pass it to disable_wire_trace() to stop.

disable_wire_trace

disable_wire_trace(handler: Optional[Handler] = None) -> None

Stop tracing that was started with enable_wire_trace().

format_frame

format_frame(direction: str, frame: bytes) -> str

Return a one-line, human-readable description of a raw frame.

Parameters:

Name Type Description Default
direction str

'TX' (host to reader) or 'RX' (reader to host).

required
frame bytes

The complete frame bytes, starting with SOH.

required

Low-level protocol

These classes build and parse GNetPlus frames. You only need them to send commands that MifareReader does not wrap. See the protocol reference.

Message

Message(address: int, function: int, data: Union[bytes, str])

Base class representing a message for the RFID reader.

Initialize a message.

Parameters:

Name Type Description Default
address int

8-bit device address (use 0 unless specified).

required
function int

8-bit function code representing the message type.

required
data Union[bytes, str]

Message payload (bytes or string).

required

sendto

sendto(serial_port: Serial) -> None

Sends this message to the provided serial port.

Parameters:

Name Type Description Default
serial_port Serial

Serial port to send the message.

required

readfrom classmethod

readfrom(serial_port: Serial) -> _MessageT

Reads a message from the serial port and constructs a Message instance.

Parameters:

Name Type Description Default
serial_port Serial

Serial interface to read from.

required

Returns:

Type Description
_MessageT

Constructed Message instance.

Raises:

Type Description
InvalidMessage

If message is incomplete or invalid.

QueryMessage

QueryMessage(address: int, function: int, data: Union[bytes, str])

Bases: Message

A query message sent from the host to the reader.

Function codes follow the GNetPlus common command table (0x00-0x1F) and the MIFARE application command table (0x20-0x3F).

POLLING class-attribute instance-attribute

POLLING = 0

GET_VERSION class-attribute instance-attribute

GET_VERSION = 1

SET_SLAVE_ADDR class-attribute instance-attribute

SET_SLAVE_ADDR = 2

LOGON class-attribute instance-attribute

LOGON = 3

LOGOFF class-attribute instance-attribute

LOGOFF = 4

SET_PASSWORD class-attribute instance-attribute

SET_PASSWORD = 5

CLASSNAME class-attribute instance-attribute

CLASSNAME = 6

SET_DATETIME class-attribute instance-attribute

SET_DATETIME = 7

GET_DATETIME class-attribute instance-attribute

GET_DATETIME = 8

GET_REGISTER class-attribute instance-attribute

GET_REGISTER = 9

SET_REGISTER class-attribute instance-attribute

SET_REGISTER = 10

RECORD_COUNT class-attribute instance-attribute

RECORD_COUNT = 11

GET_FIRST_RECORD class-attribute instance-attribute

GET_FIRST_RECORD = 12

GET_NEXT_RECORD class-attribute instance-attribute

GET_NEXT_RECORD = 13

ERASE_ALL_RECORDS class-attribute instance-attribute

ERASE_ALL_RECORDS = 14

ADD_RECORD class-attribute instance-attribute

ADD_RECORD = 15

RECOVER_ALL_RECORDS class-attribute instance-attribute

RECOVER_ALL_RECORDS = 16

DO class-attribute instance-attribute

DO = 17

DI class-attribute instance-attribute

DI = 18

ANALOG_INPUT class-attribute instance-attribute

ANALOG_INPUT = 19

THERMOMETER class-attribute instance-attribute

THERMOMETER = 20

GET_NODE class-attribute instance-attribute

GET_NODE = 21

GET_SN class-attribute instance-attribute

GET_SN = 22

SILENT_MODE class-attribute instance-attribute

SILENT_MODE = 23

RESERVE class-attribute instance-attribute

RESERVE = 24

ENABLE_AUTO_MODE class-attribute instance-attribute

ENABLE_AUTO_MODE = 25

GET_TIME_ADJUST class-attribute instance-attribute

GET_TIME_ADJUST = 26

ECHO class-attribute instance-attribute

ECHO = 27

SET_TIME_ADJUST class-attribute instance-attribute

SET_TIME_ADJUST = 28

DEBUG class-attribute instance-attribute

DEBUG = 29

RESET class-attribute instance-attribute

RESET = 30

GO_TO_ISP class-attribute instance-attribute

GO_TO_ISP = 31

REQUEST class-attribute instance-attribute

REQUEST = 32

ANTI_COLLISION class-attribute instance-attribute

ANTI_COLLISION = 33

SELECT_CARD class-attribute instance-attribute

SELECT_CARD = 34

AUTHENTICATE class-attribute instance-attribute

AUTHENTICATE = 35

READ_BLOCK class-attribute instance-attribute

READ_BLOCK = 36

WRITE_BLOCK class-attribute instance-attribute

WRITE_BLOCK = 37

SET_VALUE class-attribute instance-attribute

SET_VALUE = 38

READ_VALUE class-attribute instance-attribute

READ_VALUE = 39

CREATE_VALUE_BLOCK class-attribute instance-attribute

CREATE_VALUE_BLOCK = 40

ACCESS_CONDITION class-attribute instance-attribute

ACCESS_CONDITION = 41

HALT class-attribute instance-attribute

HALT = 42

SAVE_KEY class-attribute instance-attribute

SAVE_KEY = 43

GET_SECOND_SN class-attribute instance-attribute

GET_SECOND_SN = 44

GET_ACCESS_CONDITION class-attribute instance-attribute

GET_ACCESS_CONDITION = 45

AUTHENTICATE_KEY class-attribute instance-attribute

AUTHENTICATE_KEY = 46

REQUEST_ALL class-attribute instance-attribute

REQUEST_ALL = 47

SET_VALUEEX class-attribute instance-attribute

SET_VALUEEX = 50

TRANSFER class-attribute instance-attribute

TRANSFER = 51

RESTORE class-attribute instance-attribute

RESTORE = 52

GET_SECTOR class-attribute instance-attribute

GET_SECTOR = 61

RF_POWER_ONOFF class-attribute instance-attribute

RF_POWER_ONOFF = 62

AUTO_MODE class-attribute instance-attribute

AUTO_MODE = 63

ResponseMessage

ResponseMessage(address: int, function: int, data: Union[bytes, str])

Bases: Message

Message received from the RFID reader.

to_error

to_error() -> Optional[GNetPlusError]

Convert a NAK response into the matching GNetPlusError subclass.

Returns:

Type Description
Optional[GNetPlusError]

A GNetPlusError (subclass) if this is a NAK response, else None.

gencrc

gencrc(msg_bytes: bytes) -> int

Generate a 16-bit CRC checksum.

Parameters:

Name Type Description Default
msg_bytes bytes

bytes containing message for checksum

required

Returns:

Type Description
int

16-bit integer containing CRC checksum