blob: 443381c00b212b6ce50df4a4ca5b50a1f5a6da0f [file] [log] [blame]
Christina Quast31b5b4e2015-03-09 17:15:13 +01001#!/usr/bin/env python
2
3from smartcard.scard import *
4import smartcard.util
5
Christina Quastecfad8f2015-03-10 23:35:11 +01006SELECT = [0xA0, 0xA4, 0x00, 0x00, 0x02, 0x3F, 0x00]
Christina Quast31b5b4e2015-03-09 17:15:13 +01007COMMAND = [0x00, 0x00, 0x00, 0x00]
8
9def select():
10 try:
11 hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
12 if hresult != SCARD_S_SUCCESS:
13 raise Exception('Failed to establish context : ' +
14 SCardGetErrorMessage(hresult))
15 print 'Context established!'
16
17 try:
18 hresult, readers = SCardListReaders(hcontext, [])
19 if hresult != SCARD_S_SUCCESS:
20 raise Exception('Failed to list readers: ' +
21 SCardGetErrorMessage(hresult))
22 print 'PCSC Readers:', readers
23
24 if len(readers) < 1:
25 raise Exception('No smart card readers')
26
27 reader = readers[0]
28 print "Using reader:", reader
29
30 try:
31 hresult, hcard, dwActiveProtocol = SCardConnect(hcontext, reader,
32 SCARD_SHARE_SHARED, SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1)
33 if hresult != SCARD_S_SUCCESS:
34 raise Exception('Unable to connect: ' +
35 SCardGetErrorMessage(hresult))
36 print 'Connected with active protocol', dwActiveProtocol
37
38 try:
39 hresult, response = SCardTransmit(hcard, dwActiveProtocol,
40 SELECT)
41 if hresult != SCARD_S_SUCCESS:
42 raise Exception('Failed to transmit: ' +
43 SCardGetErrorMessage(hresult))
44 print 'Select: ' + smartcard.util.toHexString(response,
45 smartcard.util.HEX)
46 hresult, response = SCardTransmit(hcard, dwActiveProtocol,
47 COMMAND)
48 if hresult != SCARD_S_SUCCESS:
49 raise Exception('Failed to transmit: ' +
50 SCardGetErrorMessage(hresult))
51 print 'Command: ' + smartcard.util.toHexString(response,
52 smartcard.util.HEX)
53 finally:
54 hresult = SCardDisconnect(hcard, SCARD_UNPOWER_CARD)
55 if hresult != SCARD_S_SUCCESS:
56 raise Exception('Failed to disconnect: ' +
57 SCardGetErrorMessage(hresult))
58 print 'Disconnected'
59
60
61 except Exception, message:
62 print "Exception:", message
63
64 finally:
65 hresult = SCardReleaseContext(hcontext)
66 if hresult != SCARD_S_SUCCESS:
67 raise Exception('Failed to release context: ' +
68 SCardGetErrorMessage(hresult))
69 print 'Released context.'
70
71 except Exception, message:
72 print "Exception:", message