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