Search in sources :

Example 6 with CardException

use of javax.smartcardio.CardException in project jmulticard by ctt-gob-es.

the class SmartcardIoConnection method getTerminals.

/**
 * {@inheritDoc}
 */
@Override
public long[] getTerminals(final boolean onlyWithCardPresent) throws ApduConnectionException {
    final List<CardTerminal> terminales;
    try {
        terminales = TerminalFactory.getDefault().terminals().list();
    } catch (final CardException e) {
        // $NON-NLS-1$
        LOGGER.warning("No se ha podido recuperar la lista de lectores del sistema: " + e);
        return new long[0];
    }
    try {
        // Listamos los indices de los lectores que correspondan segun si tienen o no tarjeta insertada
        final ArrayList<Long> idsTerminales = new ArrayList<>(terminales.size());
        for (int idx = 0; idx < terminales.size(); idx++) {
            if (onlyWithCardPresent) {
                if (terminales.get(idx).isCardPresent()) {
                    idsTerminales.add(Long.valueOf(idx));
                }
            } else {
                idsTerminales.add(Long.valueOf(idx));
            }
        }
        final long[] ids = new long[idsTerminales.size()];
        for (int i = 0; i < ids.length; i++) {
            ids[i] = idsTerminales.get(i).longValue();
        }
        return ids;
    } catch (final Exception ex) {
        throw new ApduConnectionException(// $NON-NLS-1$
        "Error recuperando la lista de lectores de tarjetas del sistema: " + ex, // $NON-NLS-1$
        ex);
    }
}
Also used : ArrayList(java.util.ArrayList) CardTerminal(javax.smartcardio.CardTerminal) CardException(javax.smartcardio.CardException) CardNotPresentException(es.gob.jmulticard.apdu.connection.CardNotPresentException) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException) CardException(javax.smartcardio.CardException) ApduConnectionOpenedInExclusiveModeException(es.gob.jmulticard.apdu.connection.ApduConnectionOpenedInExclusiveModeException) NoReadersFoundException(es.gob.jmulticard.apdu.connection.NoReadersFoundException) LostChannelException(es.gob.jmulticard.apdu.connection.LostChannelException) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException)

Example 7 with CardException

use of javax.smartcardio.CardException in project jmulticard by ctt-gob-es.

the class SmartcardIoConnection method transmit.

/**
 * {@inheritDoc}
 */
@Override
public ResponseApdu transmit(final CommandApdu command) throws ApduConnectionException {
    if (this.canal == null) {
        throw new ApduConnectionException(// $NON-NLS-1$
        "No se puede transmitir sobre una conexion cerrada");
    }
    if (command == null) {
        throw new IllegalArgumentException(// $NON-NLS-1$
        "No se puede transmitir una APDU nula");
    }
    if (DEBUG) {
        // $NON-NLS-1$
        Logger.getLogger("es.gob.jmulticard").info(// $NON-NLS-1$
        "Enviada APDU:\n" + HexUtils.hexify(command.getBytes(), true));
    }
    try {
        byte[] sendApdu;
        if (command.getData() != null) {
            // Si la APDU es mayor que 0xFF la troceamos y la envolvemos
            if (command.getData().length > 0xFF) {
                int sentLength = 0;
                final int totalLength = command.getBytes().length;
                final int CONTENT_SIZE_ENVELOPE = 250;
                while (totalLength - sentLength > CONTENT_SIZE_ENVELOPE) {
                    final byte[] apduChunk = Arrays.copyOfRange(command.getBytes(), sentLength, sentLength + CONTENT_SIZE_ENVELOPE);
                    final CommandAPDU apdu = new CommandAPDU((byte) 0x90, (byte) 0xC2, (byte) 0x00, (byte) 0x00, apduChunk);
                    final ResponseApdu response = new ResponseApdu(this.canal.transmit(apdu).getBytes());
                    if (!response.isOk()) {
                        return response;
                    }
                    sentLength += CONTENT_SIZE_ENVELOPE;
                }
                final byte[] apduChunk = Arrays.copyOfRange(command.getBytes(), sentLength, totalLength);
                sendApdu = new CommandAPDU((byte) 0x90, (byte) 0xC2, (byte) 0x00, (byte) 0x00, apduChunk).getBytes();
            } else // Si es pequena, se envia directamente
            {
                sendApdu = command.getBytes();
            }
        } else {
            sendApdu = command.getBytes();
        }
        final ResponseApdu response = new ResponseApdu(this.canal.transmit(new CommandAPDU(sendApdu)).getBytes());
        // Solicitamos el resultado de la operacion si es necesario
        if (response.getStatusWord().getMsb() == TAG_RESPONSE_PENDING) {
            // Si ya se ha devuelto parte de los datos, los concatenamos al resultado
            if (response.getData().length > 0) {
                final byte[] data = response.getData();
                final byte[] additionalData = transmit(new GetResponseApduCommand((byte) 0x00, response.getStatusWord().getLsb())).getBytes();
                final byte[] fullResponse = new byte[data.length + additionalData.length];
                System.arraycopy(data, 0, fullResponse, 0, data.length);
                System.arraycopy(additionalData, 0, fullResponse, data.length, additionalData.length);
                return new ResponseApdu(fullResponse);
            }
            return transmit(new GetResponseApduCommand((byte) 0x00, response.getStatusWord().getLsb()));
        } else // (de eso se encargara la clase de conexion con canal seguro)
        if (response.getStatusWord().getMsb() == TAG_RESPONSE_INVALID_LENGTH && command.getCla() == (byte) 0x00) {
            command.setLe(response.getStatusWord().getLsb());
            return transmit(command);
        }
        if (DEBUG) {
            // $NON-NLS-1$
            Logger.getLogger("es.gob.jmulticard").info(// $NON-NLS-1$
            "Respuesta:\n" + HexUtils.hexify(response.getBytes(), true));
        }
        return response;
    } catch (final CardException e) {
        final Throwable t = e.getCause();
        if (t != null && SCARD_W_RESET_CARD.equals(t.getMessage())) {
            throw new LostChannelException(t.getMessage());
        }
        throw new ApduConnectionException(// $NON-NLS-1$
        "Error de comunicacion con la tarjeta tratando de transmitir la APDU " + HexUtils.hexify(command.getBytes(), true) + " al lector " + // $NON-NLS-1$
        Integer.toString(this.terminalNumber) + // $NON-NLS-1$
        " en modo EXCLUSIVE=" + Boolean.toString(this.exclusive) + " con el protocolo " + // $NON-NLS-1$
        this.protocol.toString(), // $NON-NLS-1$
        e);
    } catch (final Exception e) {
        e.printStackTrace();
        throw new ApduConnectionException(// $NON-NLS-1$
        "Error tratando de transmitir la APDU " + HexUtils.hexify(command.getBytes(), true) + " al lector " + // $NON-NLS-1$
        Integer.toString(this.terminalNumber) + // $NON-NLS-1$
        " en modo EXCLUSIVE=" + Boolean.toString(this.exclusive) + " con el protocolo " + // $NON-NLS-1$
        this.protocol.toString(), // $NON-NLS-1$
        e);
    }
}
Also used : LostChannelException(es.gob.jmulticard.apdu.connection.LostChannelException) ResponseApdu(es.gob.jmulticard.apdu.ResponseApdu) GetResponseApduCommand(es.gob.jmulticard.apdu.iso7816four.GetResponseApduCommand) CardException(javax.smartcardio.CardException) CommandAPDU(javax.smartcardio.CommandAPDU) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException) CardNotPresentException(es.gob.jmulticard.apdu.connection.CardNotPresentException) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException) CardException(javax.smartcardio.CardException) ApduConnectionOpenedInExclusiveModeException(es.gob.jmulticard.apdu.connection.ApduConnectionOpenedInExclusiveModeException) NoReadersFoundException(es.gob.jmulticard.apdu.connection.NoReadersFoundException) LostChannelException(es.gob.jmulticard.apdu.connection.LostChannelException)

Example 8 with CardException

use of javax.smartcardio.CardException in project open-ecard by ecsec.

the class PCSCTest method PCSCTest.

@Test(enabled = false)
public void PCSCTest() {
    connect();
    byte[] selectmf = new byte[] { (byte) 0x00, (byte) 0xA4, (byte) 0x00, (byte) 0x0C, (byte) 0x02, (byte) 0x3F, (byte) 0x00 };
    try {
        logger.info("Send APDU {}", ByteUtils.toHexString(selectmf));
        ResponseAPDU response = connection.transmit(new CommandAPDU(selectmf));
        logger.info("Receive APDU {}", ByteUtils.toHexString(response.getBytes()));
    } catch (CardException ex) {
        logger.error(ex.getMessage(), ex);
    }
}
Also used : ResponseAPDU(javax.smartcardio.ResponseAPDU) CardException(javax.smartcardio.CardException) CommandAPDU(javax.smartcardio.CommandAPDU) Test(org.testng.annotations.Test)

Example 9 with CardException

use of javax.smartcardio.CardException in project open-ecard by ecsec.

the class PCSCChannel method transmit.

@Override
public CardResponseAPDU transmit(byte[] command) throws SCIOException {
    try {
        CommandAPDU convertCommand = new CommandAPDU(command);
        ResponseAPDU response = channel.transmit(convertCommand);
        return new CardResponseAPDU(response.getBytes());
    } catch (CardException ex) {
        String msg = "Failed to transmit APDU to the card in terminal '%s'.";
        throw new SCIOException(String.format(msg, card.getTerminal().getName()), getCode(ex), ex);
    }
}
Also used : SCIOException(org.openecard.common.ifd.scio.SCIOException) ResponseAPDU(javax.smartcardio.ResponseAPDU) CardResponseAPDU(org.openecard.common.apdu.common.CardResponseAPDU) CardException(javax.smartcardio.CardException) CardCommandAPDU(org.openecard.common.apdu.common.CardCommandAPDU) CommandAPDU(javax.smartcardio.CommandAPDU) CardResponseAPDU(org.openecard.common.apdu.common.CardResponseAPDU)

Aggregations

CardException (javax.smartcardio.CardException)9 CardTerminal (javax.smartcardio.CardTerminal)6 ApduConnectionException (es.gob.jmulticard.apdu.connection.ApduConnectionException)3 ApduConnectionOpenedInExclusiveModeException (es.gob.jmulticard.apdu.connection.ApduConnectionOpenedInExclusiveModeException)3 CardNotPresentException (es.gob.jmulticard.apdu.connection.CardNotPresentException)3 LostChannelException (es.gob.jmulticard.apdu.connection.LostChannelException)3 NoReadersFoundException (es.gob.jmulticard.apdu.connection.NoReadersFoundException)3 Card (javax.smartcardio.Card)3 CommandAPDU (javax.smartcardio.CommandAPDU)3 CardChannel (javax.smartcardio.CardChannel)2 ResponseAPDU (javax.smartcardio.ResponseAPDU)2 SCIOException (org.openecard.common.ifd.scio.SCIOException)2 ResponseApdu (es.gob.jmulticard.apdu.ResponseApdu)1 GetResponseApduCommand (es.gob.jmulticard.apdu.iso7816four.GetResponseApduCommand)1 ArrayList (java.util.ArrayList)1 CardTerminals (javax.smartcardio.CardTerminals)1 CardCommandAPDU (org.openecard.common.apdu.common.CardCommandAPDU)1 CardResponseAPDU (org.openecard.common.apdu.common.CardResponseAPDU)1 SCIOErrorCode (org.openecard.common.ifd.scio.SCIOErrorCode)1 SCIOTerminal (org.openecard.common.ifd.scio.SCIOTerminal)1