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'
|
**kwargs
|
Any
|
Extra keyword arguments passed to |
{}
|
Raises:
| Type | Description |
|---|---|
ReaderConnectionError
|
If the serial port cannot be opened (a
|
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 |
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 |
None
|
empty
|
bool
|
Start with no card in the field instead. |
False
|
**kwargs
|
Any
|
Passed to |
{}
|
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.
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 ( |
{}
|
Raises:
| Type | Description |
|---|---|
ReaderNotFoundError
|
If no reader was found. Its message lists the serial ports that were seen. |
close
¶
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
¶
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.
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:
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').
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 |
None
|
cards
async
¶
cards(interval: float = 0.25, *, removal_polls: int = 2, reconnect: bool = True, reconnect_interval: float = 1.0) -> AsyncIterator[CardEvent]
sendmsg
¶
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 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
|
|
'little'
|
as_string
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
Union[str, int]
|
Card UID as hex string or integer. |
get_uid
¶
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 |
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If no card is present or the reader returns NAK. |
get_uid_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
¶
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
|
|
'little'
|
as_string
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
Union[str, int]
|
Card UID as hex string or integer. |
get_second_sn
¶
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:
| Type | Description |
|---|---|
Union[str, bytes]
|
Secondary serial number as hex string or bytes. |
select_card
¶
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
¶
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']
|
|
Raises:
| Type | Description |
|---|---|
NoCardError
|
If there is no card. |
ping
¶
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
|
|
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If the reader explicitly NAKs (unusual). |
is_card_present
¶
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
|
|
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:
Returns:
| Type | Description |
|---|---|
CardInfo
|
|
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If no card is present or any step fails. |
wait_for_card
¶
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
¶
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 product version string.
Returns:
| Type | Description |
|---|---|
str
|
Firmware/hardware version string from the connected reader. |
set_auto_mode
¶
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
¶
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
¶
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'
|
timeout
|
float
|
Timeout in seconds for the reader response. |
1.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
AuthenticationError
|
If the stored key does not match the card. |
GNetPlusError
|
If the reader returns another NAK. |
read_block
¶
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 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.
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 ( |
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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sector
|
int
|
Sector to open. |
required |
keys
|
Union[KeyRing, list[bytes], tuple[bytes, ...], bytes, None]
|
A |
None
|
key_type
|
Optional[str]
|
Only try |
None
|
Returns:
| Type | Description |
|---|---|
tuple[str, bytes]
|
|
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 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 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
¶
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
¶
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
¶
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
¶
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
¶
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 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]]
|
|
required |
raw
|
bool
|
|
False
|
combine
|
bool
|
|
False
|
keys
|
Optional[Union[bytes, dict[int, bytes]]]
|
Global 6-byte key or |
None
|
key_types
|
Union[str, dict[int, str]]
|
|
'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]]
|
|
None
|
Returns:
| Type | Description |
|---|---|
Union[dict[int, dict[int, Union[str, bytes]]], Union[str, bytes]]
|
|
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]]]]
|
|
required |
keys
|
Optional[Union[bytes, dict[int, bytes]]]
|
Global 6-byte key or |
None
|
key_types
|
Union[str, dict[int, str]]
|
|
'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]]
|
|
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
¶
Something that happened at the reader, from MifareReader.card_events() / cards().
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
EventKind
|
|
uid |
Optional[str]
|
The card UID for |
time |
datetime
|
When the event was seen. |
SectorAuth
dataclass
¶
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']
|
|
timeout |
float
|
Per-sector auth timeout in seconds (default |
flush |
bool
|
Flush the serial input buffer before reading (default |
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
¶
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 |
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
( |
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
¶
True if these access bits can never be changed once written.
key_b_readable
property
¶
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
|
'open'
|
trailer
|
Union[str, int]
|
Trailer condition: a preset name from |
'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
¶
Encode as the 4 trailer bytes 6-9 (access bits and general-purpose byte).
data_rights
¶
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
¶
Who may change Key A, read and change the access bits, and read and change Key B.
allows
¶
Whether key_type ('A' or 'B') may do operation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
operation
|
str
|
One of |
required |
key_type
|
str
|
|
required |
group
|
Optional[int]
|
Data-block group 0-2 for data operations. |
None
|
describe
¶
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 |
'open'
|
trailer
|
Union[str, int]
|
Trailer condition: see |
'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 |
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 |
None
|
sectors
|
Optional[dict[int, dict[str, KeyLike]]]
|
Known keys per sector, as |
None
|
set
¶
Record the known Key A and/or Key B of sector.
get
¶
The known key of key_type for sector, or None.
candidates
¶
(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
¶
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. |
save
¶
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 ( |
required |
uid
|
Union[str, bytes, int]
|
The card UID: a |
required |
sector
|
int
|
Sector number, so every sector gets its own key. |
0
|
key_type
|
str
|
|
'A'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the master secret is shorter than 16 bytes, or the other arguments are invalid. |
parse_key
¶
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¶
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. |
decode
¶
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]
|
|
required |
base
|
Optional[dict[tuple[int, int], bytes]]
|
Current contents of the blocks (default: zeros). |
None
|
Returns:
| Type | Description |
|---|---|
dict[tuple[int, int], bytes]
|
|
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 |
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 |
None
|
encoding
|
str
|
Text encoding for |
'utf-8'
|
byteorder
|
Literal['little', 'big']
|
|
'little'
|
encode
¶
Turn value into the field's bytes.
Raises:
| Type | Description |
|---|---|
SchemaError
|
If the value has the wrong type or does not fit. |
SchemaError
¶
Bases: ValueError
A schema or a value that does not fit it.
Wallet¶
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 |
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 |
balance
¶
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
¶
Add amount and return the new balance.
Raises:
| Type | Description |
|---|---|
ValueError
|
If amount is not positive or the result would exceed max_balance. |
spend
¶
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
¶
Bases: ValueError
Wallet.spend() was asked for more than the balance.
WalletError
¶
encode_value_block
¶
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 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
¶
Return how many blocks sector has (4, or 16 for 4K sectors 32-39).
trailer_block
¶
Return the relative block number of sector's trailer (3 or 15).
data_blocks
¶
Return the relative block numbers that hold data (excludes the trailer).
absolute_block
¶
Convert a relative block within sector to an absolute block number.
sector_of
¶
Convert an absolute block number to (sector, relative_block).
is_trailer
¶
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
¶
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 ( |
hint |
str
|
A short suggestion for fixing the problem, or |
NoCardError
¶
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
¶
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
¶
Bases: GNetPlusError
A block was accessed without authenticating its sector.
PCR310U readers (firmware PGM0487) return NAK 0x0C for reads and
0x0A for writes.
AccessDeniedError
¶
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
¶
CardWriteError
¶
ValueBlockError
¶
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
¶
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
¶
ReaderAccessError
¶
ReaderConnectionError
¶
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
¶
Bases: RuntimeError
MifareReader.auto() could not find a reader.
Attributes:
| Name | Type | Description |
|---|---|---|
ports |
The serial ports that were seen, as |
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. |
''
|
Returns:
| Type | Description |
|---|---|
GNetPlusError
|
An exception instance (not raised). |
InvalidMessage
¶
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 |
size |
str
|
|
blocks |
list[Optional[bytes]]
|
One entry per absolute block: 16 bytes, or None if unread. |
keys |
dict[int, tuple[Optional[bytes], Optional[bytes]]]
|
|
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
|
DEFAULT_KEYS
|
size
|
Optional[str]
|
|
None
|
progress
|
Optional[ProgressCallback]
|
Called as |
None
|
Returns:
| Type | Description |
|---|---|
CardDump
|
A |
CardDump
|
|
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
|
DEFAULT_KEYS
|
sectors
|
Optional[Sequence[int]]
|
Only write these sectors (default: all in the dump). |
None
|
progress
|
Optional[ProgressCallback]
|
Called as |
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 |
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 |
b'4\xc6\x9b\xd3'
|
size
|
str
|
|
'1K'
|
keys
|
Optional[dict[int, tuple[bytes, bytes]]]
|
Optional |
None
|
read
¶
Return the 16 bytes of relative block in sector (no authentication).
write
¶
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.
access
¶
access(sector: int) -> Optional[AccessBits]
The access bits of sector, or None if they are invalid (the sector is blocked).
value
¶
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 |
place_card
¶
place_card(card: SimulatedCard) -> None
Put card in the field (replacing any other). Sends an event in auto mode.
tear_next_write
¶
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
¶
Act as if the USB cable was pulled: every read and write raises serial.SerialException.
replug
¶
Plug the reader back in. Like a real port, it must be opened again (open()).
Frame tracing¶
enable_wire_trace
¶
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 |
False
|
Returns:
| Type | Description |
|---|---|
Handler
|
The handler that was added; pass it to |
disable_wire_trace
¶
Stop tracing that was started with enable_wire_trace().
format_frame
¶
Return a one-line, human-readable description of a raw frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
direction
|
str
|
|
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
¶
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
¶
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
¶
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
¶
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).
ResponseMessage
¶
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 |
gencrc
¶
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 |