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