Search in sources :

Example 31 with ApduConnectionException

use of es.gob.jmulticard.apdu.connection.ApduConnectionException in project jmulticard by ctt-gob-es.

the class Iso7816FourCard method readBinaryComplete.

/**
 * Lee por completo el contenido binario del fichero actualmente seleccionado.
 * @param len Longitud del fichero a leer.
 * @return APDU de respuesta.
 * @throws ApduConnectionException Si hay problemas en el envío de la APDU.
 * @throws IOException Si hay problemas en el <i>buffer</i> de lectura.
 */
public byte[] readBinaryComplete(final int len) throws IOException {
    int off = 0;
    ResponseApdu readedResponse = null;
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    // Leemos en iteraciones de MAX_READ_CHUNK bytes
    while (off < len) {
        final byte msbOffset = (byte) (off >> 8);
        final byte lsbOffset = (byte) (off & 0xFF);
        final int left = len - off;
        try {
            if (left < MAX_READ_CHUNK) {
                // Si es menor que el maximo que podemos leer por iteracion
                readedResponse = readBinary(msbOffset, lsbOffset, (byte) left);
            } else {
                readedResponse = readBinary(msbOffset, lsbOffset, (byte) MAX_READ_CHUNK);
            }
        } catch (final Exception e) {
            LOGGER.warning(// $NON-NLS-1$
            "Se ha intentado una lectura fuera de los limites del fichero, se devolvera lo leido hasta ahora: " + e);
            return out.toByteArray();
        }
        final boolean eofReached = EOF_REACHED.equals(readedResponse.getStatusWord());
        if (!readedResponse.isOk() && !eofReached) {
            // $NON-NLS-1$ //$NON-NLS-2$
            throw new IOException("Error leyendo el binario (" + readedResponse.getStatusWord() + ")");
        }
        out.write(readedResponse.getData());
        off += MAX_READ_CHUNK;
        // Si hemos llegado al final no seguimos leyendo
        if (eofReached) {
            break;
        }
    }
    return out.toByteArray();
}
Also used : ResponseApdu(es.gob.jmulticard.apdu.ResponseApdu) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) SecureChannelException(es.gob.jmulticard.apdu.connection.cwa14890.SecureChannelException) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException) IOException(java.io.IOException) PinException(es.gob.jmulticard.card.PinException)

Example 32 with ApduConnectionException

use of es.gob.jmulticard.apdu.connection.ApduConnectionException in project jmulticard by ctt-gob-es.

the class SmartCafePkcs15Applet method sign.

@Override
public byte[] sign(final byte[] data, final String algorithm, final PrivateKeyReference keyRef) throws CryptoCardException, PinException {
    if (data == null) {
        // $NON-NLS-1$
        throw new CryptoCardException("Los datos a firmar no pueden ser nulos");
    }
    if (keyRef == null) {
        // $NON-NLS-1$
        throw new IllegalArgumentException("La clave privada no puede ser nula");
    }
    if (!(keyRef instanceof SmartCafePrivateKeyReference)) {
        throw new IllegalArgumentException(// $NON-NLS-1$
        "La clave proporcionada debe ser de tipo " + SmartCafePrivateKeyReference.class.getName() + // $NON-NLS-1$
        ", pero se ha recibido de tipo " + keyRef.getClass().getName());
    }
    final SmartCafePrivateKeyReference scPrivateKey = (SmartCafePrivateKeyReference) keyRef;
    // Pedimos el PIN si no se ha pedido antes
    if (!this.authenticated) {
        try {
            verifyPin(getInternalPasswordCallback());
            this.authenticated = true;
        } catch (final ApduConnectionException e1) {
            // $NON-NLS-1$
            throw new CryptoCardException("Error en la verificacion de PIN: " + e1, e1);
        }
    }
    // Enviamos el MSE SET for Computation
    ResponseApdu res = null;
    try {
        res = sendArbitraryApdu(new MseSetComputationApduCommand(// CLA
        (byte) 0x01, new byte[] { (byte) scPrivateKey.getKeyOrdinal() }, // RSA
        new byte[] { (byte) 0x02 }));
    } catch (final ApduConnectionException e) {
        throw new CryptoCardException(// $NON-NLS-1$ //$NON-NLS-2$
        "Error estableciendo la clave y el algoritmo de firma (repuesta=" + res + "): " + e, // $NON-NLS-1$ //$NON-NLS-2$
        e);
    }
    if (res == null || !res.isOk()) {
        throw new CryptoCardException(// $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
        "No se ha podido establecer la clave y el algoritmo de firma" + (res != null ? " (repuesta=" + res + ")" : ""));
    }
    // Creamos el DigestInfo
    final byte[] digestInfo;
    try {
        digestInfo = DigestInfo.encode(algorithm, data, this.cryptoHelper);
    } catch (final IOException e) {
        // $NON-NLS-1$
        throw new CryptoCardException("Error en el calculo de la huella para firmar: " + e, e);
    }
    // Y lo enviamos a firmar
    try {
        res = sendArbitraryApdu(new PsoSignHashApduCommand((byte) 0x01, digestInfo));
    } catch (final ApduConnectionException e) {
        throw new CryptoCardException(// $NON-NLS-1$ //$NON-NLS-2$
        "Error firmando (repuesta=" + res + "): " + e, // $NON-NLS-1$ //$NON-NLS-2$
        e);
    }
    if (res == null || !res.isOk()) {
        throw new CryptoCardException(// $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
        "No se ha podido firmar el DigestInfo" + (res != null ? " (repuesta=" + res + ")" : ""));
    }
    return res.getData();
}
Also used : MseSetComputationApduCommand(es.gob.jmulticard.apdu.iso7816four.MseSetComputationApduCommand) PsoSignHashApduCommand(es.gob.jmulticard.apdu.iso7816eight.PsoSignHashApduCommand) ResponseApdu(es.gob.jmulticard.apdu.ResponseApdu) IOException(java.io.IOException) CryptoCardException(es.gob.jmulticard.card.CryptoCardException) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException)

Example 33 with ApduConnectionException

use of es.gob.jmulticard.apdu.connection.ApduConnectionException in project jmulticard by ctt-gob-es.

the class SmartCafePkcs15Applet method getPinRetriesLeft.

private int getPinRetriesLeft() throws PinException {
    final CommandApdu verifyCommandApdu = new RetriesLeftApduCommand();
    final ResponseApdu verifyResponse;
    try {
        verifyResponse = getConnection().transmit(verifyCommandApdu);
    } catch (final ApduConnectionException e) {
        throw new PinException(// $NON-NLS-1$
        "Error obteniendo el PIN del CallbackHandler: " + e, // $NON-NLS-1$
        e);
    }
    if (verifyResponse.isOk() || verifyResponse.getBytes().length > 2) {
        return verifyResponse.getBytes()[1];
    }
    throw new PinException(// $NON-NLS-1$
    "Error comprobando los intentos restantes de PIN con respuesta: " + HexUtils.hexify(verifyResponse.getBytes(), true));
}
Also used : CommandApdu(es.gob.jmulticard.apdu.CommandApdu) ResponseApdu(es.gob.jmulticard.apdu.ResponseApdu) BadPinException(es.gob.jmulticard.card.BadPinException) PinException(es.gob.jmulticard.card.PinException) RetriesLeftApduCommand(es.gob.jmulticard.apdu.gide.RetriesLeftApduCommand) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException)

Example 34 with ApduConnectionException

use of es.gob.jmulticard.apdu.connection.ApduConnectionException in project jmulticard by ctt-gob-es.

the class TuiR5 method connect.

/**
 * Conecta con el lector del sistema que tenga una TUI insertada.
 * @param conn Conexi&oacute;n hacia la TUI
 * @throws IOException Cuando hay errores de entrada / salida.
 */
private void connect(final ApduConnection conn) throws IOException {
    if (conn == null) {
        // $NON-NLS-1$
        throw new IllegalArgumentException("La conexion no puede ser nula");
    }
    final long[] terminals = conn.getTerminals(false);
    if (terminals.length < 1) {
        throw new NoReadersFoundException();
    }
    byte[] responseAtr;
    Atr actualAtr;
    InvalidCardException invalidCardException = null;
    CardNotPresentException cardNotPresentException = null;
    for (final long terminal : terminals) {
        conn.setTerminal((int) terminal);
        try {
            responseAtr = conn.reset();
        } catch (final CardNotPresentException e) {
            cardNotPresentException = e;
            continue;
        }
        actualAtr = new Atr(responseAtr, ATR_MASK);
        if (!ATR.equals(actualAtr)) {
            // La tarjeta encontrada no es una TUI
            invalidCardException = new InvalidCardException(getCardName(), ATR, responseAtr);
            continue;
        }
        return;
    }
    if (invalidCardException != null) {
        throw invalidCardException;
    }
    if (cardNotPresentException != null) {
        throw cardNotPresentException;
    }
    // $NON-NLS-1$
    throw new ApduConnectionException("No se ha podido conectar con ningun lector de tarjetas");
}
Also used : CardNotPresentException(es.gob.jmulticard.apdu.connection.CardNotPresentException) NoReadersFoundException(es.gob.jmulticard.apdu.connection.NoReadersFoundException) Atr(es.gob.jmulticard.card.Atr) InvalidCardException(es.gob.jmulticard.card.InvalidCardException) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException)

Example 35 with ApduConnectionException

use of es.gob.jmulticard.apdu.connection.ApduConnectionException 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)

Aggregations

ApduConnectionException (es.gob.jmulticard.apdu.connection.ApduConnectionException)38 ResponseApdu (es.gob.jmulticard.apdu.ResponseApdu)21 IOException (java.io.IOException)16 CommandApdu (es.gob.jmulticard.apdu.CommandApdu)14 PinException (es.gob.jmulticard.card.PinException)14 BadPinException (es.gob.jmulticard.card.BadPinException)13 CryptoCardException (es.gob.jmulticard.card.CryptoCardException)13 Iso7816FourCardException (es.gob.jmulticard.card.iso7816four.Iso7816FourCardException)12 CertificateException (java.security.cert.CertificateException)10 AuthenticationModeLockedException (es.gob.jmulticard.card.AuthenticationModeLockedException)9 CardNotPresentException (es.gob.jmulticard.apdu.connection.CardNotPresentException)7 LostChannelException (es.gob.jmulticard.apdu.connection.LostChannelException)7 InvalidCardException (es.gob.jmulticard.card.InvalidCardException)7 NoReadersFoundException (es.gob.jmulticard.apdu.connection.NoReadersFoundException)6 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)6 ApduConnection (es.gob.jmulticard.apdu.connection.ApduConnection)5 Cwa14890Connection (es.gob.jmulticard.apdu.connection.cwa14890.Cwa14890Connection)5 TlvException (es.gob.jmulticard.asn1.TlvException)5 SecureChannelException (es.gob.jmulticard.apdu.connection.cwa14890.SecureChannelException)4 Asn1Exception (es.gob.jmulticard.asn1.Asn1Exception)4