Search in sources :

Example 11 with ApduConnectionException

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

the class Ceres 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 CeresPrivateKeyReference)) {
        throw new IllegalArgumentException(// $NON-NLS-1$
        "La clave proporcionada debe ser de tipo CeresPrivateKeyReference, pero se ha recibido de tipo " + keyRef.getClass().getName());
    }
    final CeresPrivateKeyReference ceresPrivateKey = (CeresPrivateKeyReference) 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);
        }
    }
    final byte[] digestInfo;
    try {
        digestInfo = DigestInfo.encode(algorithm, data, this.cryptoHelper);
    } catch (final Exception e) {
        throw new CryptoCardException(// $NON-NLS-1$ //$NON-NLS-2$
        "Error creando el DigestInfo para la firma con el algoritmo " + algorithm + ": " + e, // $NON-NLS-1$ //$NON-NLS-2$
        e);
    }
    loadData(ceresPrivateKey.getKeyBitSize(), digestInfo);
    final ResponseApdu res;
    final CommandApdu cmd = new SignDataApduCommand(// Referencia
    ceresPrivateKey.getKeyReference(), // Tamano en bits de la clave
    ceresPrivateKey.getKeyBitSize());
    try {
        res = sendArbitraryApdu(cmd);
    } catch (final Exception e) {
        // $NON-NLS-1$
        throw new CryptoCardException("Error firmando los datos: " + e, e);
    }
    if (!res.isOk()) {
        throw new CryptoCardException(// $NON-NLS-1$
        "No se han podido firmar los datos. Respuesta: " + HexUtils.hexify(res.getBytes(), true));
    }
    return res.getData();
}
Also used : CommandApdu(es.gob.jmulticard.apdu.CommandApdu) ResponseApdu(es.gob.jmulticard.apdu.ResponseApdu) SignDataApduCommand(es.gob.jmulticard.apdu.ceres.SignDataApduCommand) CryptoCardException(es.gob.jmulticard.card.CryptoCardException) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) AuthenticationModeLockedException(es.gob.jmulticard.card.AuthenticationModeLockedException) FileNotFoundException(es.gob.jmulticard.card.iso7816four.FileNotFoundException) CryptoCardException(es.gob.jmulticard.card.CryptoCardException) InvalidCardException(es.gob.jmulticard.card.InvalidCardException) BadPinException(es.gob.jmulticard.card.BadPinException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) PinException(es.gob.jmulticard.card.PinException) TlvException(es.gob.jmulticard.asn1.TlvException) Iso7816FourCardException(es.gob.jmulticard.card.iso7816four.Iso7816FourCardException) Asn1Exception(es.gob.jmulticard.asn1.Asn1Exception)

Example 12 with ApduConnectionException

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

the class Ceres method verifyPin.

@Override
public void verifyPin(final PasswordCallback pinPc) throws ApduConnectionException, PinException {
    if (pinPc == null) {
        // $NON-NLS-1$
        throw new PinException("No se ha establecido un PasswordCallback");
    }
    final CommandApdu chv = new CeresVerifyApduCommand(CLA, pinPc);
    final ResponseApdu verifyResponse = sendArbitraryApdu(chv);
    if (!verifyResponse.isOk()) {
        if (verifyResponse.getStatusWord().getMsb() == ERROR_PIN_SW1 || verifyResponse.getStatusWord().getMsb() == ERROR_PIN_SW2) {
            if (AUTO_RETRY) {
                this.passwordCallback = null;
                verifyPin(getInternalPasswordCallback());
                return;
            }
            throw new BadPinException(verifyResponse.getStatusWord().getLsb() - (byte) 0xC0);
        } else if (new StatusWord((byte) 0x69, (byte) 0x83).equals(verifyResponse.getStatusWord())) {
            throw new AuthenticationModeLockedException();
        }
        throw new ApduConnectionException(new Iso7816FourCardException(// $NON-NLS-1$ //$NON-NLS-2$
        "Error en la verificacion de PIN (" + verifyResponse.getStatusWord() + ")", verifyResponse.getStatusWord()));
    }
}
Also used : AuthenticationModeLockedException(es.gob.jmulticard.card.AuthenticationModeLockedException) Iso7816FourCardException(es.gob.jmulticard.card.iso7816four.Iso7816FourCardException) CommandApdu(es.gob.jmulticard.apdu.CommandApdu) CeresVerifyApduCommand(es.gob.jmulticard.apdu.ceres.CeresVerifyApduCommand) BadPinException(es.gob.jmulticard.card.BadPinException) StatusWord(es.gob.jmulticard.apdu.StatusWord) ResponseApdu(es.gob.jmulticard.apdu.ResponseApdu) BadPinException(es.gob.jmulticard.card.BadPinException) PinException(es.gob.jmulticard.card.PinException) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException)

Example 13 with ApduConnectionException

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

the class SmartCafePkcs15Applet method verifyPin.

@Override
public void verifyPin(final PasswordCallback psc) throws ApduConnectionException, PinException {
    if (psc == null) {
        throw new IllegalArgumentException(// $NON-NLS-1$
        "No se puede verificar el titular con un PasswordCallback nulo");
    }
    VerifyApduCommand verifyCommandApdu = new VerifyApduCommand(psc);
    final ResponseApdu verifyResponse = getConnection().transmit(verifyCommandApdu);
    verifyCommandApdu = null;
    if (!verifyResponse.isOk()) {
        if (verifyResponse.getStatusWord().getMsb() == ERROR_PIN_SW1) {
            throw new BadPinException(verifyResponse.getStatusWord().getLsb() - (byte) 0xC0);
        } else if (verifyResponse.getStatusWord().getMsb() == (byte) 0x69 && verifyResponse.getStatusWord().getLsb() == (byte) 0x83) {
            throw new AuthenticationModeLockedException();
        } else {
            throw new ApduConnectionException(new Iso7816FourCardException(// $NON-NLS-1$ //$NON-NLS-2$
            "Error en la verificacion de PIN (" + verifyResponse.getStatusWord() + ")", verifyResponse.getStatusWord()));
        }
    }
}
Also used : AuthenticationModeLockedException(es.gob.jmulticard.card.AuthenticationModeLockedException) Iso7816FourCardException(es.gob.jmulticard.card.iso7816four.Iso7816FourCardException) BadPinException(es.gob.jmulticard.card.BadPinException) ResponseApdu(es.gob.jmulticard.apdu.ResponseApdu) VerifyApduCommand(es.gob.jmulticard.apdu.gide.VerifyApduCommand) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException)

Example 14 with ApduConnectionException

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

the class SmartCafePkcs15Applet method preloadCertificates.

private void preloadCertificates() throws FileNotFoundException, Iso7816FourCardException, IOException, Asn1Exception, TlvException {
    selectMasterFile();
    // Seleccionamos el ODF, no nos devuelve FCI ni nada
    selectFileById(ODF_PATH);
    // Leemos el ODF
    final byte[] odfBytes = readBinaryComplete(162);
    final Odf odf = new Odf();
    odf.setDerValue(odfBytes);
    // Sacamos del ODF la ruta del CDF
    final Path cdfPath = odf.getCdfPath();
    // Leemos el CDF
    final Cdf cdf = new Cdf();
    try {
        selectMasterFile();
        final byte[] cdfBytes = selectFileByIdAndRead(cdfPath.getPathBytes());
        cdf.setDerValue(cdfBytes);
    } catch (final Exception e) {
        throw new ApduConnectionException(// $NON-NLS-1$
        "No se ha podido cargar el CDF de la tarjeta: " + e, // $NON-NLS-1$
        e);
    }
    final CertificateFactory cf;
    try {
        // $NON-NLS-1$
        cf = CertificateFactory.getInstance("X.509");
    } catch (final CertificateException e) {
        // $NON-NLS-1$
        throw new IOException("Error obteniendo la factoria de certificados X.509: " + e, e);
    }
    if (cdf.getCertificateCount() < 1) {
        // $NON-NLS-1$
        LOGGER.warning("La tarjeta no contiene ningun certificado");
    }
    for (int i = 0; i < cdf.getCertificateCount(); i++) {
        try {
            int fileLength = -1;
            Location certLocation = new Location(cdf.getCertificatePath(i));
            while (certLocation != null) {
                final byte[] id = certLocation.getFile();
                try {
                    fileLength = selectFileById(id);
                } catch (final FileNotFoundException e) {
                    System.out.println(// $NON-NLS-1$//$NON-NLS-2$
                    "El CDF indicaba un certificado en la ruta '" + certLocation + "', pero un elemento de esta no existe, se ignorara: " + e);
                }
                certLocation = certLocation.getChild();
            }
            final byte[] certBytes;
            if (fileLength > 0) {
                certBytes = readBinaryComplete(fileLength);
            } else {
                // A veces hay punteros que apuntan a localizaciones vacias
                LOGGER.warning(// $NON-NLS-1$ //$NON-NLS-2$
                "El certificado " + i + " del dispositivo esta vacio");
                continue;
            }
            CERTS_BY_ALIAS.put(cdf.getCertificateAlias(i), (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certBytes)));
        } catch (final Exception e) {
            // Puede darse el caso de que el puntero apunte a algo que no es un certificado
            LOGGER.severe(// $NON-NLS-1$ //$NON-NLS-2$
            "Error en la lectura del certificado " + i + " del dispositivo: " + e);
            continue;
        }
    }
}
Also used : Path(es.gob.jmulticard.asn1.der.pkcs15.Path) Cdf(es.gob.jmulticard.asn1.der.pkcs15.Cdf) FileNotFoundException(es.gob.jmulticard.card.iso7816four.FileNotFoundException) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) AuthenticationModeLockedException(es.gob.jmulticard.card.AuthenticationModeLockedException) FileNotFoundException(es.gob.jmulticard.card.iso7816four.FileNotFoundException) BadPinException(es.gob.jmulticard.card.BadPinException) PinException(es.gob.jmulticard.card.PinException) Iso7816FourCardException(es.gob.jmulticard.card.iso7816four.Iso7816FourCardException) Asn1Exception(es.gob.jmulticard.asn1.Asn1Exception) CryptoCardException(es.gob.jmulticard.card.CryptoCardException) InvalidCardException(es.gob.jmulticard.card.InvalidCardException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) TlvException(es.gob.jmulticard.asn1.TlvException) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException) Odf(es.gob.jmulticard.asn1.der.pkcs15.Odf) ByteArrayInputStream(java.io.ByteArrayInputStream) Location(es.gob.jmulticard.card.Location)

Example 15 with ApduConnectionException

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

the class CeresSc method openSecureChannelIfNotAlreadyOpened.

/**
 * Establece y abre el canal seguro CWA-14890 si no lo estaba ya hecho.
 * @throws CryptoCardException Si hay problemas en el proceso.
 * @throws PinException Si el PIN usado para la apertura de canal no es v&aacute;lido o no se ha proporcionado
 * 						un PIN para validar.
 */
@Override
protected void openSecureChannelIfNotAlreadyOpened() throws CryptoCardException, PinException {
    // Abrimos el canal seguro si no lo esta ya
    if (!isSecurityChannelOpen()) {
        // Aunque el canal seguro estuviese cerrado, podria si estar enganchado
        if (!(getConnection() instanceof Cwa14890Connection)) {
            final ApduConnection secureConnection;
            secureConnection = new Cwa14890OneV2Connection(this, getConnection(), this.cryptoHelper, getCwa14890PublicConstants(), getCwa14890PrivateConstants());
            try {
                setConnection(secureConnection);
            } catch (final ApduConnectionException e) {
                // $NON-NLS-1$
                throw new CryptoCardException("Error en el establecimiento del canal seguro: " + e, e);
            }
        }
        try {
            verifyPin(getInternalPasswordCallback());
        } catch (final ApduConnectionException e) {
            // $NON-NLS-1$
            throw new CryptoCardException("Error en la apertura del canal seguro: " + e, e);
        }
    }
}
Also used : Cwa14890Connection(es.gob.jmulticard.apdu.connection.cwa14890.Cwa14890Connection) Cwa14890OneV2Connection(es.gob.jmulticard.apdu.connection.cwa14890.Cwa14890OneV2Connection) ApduConnection(es.gob.jmulticard.apdu.connection.ApduConnection) CryptoCardException(es.gob.jmulticard.card.CryptoCardException) 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