pythonbeid 0.2.0__py3-none-any.whl → 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pythonbeid/__init__.py CHANGED
@@ -1,10 +1,11 @@
1
1
  """pythonbeid — read information from Belgian eID cards."""
2
2
 
3
- from .card_reader import CardReader
3
+ from .card_reader import CardReader, list_readers
4
4
  from .exceptions import APDUError, CardCommunicationError, NoCardError, NoReaderError
5
5
 
6
6
  __all__ = [
7
7
  "CardReader",
8
+ "list_readers",
8
9
  "NoReaderError",
9
10
  "NoCardError",
10
11
  "CardCommunicationError",
pythonbeid/card_reader.py CHANGED
@@ -1,256 +1,258 @@
1
- """Belgian eID card reader.
2
-
3
- Reads personal data, address and optionally the photo from a Belgian
4
- electronic identity card via a PC/SC-compatible smart card reader.
5
-
6
- Dependencies: pyscard (python-smartcard)
7
-
8
- Usage::
9
-
10
- from pythonbeid import CardReader
11
-
12
- with CardReader() as cr:
13
- info = cr.read_informations(photo=False)
14
- print(info["last_name"])
15
- """
16
- import base64
17
- import logging
18
- from datetime import datetime
19
- from typing import Any
20
-
21
- from smartcard.Exceptions import CardConnectionException, NoCardException
22
- from smartcard.System import readers
23
-
24
- from .exceptions import APDUError, CardCommunicationError, NoCardError, NoReaderError
25
- from .parser import parse_french_date, parse_tlv
26
-
27
- logger = logging.getLogger(__name__)
28
-
29
- # ── File identifiers (path on the card) ──────────────────────────────────────
30
- _FILE_ID = [0x3F, 0x00, 0xDF, 0x01, 0x40, 0x31] # personal identity data
31
- _FILE_ADDRESS = [0x3F, 0x00, 0xDF, 0x01, 0x40, 0x33] # address data
32
- _FILE_PHOTO = [0x3F, 0x00, 0xDF, 0x01, 0x40, 0x35] # photo data
33
-
34
- # ISO 7816-4: Le=0x00 in a short APDU means "expect up to 256 bytes".
35
- _LE_MAX = 0x00
36
-
37
- # ── Status words that are handled in-band ──────────────────────────────────
38
- _SW_OK = 0x90 # Normal completion
39
- _SW_MORE_DATA = 0x61 # More data available (GET RESPONSE with SW2 bytes)
40
- _SW_WRONG_LE = 0x6C # Wrong Le: use SW2 as exact length
41
-
42
-
43
- class CardReader:
44
- """Read information from a Belgian eID card.
45
-
46
- Parameters
47
- ----------
48
- reader_index:
49
- Index of the PC/SC reader to use when multiple readers are connected.
50
- Defaults to 0 (first available reader).
51
-
52
- Examples
53
- --------
54
- Using as a context manager (recommended)::
55
-
56
- with CardReader() as cr:
57
- data = cr.read_informations()
58
-
59
- Or manually::
60
-
61
- cr = CardReader()
62
- try:
63
- data = cr.read_informations()
64
- finally:
65
- cr.close()
66
- """
67
-
68
- def __init__(self, reader_index: int = 0) -> None:
69
- available = readers()
70
- if not available:
71
- raise NoReaderError("No smart card reader detected")
72
- if reader_index >= len(available):
73
- raise NoReaderError(
74
- f"Reader index {reader_index} out of range "
75
- f"({len(available)} reader(s) available)"
76
- )
77
- reader = available[reader_index]
78
- logger.debug("Using reader: %s", reader)
79
- try:
80
- self._cnx = reader.createConnection()
81
- self._cnx.connect()
82
- except NoCardException:
83
- raise NoCardError(f"No card in reader '{reader}'")
84
- except CardConnectionException as exc:
85
- raise CardCommunicationError(f"Connection error on '{reader}': {exc}") from exc
86
- logger.debug("Connected to card via '%s'", reader)
87
-
88
- # ── Context manager ───────────────────────────────────────────────────
89
-
90
- def __enter__(self) -> "CardReader":
91
- return self
92
-
93
- def __exit__(self, *_: Any) -> None:
94
- self.close()
95
-
96
- def close(self) -> None:
97
- """Disconnect from the card and release the reader."""
98
- try:
99
- self._cnx.disconnect()
100
- logger.debug("Disconnected from card")
101
- except Exception:
102
- pass # Ignore errors on cleanup
103
-
104
- # ── Low-level APDU transport ──────────────────────────────────────────
105
-
106
- def _send_apdu(self, apdu: list[int]) -> tuple[list[int], int, int]:
107
- """Transmit one APDU and return ``(data, SW1, SW2)``.
108
-
109
- Raises
110
- ------
111
- APDUError
112
- If the card returns an unexpected status word (i.e. not 0x90,
113
- 0x61, or 0x6C).
114
- """
115
- response, sw1, sw2 = self._cnx.transmit(apdu)
116
- logger.debug("APDU %s → SW=%02X%02X data(%d)=%s",
117
- [f"{b:02X}" for b in apdu], sw1, sw2, len(response),
118
- [f"{b:02X}" for b in response[:8]])
119
- if sw1 not in (_SW_OK, _SW_MORE_DATA, _SW_WRONG_LE):
120
- raise APDUError(sw1, sw2,
121
- f"Unexpected status SW={sw1:02X}{sw2:02X} "
122
- f"for APDU {[hex(b) for b in apdu[:4]]}")
123
- return response, sw1, sw2
124
-
125
- # ── File access helpers ───────────────────────────────────────────────
126
-
127
- def _select_file(self, file_id: list[int]) -> None:
128
- """Send a SELECT command for *file_id* (no response expected)."""
129
- cmd = [0x00, 0xA4, 0x08, 0x0C, len(file_id)] + file_id
130
- _, sw1, sw2 = self._send_apdu(cmd)
131
- if sw1 != _SW_OK:
132
- raise APDUError(sw1, sw2, f"SELECT failed for file {[hex(b) for b in file_id]}")
133
- logger.debug("Selected file %s", [f"{b:02X}" for b in file_id])
134
-
135
- def _read_binary(self, p1: int, p2: int, le: int) -> tuple[list[int], int, int]:
136
- """Send a READ BINARY command and handle Le mismatch (0x6C)."""
137
- cmd = [0x00, 0xB0, p1, p2, le]
138
- data, sw1, sw2 = self._send_apdu(cmd)
139
- if sw1 == _SW_WRONG_LE:
140
- # Card tells us the exact length: re-issue with SW2 as Le.
141
- logger.debug("RE-READ BINARY with Le=%d (was %d)", sw2, le)
142
- cmd[-1] = sw2
143
- data, sw1, sw2 = self._send_apdu(cmd)
144
- return data, sw1, sw2
145
-
146
- def _read_data(self, file_id: list[int]) -> list[int]:
147
- """Select *file_id* and read its content (up to 256 bytes)."""
148
- self._select_file(file_id)
149
- data, sw1, sw2 = self._read_binary(0x00, 0x00, _LE_MAX)
150
- logger.debug("Read %d bytes from file %s, SW=%02X%02X",
151
- len(data), [f"{b:02X}" for b in file_id], sw1, sw2)
152
- return data
153
-
154
- def _read_photo(self) -> bytearray:
155
- """Read the complete photo file in 256-byte chunks.
156
-
157
- The photo file is typically larger than 256 bytes so it must be
158
- read with successive READ BINARY commands using an incrementing
159
- offset (P1 = high byte, P2 = low byte of a 15-bit offset).
160
- """
161
- self._select_file(_FILE_PHOTO)
162
- photo_bytes: list[int] = []
163
- # Offset advances by 256 bytes on each iteration.
164
- # P1 holds the high byte of the byte offset (offset >> 8),
165
- # P2 holds the low byte (offset & 0xFF).
166
- # Starting with P1=0, P2=0 and incrementing P1 by 1 each time
167
- # moves the window by 256 bytes per step.
168
- p1 = 0
169
- while True:
170
- data, sw1, sw2 = self._read_binary(p1, 0x00, _LE_MAX)
171
- if sw1 == _SW_OK:
172
- photo_bytes.extend(data)
173
- if len(data) < 256:
174
- # Received fewer bytes than requested → end of file.
175
- break
176
- p1 += 1
177
- elif sw1 == _SW_WRONG_LE:
178
- # _read_binary already retried with the correct Le,
179
- # so if we still get here something went wrong.
180
- logger.warning("Unexpected 0x6C after retry at p1=%d", p1)
181
- photo_bytes.extend(data)
182
- break
183
- else:
184
- # Any other status (e.g. 0x6282 end-of-file) ends the loop.
185
- logger.debug("Photo read ended at p1=%d, SW=%02X%02X", p1, sw1, sw2)
186
- break
187
- logger.debug("Photo: %d bytes total", len(photo_bytes))
188
- return bytearray(photo_bytes)
189
-
190
- # ── Public API ────────────────────────────────────────────────────────
191
-
192
- def read_informations(self, photo: bool = False) -> dict[str, Any]:
193
- """Read and return all information from the card.
194
-
195
- Parameters
196
- ----------
197
- photo:
198
- When ``True`` the card photo is read and included in the
199
- returned dictionary as a base-64 encoded string.
200
-
201
- Returns
202
- -------
203
- dict
204
- Keys: ``card_number``, ``validity_start``, ``validity_end``,
205
- ``issuing_municipality``, ``national_number``, ``last_name``,
206
- ``first_names``, ``suffix``, ``nationality``, ``birth_place``,
207
- ``birth_date``, ``sex``, ``address``, ``postal_code``,
208
- ``city``, and optionally ``photo``.
209
- """
210
- # ── Identity file ────────────────────────────────────────────────
211
- id_data = self._read_data(_FILE_ID)
212
- id_fields = parse_tlv(id_data, 13) # tags 1–13 (tag 2 / index 1 unused)
213
-
214
- informations: dict[str, Any] = {
215
- "card_number": id_fields[0],
216
- # id_fields[1] is the chip serial number — not exposed in the API
217
- "validity_start": datetime.strptime(id_fields[2], "%d.%m.%Y"),
218
- "validity_end": datetime.strptime(id_fields[3], "%d.%m.%Y"),
219
- "issuing_municipality": id_fields[4],
220
- "national_number": id_fields[5],
221
- "last_name": id_fields[6],
222
- "first_names": id_fields[7],
223
- "suffix": id_fields[8],
224
- "nationality": id_fields[9],
225
- "birth_place": id_fields[10],
226
- "birth_date": parse_french_date(id_fields[11]),
227
- "sex": id_fields[12],
228
- }
229
-
230
- # ── Address file ─────────────────────────────────────────────────
231
- addr_data = self._read_data(_FILE_ADDRESS)
232
- addr_fields = parse_tlv(addr_data, 3)
233
-
234
- informations["address"] = addr_fields[0]
235
- informations["postal_code"] = addr_fields[1]
236
- informations["city"] = addr_fields[2]
237
-
238
- # ── Photo (optional) ─────────────────────────────────────────────
239
- if photo:
240
- photo_bytes = self._read_photo()
241
- informations["photo"] = base64.b64encode(photo_bytes).decode("ascii")
242
-
243
- # Mirror every key as an instance attribute for convenience.
244
- for key, value in informations.items():
245
- setattr(self, key, value)
246
-
247
- return informations
248
-
249
-
250
- if __name__ == "__main__":
251
- import logging
252
- from pprint import pprint
253
-
254
- logging.basicConfig(level=logging.WARNING)
255
- with CardReader() as cr:
256
- pprint(cr.read_informations(photo=False))
1
+ """Belgian eID card reader.
2
+
3
+ Reads personal data, address and optionally the photo from a Belgian
4
+ electronic identity card via a PC/SC-compatible smart card reader.
5
+
6
+ Dependencies: pyscard (python-smartcard)
7
+
8
+ Usage::
9
+
10
+ from pythonbeid import CardReader
11
+
12
+ with CardReader() as cr:
13
+ info = cr.read_informations(photo=False)
14
+ print(info["last_name"])
15
+ """
16
+ import base64
17
+ import logging
18
+ from datetime import datetime
19
+ from typing import Any
20
+
21
+ from smartcard.Exceptions import CardConnectionException, NoCardException
22
+ from smartcard.System import readers
23
+
24
+ from .exceptions import APDUError, CardCommunicationError, NoCardError, NoReaderError
25
+ from .parser import parse_french_date, parse_tlv
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ # ── File identifiers (path on the card) ──────────────────────────────────────
30
+ _FILE_ID = [0x3F, 0x00, 0xDF, 0x01, 0x40, 0x31] # personal identity data
31
+ _FILE_ADDRESS = [0x3F, 0x00, 0xDF, 0x01, 0x40, 0x33] # address data
32
+ _FILE_PHOTO = [0x3F, 0x00, 0xDF, 0x01, 0x40, 0x35] # photo data
33
+
34
+ # ISO 7816-4: Le=0x00 in a short APDU means "expect up to 256 bytes".
35
+ _LE_MAX = 0x00
36
+
37
+ # ── Status words that are handled in-band ──────────────────────────────────
38
+ _SW_OK = 0x90 # Normal completion
39
+ _SW_MORE_DATA = 0x61 # More data available (GET RESPONSE with SW2 bytes)
40
+ _SW_WRONG_LE = 0x6C # Wrong Le: use SW2 as exact length
41
+
42
+
43
+ def list_readers() -> list[str]:
44
+ """Return the names of all connected PC/SC smart card readers.
45
+
46
+ Returns:
47
+ A list of human-readable reader names, in PC/SC order (the index
48
+ of a name matches the ``reader_index`` argument of
49
+ :class:`CardReader`). Empty when no reader is connected.
50
+ """
51
+ return [str(reader) for reader in readers()]
52
+
53
+
54
+ class CardReader:
55
+ """Read information from a Belgian eID card.
56
+
57
+ Args:
58
+ reader_index: Index of the PC/SC reader to use when multiple readers
59
+ are connected. Defaults to 0 (first available reader).
60
+
61
+ Examples:
62
+ Using as a context manager (recommended)::
63
+
64
+ with CardReader() as cr:
65
+ data = cr.read_informations()
66
+
67
+ Or manually::
68
+
69
+ cr = CardReader()
70
+ try:
71
+ data = cr.read_informations()
72
+ finally:
73
+ cr.close()
74
+ """
75
+
76
+ def __init__(self, reader_index: int = 0) -> None:
77
+ available = readers()
78
+ if not available:
79
+ raise NoReaderError("No smart card reader detected")
80
+ if reader_index >= len(available):
81
+ raise NoReaderError(
82
+ f"Reader index {reader_index} out of range "
83
+ f"({len(available)} reader(s) available)"
84
+ )
85
+ reader = available[reader_index]
86
+ logger.debug("Using reader: %s", reader)
87
+ try:
88
+ self._cnx = reader.createConnection()
89
+ self._cnx.connect()
90
+ except NoCardException:
91
+ raise NoCardError(f"No card in reader '{reader}'")
92
+ except CardConnectionException as exc:
93
+ raise CardCommunicationError(f"Connection error on '{reader}': {exc}") from exc
94
+ logger.debug("Connected to card via '%s'", reader)
95
+
96
+ # ── Context manager ───────────────────────────────────────────────────
97
+
98
+ def __enter__(self) -> "CardReader":
99
+ return self
100
+
101
+ def __exit__(self, *_: Any) -> None:
102
+ self.close()
103
+
104
+ def close(self) -> None:
105
+ """Disconnect from the card and release the reader."""
106
+ try:
107
+ self._cnx.disconnect()
108
+ logger.debug("Disconnected from card")
109
+ except Exception:
110
+ pass # Ignore errors on cleanup
111
+
112
+ # ── Low-level APDU transport ──────────────────────────────────────────
113
+
114
+ def _send_apdu(self, apdu: list[int]) -> tuple[list[int], int, int]:
115
+ """Transmit one APDU and return ``(data, SW1, SW2)``.
116
+
117
+ Raises:
118
+ APDUError: If the card returns an unexpected status word
119
+ (i.e. not 0x90, 0x61, or 0x6C).
120
+ """
121
+ response, sw1, sw2 = self._cnx.transmit(apdu)
122
+ logger.debug("APDU %s → SW=%02X%02X data(%d)=%s",
123
+ [f"{b:02X}" for b in apdu], sw1, sw2, len(response),
124
+ [f"{b:02X}" for b in response[:8]])
125
+ if sw1 not in (_SW_OK, _SW_MORE_DATA, _SW_WRONG_LE):
126
+ raise APDUError(sw1, sw2,
127
+ f"Unexpected status SW={sw1:02X}{sw2:02X} "
128
+ f"for APDU {[hex(b) for b in apdu[:4]]}")
129
+ return response, sw1, sw2
130
+
131
+ # ── File access helpers ───────────────────────────────────────────────
132
+
133
+ def _select_file(self, file_id: list[int]) -> None:
134
+ """Send a SELECT command for *file_id* (no response expected)."""
135
+ cmd = [0x00, 0xA4, 0x08, 0x0C, len(file_id)] + file_id
136
+ _, sw1, sw2 = self._send_apdu(cmd)
137
+ if sw1 != _SW_OK:
138
+ raise APDUError(sw1, sw2, f"SELECT failed for file {[hex(b) for b in file_id]}")
139
+ logger.debug("Selected file %s", [f"{b:02X}" for b in file_id])
140
+
141
+ def _read_binary(self, p1: int, p2: int, le: int) -> tuple[list[int], int, int]:
142
+ """Send a READ BINARY command and handle Le mismatch (0x6C)."""
143
+ cmd = [0x00, 0xB0, p1, p2, le]
144
+ data, sw1, sw2 = self._send_apdu(cmd)
145
+ if sw1 == _SW_WRONG_LE:
146
+ # Card tells us the exact length: re-issue with SW2 as Le.
147
+ logger.debug("RE-READ BINARY with Le=%d (was %d)", sw2, le)
148
+ cmd[-1] = sw2
149
+ data, sw1, sw2 = self._send_apdu(cmd)
150
+ return data, sw1, sw2
151
+
152
+ def _read_data(self, file_id: list[int]) -> list[int]:
153
+ """Select *file_id* and read its content (up to 256 bytes)."""
154
+ self._select_file(file_id)
155
+ data, sw1, sw2 = self._read_binary(0x00, 0x00, _LE_MAX)
156
+ logger.debug("Read %d bytes from file %s, SW=%02X%02X",
157
+ len(data), [f"{b:02X}" for b in file_id], sw1, sw2)
158
+ return data
159
+
160
+ def _read_photo(self) -> bytearray:
161
+ """Read the complete photo file in 256-byte chunks.
162
+
163
+ The photo file is typically larger than 256 bytes so it must be
164
+ read with successive READ BINARY commands using an incrementing
165
+ offset (P1 = high byte, P2 = low byte of a 15-bit offset).
166
+ """
167
+ self._select_file(_FILE_PHOTO)
168
+ photo_bytes: list[int] = []
169
+ # Offset advances by 256 bytes on each iteration.
170
+ # P1 holds the high byte of the byte offset (offset >> 8),
171
+ # P2 holds the low byte (offset & 0xFF).
172
+ # Starting with P1=0, P2=0 and incrementing P1 by 1 each time
173
+ # moves the window by 256 bytes per step.
174
+ p1 = 0
175
+ while True:
176
+ data, sw1, sw2 = self._read_binary(p1, 0x00, _LE_MAX)
177
+ if sw1 == _SW_OK:
178
+ photo_bytes.extend(data)
179
+ if len(data) < 256:
180
+ # Received fewer bytes than requested → end of file.
181
+ break
182
+ p1 += 1
183
+ elif sw1 == _SW_WRONG_LE:
184
+ # _read_binary already retried with the correct Le,
185
+ # so if we still get here something went wrong.
186
+ logger.warning("Unexpected 0x6C after retry at p1=%d", p1)
187
+ photo_bytes.extend(data)
188
+ break
189
+ else:
190
+ # Any other status (e.g. 0x6282 end-of-file) ends the loop.
191
+ logger.debug("Photo read ended at p1=%d, SW=%02X%02X", p1, sw1, sw2)
192
+ break
193
+ logger.debug("Photo: %d bytes total", len(photo_bytes))
194
+ return bytearray(photo_bytes)
195
+
196
+ # ── Public API ────────────────────────────────────────────────────────
197
+
198
+ def read_informations(self, photo: bool = False) -> dict[str, Any]:
199
+ """Read and return all information from the card.
200
+
201
+ Args:
202
+ photo: When ``True`` the card photo is read and included in the
203
+ returned dictionary as a base-64 encoded string.
204
+
205
+ Returns:
206
+ A dictionary with keys: ``card_number``, ``validity_start``,
207
+ ``validity_end``, ``issuing_municipality``, ``national_number``,
208
+ ``last_name``, ``first_names``, ``suffix``, ``nationality``,
209
+ ``birth_place``, ``birth_date``, ``sex``, ``address``,
210
+ ``postal_code``, ``city``, and optionally ``photo``.
211
+ """
212
+ # ── Identity file ────────────────────────────────────────────────
213
+ id_data = self._read_data(_FILE_ID)
214
+ id_fields = parse_tlv(id_data, 13) # tags 1–13 (tag 2 / index 1 unused)
215
+
216
+ informations: dict[str, Any] = {
217
+ "card_number": id_fields[0],
218
+ # id_fields[1] is the chip serial number — not exposed in the API
219
+ "validity_start": datetime.strptime(id_fields[2], "%d.%m.%Y"),
220
+ "validity_end": datetime.strptime(id_fields[3], "%d.%m.%Y"),
221
+ "issuing_municipality": id_fields[4],
222
+ "national_number": id_fields[5],
223
+ "last_name": id_fields[6],
224
+ "first_names": id_fields[7],
225
+ "suffix": id_fields[8],
226
+ "nationality": id_fields[9],
227
+ "birth_place": id_fields[10],
228
+ "birth_date": parse_french_date(id_fields[11]),
229
+ "sex": id_fields[12],
230
+ }
231
+
232
+ # ── Address file ─────────────────────────────────────────────────
233
+ addr_data = self._read_data(_FILE_ADDRESS)
234
+ addr_fields = parse_tlv(addr_data, 3)
235
+
236
+ informations["address"] = addr_fields[0]
237
+ informations["postal_code"] = addr_fields[1]
238
+ informations["city"] = addr_fields[2]
239
+
240
+ # ── Photo (optional) ─────────────────────────────────────────────
241
+ if photo:
242
+ photo_bytes = self._read_photo()
243
+ informations["photo"] = base64.b64encode(photo_bytes).decode("ascii")
244
+
245
+ # Mirror every key as an instance attribute for convenience.
246
+ for key, value in informations.items():
247
+ setattr(self, key, value)
248
+
249
+ return informations
250
+
251
+
252
+ if __name__ == "__main__":
253
+ import logging
254
+ from pprint import pprint
255
+
256
+ logging.basicConfig(level=logging.WARNING)
257
+ with CardReader() as cr:
258
+ pprint(cr.read_informations(photo=False))
pythonbeid/exceptions.py CHANGED
@@ -1,30 +1,27 @@
1
- """Custom exceptions for pythonbeid."""
2
-
3
-
4
- class NoReaderError(RuntimeError):
5
- """Raised when no smart card reader is detected."""
6
-
7
-
8
- class NoCardError(RuntimeError):
9
- """Raised when a reader is present but no card is inserted."""
10
-
11
-
12
- class CardCommunicationError(RuntimeError):
13
- """Raised on a general card communication failure."""
14
-
15
-
16
- class APDUError(CardCommunicationError):
17
- """Raised when an APDU command returns an unexpected status word.
18
-
19
- Attributes
20
- ----------
21
- sw1 : int
22
- First status byte (SW1).
23
- sw2 : int
24
- Second status byte (SW2).
25
- """
26
-
27
- def __init__(self, sw1: int, sw2: int, message: str = "") -> None:
28
- self.sw1 = sw1
29
- self.sw2 = sw2
30
- super().__init__(message or f"Unexpected APDU status: SW={sw1:02X}{sw2:02X}")
1
+ """Custom exceptions for pythonbeid."""
2
+
3
+
4
+ class NoReaderError(RuntimeError):
5
+ """Raised when no smart card reader is detected."""
6
+
7
+
8
+ class NoCardError(RuntimeError):
9
+ """Raised when a reader is present but no card is inserted."""
10
+
11
+
12
+ class CardCommunicationError(RuntimeError):
13
+ """Raised on a general card communication failure."""
14
+
15
+
16
+ class APDUError(CardCommunicationError):
17
+ """Raised when an APDU command returns an unexpected status word.
18
+
19
+ Attributes:
20
+ sw1: First status byte (SW1).
21
+ sw2: Second status byte (SW2).
22
+ """
23
+
24
+ def __init__(self, sw1: int, sw2: int, message: str = "") -> None:
25
+ self.sw1 = sw1
26
+ self.sw2 = sw2
27
+ super().__init__(message or f"Unexpected APDU status: SW={sw1:02X}{sw2:02X}")
pythonbeid/parser.py CHANGED
@@ -1,89 +1,80 @@
1
- """Pure parsing functions for Belgian eID card data.
2
-
3
- These functions have no I/O dependencies and can be tested without hardware.
4
- """
5
- from datetime import datetime
6
-
7
- # French month abbreviations as found on Belgian eID cards.
8
- _MONTH_MAP: dict[str, str] = {
9
- "JANV": "01", "JAN": "01",
10
- "FEVR": "02", "FEV": "02",
11
- "MARS": "03", "MAR": "03",
12
- "AVRI": "04", "AVR": "04",
13
- "MAI": "05",
14
- "JUIN": "06",
15
- "JUIL": "07",
16
- "AOUT": "08", "AOU": "08",
17
- "SEPT": "09", "SEP": "09",
18
- "OCTO": "10", "OCT": "10",
19
- "NOVE": "11", "NOV": "11",
20
- "DECE": "12", "DEC": "12",
21
- }
22
-
23
-
24
- def parse_tlv(data: list[int], num_fields: int) -> list[str]:
25
- """Parse a TLV-encoded buffer from a Belgian eID card.
26
-
27
- Each record has the format: [tag: 1 byte] [length: 1 byte] [value: length bytes].
28
- Parsing stops once *num_fields* records have been extracted or the buffer
29
- is exhausted (whichever comes first).
30
-
31
- Parameters
32
- ----------
33
- data:
34
- Raw bytes received from the card (list of ints, 0–255).
35
- num_fields:
36
- Maximum number of fields to extract.
37
-
38
- Returns
39
- -------
40
- list[str]
41
- Decoded string values; an empty string is used for any field that
42
- cannot be decoded as UTF-8.
43
- """
44
- idx = 0
45
- fields: list[str] = []
46
- while len(fields) < num_fields:
47
- # Need at least 2 bytes for tag + length.
48
- if idx + 1 >= len(data):
49
- break
50
- # tag byte (idx) — not used for value extraction
51
- idx += 1
52
- length = data[idx]
53
- idx += 1
54
- # Guard against a truncated buffer.
55
- if idx + length > len(data):
56
- break
57
- raw = bytes(data[idx: idx + length])
58
- idx += length
59
- try:
60
- fields.append(raw.decode("utf-8"))
61
- except UnicodeDecodeError:
62
- fields.append("")
63
- return fields
64
-
65
-
66
- def parse_french_date(date_str: str) -> datetime:
67
- """Parse a French date string as printed on Belgian eID cards.
68
-
69
- Expected format: ``DD MON YYYY`` where *MON* is a French month
70
- abbreviation (e.g. ``"15 JANV 2000"`` or ``"03 MAR 1985"``).
71
-
72
- Unknown month abbreviations fall back to January ("01").
73
-
74
- Parameters
75
- ----------
76
- date_str:
77
- Date string to parse.
78
-
79
- Returns
80
- -------
81
- datetime
82
- Parsed date (time component is midnight, no timezone).
83
- """
84
- parts = date_str.split()
85
- if len(parts) != 3:
86
- raise ValueError(f"Unexpected date format: {date_str!r}")
87
- day, month_abbr, year = parts
88
- month = _MONTH_MAP.get(month_abbr.upper(), "01")
89
- return datetime.strptime(f"{day}/{month}/{year}", "%d/%m/%Y")
1
+ """Pure parsing functions for Belgian eID card data.
2
+
3
+ These functions have no I/O dependencies and can be tested without hardware.
4
+ """
5
+ from datetime import datetime
6
+
7
+ # French month abbreviations as found on Belgian eID cards.
8
+ _MONTH_MAP: dict[str, str] = {
9
+ "JANV": "01", "JAN": "01",
10
+ "FEVR": "02", "FEV": "02",
11
+ "MARS": "03", "MAR": "03",
12
+ "AVRI": "04", "AVR": "04",
13
+ "MAI": "05",
14
+ "JUIN": "06",
15
+ "JUIL": "07",
16
+ "AOUT": "08", "AOU": "08",
17
+ "SEPT": "09", "SEP": "09",
18
+ "OCTO": "10", "OCT": "10",
19
+ "NOVE": "11", "NOV": "11",
20
+ "DECE": "12", "DEC": "12",
21
+ }
22
+
23
+
24
+ def parse_tlv(data: list[int], num_fields: int) -> list[str]:
25
+ """Parse a TLV-encoded buffer from a Belgian eID card.
26
+
27
+ Each record has the format: [tag: 1 byte] [length: 1 byte] [value: length bytes].
28
+ Parsing stops once *num_fields* records have been extracted or the buffer
29
+ is exhausted (whichever comes first).
30
+
31
+ Args:
32
+ data: Raw bytes received from the card (list of ints, 0-255).
33
+ num_fields: Maximum number of fields to extract.
34
+
35
+ Returns:
36
+ Decoded string values; an empty string is used for any field that
37
+ cannot be decoded as UTF-8.
38
+ """
39
+ idx = 0
40
+ fields: list[str] = []
41
+ while len(fields) < num_fields:
42
+ # Need at least 2 bytes for tag + length.
43
+ if idx + 1 >= len(data):
44
+ break
45
+ # tag byte (idx) — not used for value extraction
46
+ idx += 1
47
+ length = data[idx]
48
+ idx += 1
49
+ # Guard against a truncated buffer.
50
+ if idx + length > len(data):
51
+ break
52
+ raw = bytes(data[idx: idx + length])
53
+ idx += length
54
+ try:
55
+ fields.append(raw.decode("utf-8"))
56
+ except UnicodeDecodeError:
57
+ fields.append("")
58
+ return fields
59
+
60
+
61
+ def parse_french_date(date_str: str) -> datetime:
62
+ """Parse a French date string as printed on Belgian eID cards.
63
+
64
+ Expected format: ``DD MON YYYY`` where *MON* is a French month
65
+ abbreviation (e.g. ``"15 JANV 2000"`` or ``"03 MAR 1985"``).
66
+
67
+ Unknown month abbreviations fall back to January ("01").
68
+
69
+ Args:
70
+ date_str: Date string to parse.
71
+
72
+ Returns:
73
+ Parsed date as a ``datetime`` (time component is midnight, no timezone).
74
+ """
75
+ parts = date_str.split()
76
+ if len(parts) != 3:
77
+ raise ValueError(f"Unexpected date format: {date_str!r}")
78
+ day, month_abbr, year = parts
79
+ month = _MONTH_MAP.get(month_abbr.upper(), "01")
80
+ return datetime.strptime(f"{day}/{month}/{year}", "%d/%m/%Y")
@@ -1,104 +1,104 @@
1
- Metadata-Version: 2.4
2
- Name: pythonbeid
3
- Version: 0.2.0
4
- Summary: Un module pour lire les informations des cartes d'identité belges
5
- Author-email: Fabien Toune <fabien.toune@gmail.com>
6
- License-Expression: MIT
7
- Project-URL: Homepage, https://github.com/Lapin-Blanc/pythonbeid
8
- Project-URL: Bug Tracker, https://github.com/Lapin-Blanc/pythonbeid/issues
9
- Classifier: Programming Language :: Python :: 3
10
- Classifier: Operating System :: OS Independent
11
- Classifier: Topic :: Security
12
- Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
- Requires-Python: >=3.9
14
- Description-Content-Type: text/markdown
15
- License-File: LICENSE
16
- Requires-Dist: pyscard
17
- Provides-Extra: dev
18
- Requires-Dist: pytest; extra == "dev"
19
- Requires-Dist: pytest-cov; extra == "dev"
20
- Requires-Dist: build; extra == "dev"
21
- Requires-Dist: twine; extra == "dev"
22
- Dynamic: license-file
23
-
24
-
25
- # PythonBEID
26
-
27
- PythonBEID est un module Python pour lire les informations essentielles des cartes d'identité belge à l'aide d'un lecteur de cartes PC/SC et de la bibliothèque `pyscard`.
28
-
29
- ## Installation
30
-
31
- ```bash
32
- pip install pythonbeid
33
- ```
34
-
35
- ## Utilisation
36
-
37
- ```python
38
- from pythonbeid import CardReader, NoReaderError, NoCardError
39
-
40
- try:
41
- with CardReader() as cr: # context manager — ferme proprement la connexion
42
- info = cr.read_informations(photo=False)
43
- print(info["last_name"]) # Smith
44
- print(info["birth_date"]) # datetime(1990, 1, 1)
45
- except NoReaderError:
46
- print("Aucun lecteur de carte détecté.")
47
- except NoCardError:
48
- print("Aucune carte dans le lecteur.")
49
- ```
50
-
51
- Si plusieurs lecteurs sont connectés, précisez l'index :
52
-
53
- ```python
54
- with CardReader(reader_index=1) as cr:
55
- info = cr.read_informations()
56
- ```
57
-
58
- ### Champs retournés par `read_informations()`
59
-
60
- | Clé | Type | Description |
61
- |---|---|---|
62
- | `card_number` | str | Numéro de la carte |
63
- | `validity_start` | datetime | Date début de validité |
64
- | `validity_end` | datetime | Date fin de validité |
65
- | `issuing_municipality` | str | Commune de délivrance |
66
- | `national_number` | str | Numéro national |
67
- | `last_name` | str | Nom de famille |
68
- | `first_names` | str | Prénom(s) |
69
- | `suffix` | str | Suffixe de nom |
70
- | `nationality` | str | Nationalité |
71
- | `birth_place` | str | Lieu de naissance |
72
- | `birth_date` | datetime | Date de naissance |
73
- | `sex` | str | Sexe |
74
- | `address` | str | Adresse |
75
- | `postal_code` | str | Code postal |
76
- | `city` | str | Localité |
77
- | `photo` | str | Photo en base64 (si `photo=True`) |
78
-
79
- ### Activer les logs
80
-
81
- ```python
82
- import logging
83
- logging.basicConfig(level=logging.DEBUG)
84
- ```
85
-
86
- ## Dépendances
87
-
88
- - `pyscard`
89
-
90
- ## Tests
91
-
92
- ```bash
93
- pip install -e ".[dev]"
94
- pytest # tous les tests (matériel skippé si absent)
95
- pytest tests/test_parser.py # tests sans matériel uniquement
96
- ```
97
-
98
- ## Contribuer
99
-
100
- Les contributions et améliorations sont les bienvenues !
101
-
102
- ## Licence
103
-
104
- Ce projet est sous licence MIT. Voir le fichier `LICENSE` pour plus de détails.
1
+ Metadata-Version: 2.4
2
+ Name: pythonbeid
3
+ Version: 0.3.0
4
+ Summary: Un module pour lire les informations des cartes d'identité belges
5
+ Author-email: Fabien Toune <fabien.toune@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Lapin-Blanc/pythonbeid
8
+ Project-URL: Bug Tracker, https://github.com/Lapin-Blanc/pythonbeid/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Topic :: Security
12
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: pyscard
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest; extra == "dev"
19
+ Requires-Dist: pytest-cov; extra == "dev"
20
+ Requires-Dist: build; extra == "dev"
21
+ Requires-Dist: twine; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+
25
+ # PythonBEID
26
+
27
+ PythonBEID est un module Python pour lire les informations essentielles des cartes d'identité belge à l'aide d'un lecteur de cartes PC/SC et de la bibliothèque `pyscard`.
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ pip install pythonbeid
33
+ ```
34
+
35
+ ## Utilisation
36
+
37
+ ```python
38
+ from pythonbeid import CardReader, NoReaderError, NoCardError
39
+
40
+ try:
41
+ with CardReader() as cr: # context manager — ferme proprement la connexion
42
+ info = cr.read_informations(photo=False)
43
+ print(info["last_name"]) # Smith
44
+ print(info["birth_date"]) # datetime(1990, 1, 1)
45
+ except NoReaderError:
46
+ print("Aucun lecteur de carte détecté.")
47
+ except NoCardError:
48
+ print("Aucune carte dans le lecteur.")
49
+ ```
50
+
51
+ Si plusieurs lecteurs sont connectés, précisez l'index :
52
+
53
+ ```python
54
+ with CardReader(reader_index=1) as cr:
55
+ info = cr.read_informations()
56
+ ```
57
+
58
+ ### Champs retournés par `read_informations()`
59
+
60
+ | Clé | Type | Description |
61
+ |---|---|---|
62
+ | `card_number` | str | Numéro de la carte |
63
+ | `validity_start` | datetime | Date début de validité |
64
+ | `validity_end` | datetime | Date fin de validité |
65
+ | `issuing_municipality` | str | Commune de délivrance |
66
+ | `national_number` | str | Numéro national |
67
+ | `last_name` | str | Nom de famille |
68
+ | `first_names` | str | Prénom(s) |
69
+ | `suffix` | str | Suffixe de nom |
70
+ | `nationality` | str | Nationalité |
71
+ | `birth_place` | str | Lieu de naissance |
72
+ | `birth_date` | datetime | Date de naissance |
73
+ | `sex` | str | Sexe |
74
+ | `address` | str | Adresse |
75
+ | `postal_code` | str | Code postal |
76
+ | `city` | str | Localité |
77
+ | `photo` | str | Photo en base64 (si `photo=True`) |
78
+
79
+ ### Activer les logs
80
+
81
+ ```python
82
+ import logging
83
+ logging.basicConfig(level=logging.DEBUG)
84
+ ```
85
+
86
+ ## Dépendances
87
+
88
+ - `pyscard`
89
+
90
+ ## Tests
91
+
92
+ ```bash
93
+ pip install -e ".[dev]"
94
+ pytest # tous les tests (matériel skippé si absent)
95
+ pytest tests/test_parser.py # tests sans matériel uniquement
96
+ ```
97
+
98
+ ## Contribuer
99
+
100
+ Les contributions et améliorations sont les bienvenues !
101
+
102
+ ## Licence
103
+
104
+ Ce projet est sous licence MIT. Voir le fichier `LICENSE` pour plus de détails.
@@ -0,0 +1,9 @@
1
+ pythonbeid/__init__.py,sha256=8KzyXHkCdzubZwUfXJx5FimpnxCx0InbZnHg48adiu0,339
2
+ pythonbeid/card_reader.py,sha256=U8Z6PfyKdPQO1_2CX-CEVRxaUJBp8od5bE-iWvuX8LU,11133
3
+ pythonbeid/exceptions.py,sha256=Bhn0q4n88UqVYY01gd11jQ779q2XO2ZpEAeJx-J0_8U,758
4
+ pythonbeid/parser.py,sha256=uq5aEnvEC5vcFo1I4jO7pNQK4McGziburbUK-MEHolg,2537
5
+ pythonbeid-0.3.0.dist-info/licenses/LICENSE,sha256=VOOj3rL3m3LyHxJOvzfNxWbRhDeBfzne6GKYwypfvxA,1069
6
+ pythonbeid-0.3.0.dist-info/METADATA,sha256=KJ1PE87C2FDwtMTWuhKO5uXYvTBzLI8xDdSv8njrF4U,2974
7
+ pythonbeid-0.3.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
8
+ pythonbeid-0.3.0.dist-info/top_level.txt,sha256=-Uw6t8lKuiCAYujzrtgkiyiNdngHathGf-Nh0EVwHc4,11
9
+ pythonbeid-0.3.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (82.0.0)
2
+ Generator: setuptools (82.0.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Fabien Toune
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Fabien Toune
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,9 +0,0 @@
1
- pythonbeid/__init__.py,sha256=gfglDkvri8Gh2ixRUY_6KOVQ1UAUSfGuy1nBdJswOPg,305
2
- pythonbeid/card_reader.py,sha256=UCo-2FehvCyIx1jQu3fkATD8kapUtSH8s8wNtxMNNE4,11070
3
- pythonbeid/exceptions.py,sha256=BS06iT3v5FbGFTEZBjkdCZ9A2nCWPLPf8lmYh_cz5Fo,820
4
- pythonbeid/parser.py,sha256=TyFzpj5sfu3J9w1sxt96j1Xr4gK7INC5a4VFaZCIyyA,2711
5
- pythonbeid-0.2.0.dist-info/licenses/LICENSE,sha256=8xOq3W-9w8IgGAWBbKMFTcX3fMQCV4YmgQsvC14CTPE,1090
6
- pythonbeid-0.2.0.dist-info/METADATA,sha256=UDm9o_DqulBCyk4WKpXV8XNCqxR4ALG28ZzfZLqJiRg,3078
7
- pythonbeid-0.2.0.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
8
- pythonbeid-0.2.0.dist-info/top_level.txt,sha256=-Uw6t8lKuiCAYujzrtgkiyiNdngHathGf-Nh0EVwHc4,11
9
- pythonbeid-0.2.0.dist-info/RECORD,,