Smartcard library for Python providing PC/SC interface for smart card communication
npx @tessl/cli install tessl/pypi-pyscard@2.3.00
# pyscard
1
2
A comprehensive Python library for interacting with smart cards through the PC/SC (Personal Computer/Smart Card) interface. pyscard provides both high-level and low-level APIs for smart card communication, enabling developers to build applications that can read from and write to smart cards across multiple platforms (Windows, macOS, Linux).
3
4
## Package Information
5
6
- **Package Name**: pyscard
7
- **Language**: Python
8
- **Installation**: `pip install pyscard`
9
- **Python Requires**: >=3.9
10
- **Platforms**: Windows, macOS, Linux
11
12
## Core Imports
13
14
```python
15
import smartcard
16
```
17
18
Common high-level usage:
19
20
```python
21
from smartcard import Session
22
from smartcard.System import readers
23
```
24
25
For monitoring and events:
26
27
```python
28
from smartcard.CardMonitoring import CardMonitor, CardObserver
29
from smartcard.ReaderMonitoring import ReaderMonitor, ReaderObserver
30
```
31
32
For low-level PC/SC access:
33
34
```python
35
from smartcard import scard
36
```
37
38
## Basic Usage
39
40
### Simple Card Communication
41
42
```python
43
from smartcard import Session
44
45
# Create a session with the first available reader
46
session = Session()
47
48
# Send an APDU command (select telecom directory)
49
SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02]
50
DF_TELECOM = [0x7F, 0x10]
51
response, sw1, sw2 = session.sendCommandAPDU(SELECT + DF_TELECOM)
52
53
print(f"Response: {response}")
54
print(f"Status Words: {sw1:02X} {sw2:02X}")
55
56
# Clean up
57
session.close()
58
```
59
60
### Card Detection and Monitoring
61
62
```python
63
from smartcard.CardMonitoring import CardMonitor, CardObserver
64
from smartcard.util import toHexString
65
66
class MyCardObserver(CardObserver):
67
def update(self, observable, actions):
68
(addedcards, removedcards) = actions
69
for card in addedcards:
70
print(f"Card inserted: {toHexString(card.atr)}")
71
for card in removedcards:
72
print(f"Card removed: {toHexString(card.atr)}")
73
74
# Start monitoring
75
monitor = CardMonitor()
76
observer = MyCardObserver()
77
monitor.addObserver(observer)
78
79
# Monitor will continue until program exits
80
```
81
82
### Reader Management
83
84
```python
85
from smartcard.System import readers
86
87
# List all available readers
88
reader_list = readers()
89
for reader in reader_list:
90
print(f"Reader: {reader}")
91
92
# Get reader names as strings (legacy)
93
reader_names = smartcard.listReaders()
94
for name in reader_names:
95
print(f"Reader name: {name}")
96
```
97
98
## Architecture
99
100
pyscard provides a layered architecture for smart card access:
101
102
- **High-level Session API**: Simple APDU communication via `Session` class
103
- **Framework Layer**: Card requests, connections, services, and monitoring
104
- **PC/SC Layer**: Direct access to PC/SC functions through `scard` module
105
- **Utility Layer**: Data conversion, formatting, and helper functions
106
- **GUI Components**: wxPython-based visual components (optional)
107
108
The library handles platform-specific PC/SC implementations automatically (WinSCard on Windows, PCSC-Lite on Unix-like systems).
109
110
## Capabilities
111
112
### High-Level Session API
113
114
Simple card communication interface providing session management and APDU transmission without requiring detailed knowledge of PC/SC or card connection management.
115
116
```python { .api }
117
class Session:
118
def __init__(self, readerName=None): ...
119
def close(self): ...
120
def sendCommandAPDU(self, command): ...
121
def getATR(self): ...
122
123
def listReaders(): ...
124
```
125
126
[Session API](./session-api.md)
127
128
### Card Request and Connection Management
129
130
Framework for waiting for card insertion, establishing connections, and managing card communication with fine-grained control over protocols and connection modes.
131
132
```python { .api }
133
class CardRequest:
134
def __init__(self, newcardonly=False, readers=None, cardType=None, cardServiceClass=None, timeout=1): ...
135
def waitforcard(self): ...
136
def waitforcardevent(self): ...
137
138
class CardConnection:
139
def connect(self, protocol=None, mode=None, disposition=None): ...
140
def transmit(self, command, protocol=None): ...
141
def getATR(self): ...
142
```
143
144
[Card Connections](./card-connections.md)
145
146
### Card and Reader Monitoring
147
148
Event-driven monitoring system for detecting card insertion/removal and reader connection/disconnection with observer pattern implementation.
149
150
```python { .api }
151
class CardMonitor:
152
def addObserver(self, observer): ...
153
def deleteObserver(self, observer): ...
154
155
class CardObserver:
156
def update(self, observable, handlers): ...
157
158
class ReaderMonitor:
159
def __init__(self, startOnDemand=True, readerProc=readers, period=1): ...
160
def addObserver(self, observer): ...
161
```
162
163
[Monitoring](./monitoring.md)
164
165
### ATR Processing and Card Type Detection
166
167
Tools for parsing Answer To Reset (ATR) sequences, extracting card parameters, and implementing card type detection logic.
168
169
```python { .api }
170
class ATR:
171
def __init__(self, atr): ...
172
def getSupportedProtocols(self): ...
173
def getHistoricalBytes(self): ...
174
def isT0Supported(self): ...
175
def isT1Supported(self): ...
176
177
class CardType:
178
def matches(self, atr, reader=None): ...
179
180
class ATRCardType(CardType):
181
def __init__(self, atr, mask=None): ...
182
```
183
184
[ATR and Card Types](./atr-card-types.md)
185
186
### System Reader Management
187
188
Functions for discovering and managing smart card readers, including reader groups and system-level reader operations.
189
190
```python { .api }
191
def readers(groups=None): ...
192
def readergroups(): ...
193
194
class Reader:
195
def __init__(self, readername): ...
196
def createConnection(self): ...
197
```
198
199
[Reader Management](./reader-management.md)
200
201
### Low-Level PC/SC Interface
202
203
Direct access to PC/SC (Personal Computer/Smart Card) functions and constants, providing complete control over smart card operations at the system level.
204
205
```python { .api }
206
# All PC/SC functions and constants available via:
207
from smartcard.scard import *
208
```
209
210
[PC/SC Interface](./pcsc-interface.md)
211
212
### Data Utilities and Formatting
213
214
Comprehensive utility functions for data conversion between different formats (hex strings, byte lists, ASCII), padding operations, and specialized encoding support.
215
216
```python { .api }
217
def toHexString(data, output_format=0): ...
218
def toBytes(bytestring): ...
219
def toASCIIBytes(string): ...
220
def toASCIIString(bytelist): ...
221
def padd(bytelist, length, padding="FF"): ...
222
```
223
224
[Utilities](./utilities.md)
225
226
### Status Word Error Handling
227
228
Structured error checking and exception handling for smart card status words (SW1, SW2) with support for various ISO standards and custom error checking chains.
229
230
```python { .api }
231
class ErrorChecker:
232
def __call__(self, data, sw1, sw2): ...
233
234
class ISO7816_4ErrorChecker(ErrorChecker): ...
235
class ISO7816_8ErrorChecker(ErrorChecker): ...
236
class ISO7816_9ErrorChecker(ErrorChecker): ...
237
238
class SWException(Exception): ...
239
class WarningProcessingException(SWException): ...
240
```
241
242
[Status Word Handling](./status-word-handling.md)
243
244
### GUI Components (Optional)
245
246
wxPython-based graphical user interface components for building smart card applications with visual elements like card/reader trees and APDU trace panels.
247
248
```python { .api }
249
# GUI components available when wxPython is installed
250
from smartcard.wx import SimpleSCardApp, APDUTracerPanel
251
```
252
253
[GUI Components](./gui-components.md)
254
255
## Types
256
257
```python { .api }
258
# Core type aliases used throughout the API
259
ReaderName = str
260
ATRBytes = list[int]
261
APDUCommand = list[int]
262
APDUResponse = list[int]
263
StatusWord = int
264
265
# Protocol constants
266
T0_protocol = 0x00000001
267
T1_protocol = 0x00000002
268
RAW_protocol = 0x00010000
269
T15_protocol = 0x00000008
270
271
# Format constants for utilities
272
PACK = 1
273
HEX = 2
274
UPPERCASE = 4
275
COMMA = 8
276
```