Search in sources :

Example 6 with Iso7816FourCardException

use of es.gob.jmulticard.card.iso7816four.Iso7816FourCardException in project jmulticard by ctt-gob-es.

the class TuiR5 method preloadCertificates.

private void preloadCertificates() throws IOException, Iso7816FourCardException {
    selectMasterFile();
    final Cdf cdf = new Cdf();
    try {
        cdf.setDerValue(selectFileByLocationAndRead(CDF_LOCATION));
    } catch (final Exception e) {
        // $NON-NLS-1$
        throw new IOException("Error en la lectura del CDF: " + e, 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);
    }
    for (int i = 0; i < cdf.getCertificateCount(); i++) {
        try {
            certificatesByAlias.put(cdf.getCertificateAlias(i), (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(selectFileByLocationAndRead(new Location(cdf.getCertificatePath(i))))));
        } catch (final CertificateException e) {
            // $NON-NLS-1$ //$NON-NLS-2$
            throw new IOException("Error en la lectura del certificado " + i + " del dispositivo: " + e, e);
        }
    }
}
Also used : Cdf(es.gob.jmulticard.asn1.der.pkcs15.Cdf) ByteArrayInputStream(java.io.ByteArrayInputStream) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException) FileNotFoundException(es.gob.jmulticard.card.iso7816four.FileNotFoundException) CryptoCardException(es.gob.jmulticard.card.CryptoCardException) InvalidCardException(es.gob.jmulticard.card.InvalidCardException) CardNotPresentException(es.gob.jmulticard.apdu.connection.CardNotPresentException) BadPinException(es.gob.jmulticard.card.BadPinException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoReadersFoundException(es.gob.jmulticard.apdu.connection.NoReadersFoundException) Iso7816FourCardException(es.gob.jmulticard.card.iso7816four.Iso7816FourCardException) Location(es.gob.jmulticard.card.Location)

Example 7 with Iso7816FourCardException

use of es.gob.jmulticard.card.iso7816four.Iso7816FourCardException in project jmulticard by ctt-gob-es.

the class Dnie method loadCertificatesInternal.

protected void loadCertificatesInternal() throws CryptoCardException {
    // Cargamos certificados si es necesario
    if (this.authCert == null || this.signCert == null || this.cyphCert == null && this.cyphCertPath != null || this.signAliasCert == null && this.signAliasCertPath != null) {
        try {
            this.signCert = loadCertificate(this.signCertPath);
            this.authCert = loadCertificate(this.authCertPath);
            if (this.cyphCertPath != null) {
                this.cyphCert = loadCertificate(this.cyphCertPath);
            }
            if (this.signAliasCertPath != null) {
                this.signAliasCert = loadCertificate(this.signAliasCertPath);
            }
        } catch (final CertificateException e) {
            throw new CryptoCardException(// $NON-NLS-1$
            "Error al cargar los certificados del DNIe, no es posible obtener una factoria de certificados X.509: " + e, // $NON-NLS-1$
            e);
        } catch (final IOException e) {
            throw new CryptoCardException(// $NON-NLS-1$
            "Error al cargar los certificados del DNIe, error en la descompresion de los datos: " + e, // $NON-NLS-1$
            e);
        } catch (final Iso7816FourCardException e) {
            throw new CryptoCardException(// $NON-NLS-1$
            "Error al cargar los certificados del DNIe: " + e, // $NON-NLS-1$
            e);
        }
    }
}
Also used : Iso7816FourCardException(es.gob.jmulticard.card.iso7816four.Iso7816FourCardException) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CryptoCardException(es.gob.jmulticard.card.CryptoCardException)

Example 8 with Iso7816FourCardException

use of es.gob.jmulticard.card.iso7816four.Iso7816FourCardException in project jmulticard by ctt-gob-es.

the class Dnie 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((byte) 0x00, psc);
    final ResponseApdu verifyResponse = getConnection().transmit(verifyCommandApdu);
    verifyCommandApdu = null;
    // a pedir si es necesario
    if (!verifyResponse.isOk()) {
        if (verifyResponse.getStatusWord().getMsb() == ERROR_PIN_SW1) {
            // Cliente @firma, que derivaria en DNI bloqueado
            if (!PIN_AUTO_RETRY || psc.getClass().getName().endsWith("CachePasswordCallback")) {
                // $NON-NLS-1$
                throw new BadPinException(verifyResponse.getStatusWord().getLsb() - (byte) 0xC0);
            }
            // Si hay reintento automatico volvemos a pedir el PIN con la misma CallBack
            verifyPin(getInternalPasswordCallback());
        } else if (verifyResponse.getStatusWord().getMsb() == (byte) 0x69 && verifyResponse.getStatusWord().getLsb() == (byte) 0x83) {
            throw new AuthenticationModeLockedException();
        } else if (verifyResponse.getStatusWord().getMsb() == (byte) 0x00 && verifyResponse.getStatusWord().getLsb() == (byte) 0x00) {
            // $NON-NLS-1$
            throw new ApduConnectionException("Se ha perdido el canal NFC");
        } 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.dnie.VerifyApduCommand) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException)

Example 9 with Iso7816FourCardException

use of es.gob.jmulticard.card.iso7816four.Iso7816FourCardException in project jmulticard by ctt-gob-es.

the class Ceres method preload.

private void preload() throws ApduConnectionException, Iso7816FourCardException, IOException, CertificateException, Asn1Exception, TlvException {
    // Nos vamos al raiz antes de nada
    selectMasterFile();
    // Leemos el CDF
    final byte[] cdfBytes = selectFileByLocationAndRead(CDF_LOCATION);
    // Cargamos el CDF
    Pkcs15Cdf cdf = new CeresCdf();
    try {
        cdf.setDerValue(cdfBytes);
    } catch (final Exception e) {
        // Si ha fallado la inicializacion del CDF tipo CERES probamos con el CDF generico PKCS#15,
        // presente en las nuevas tarjetas FNMT-CERES
        cdf = new Cdf();
        cdf.setDerValue(cdfBytes);
    }
    // Leemos los certificados segun las rutas del CDF
    this.certs = new LinkedHashMap<>(cdf.getCertificateCount());
    this.aliasByCertAndKeyId = new LinkedHashMap<>(cdf.getCertificateCount());
    for (int i = 0; i < cdf.getCertificateCount(); i++) {
        final Location l = new Location(// $NON-NLS-1$ //$NON-NLS-2$
        cdf.getCertificatePath(i).replace("\\", "").trim());
        X509Certificate cert;
        try {
            cert = CompressionUtils.getCertificateFromCompressedOrNotData(selectFileByLocationAndRead(l));
        } catch (final IOException e) {
            // $NON-NLS-1$
            LOGGER.warning("No se ha encontrado un certificado referenciado, se pasa al siguiente: " + e);
            continue;
        }
        // $NON-NLS-1$
        final String alias = i + " " + cert.getSerialNumber();
        this.aliasByCertAndKeyId.put(HexUtils.hexify(cdf.getCertificateId(i), false), alias);
        this.certs.put(alias, cert);
    }
    // Leemos el PrKDF
    final byte[] prkdfValue = selectFileByLocationAndRead(PRKDF_LOCATION);
    // Establecemos el valor del PrKDF
    Pkcs15PrKdf prkdf = new CeresPrKdf();
    try {
        prkdf.setDerValue(prkdfValue);
    } catch (final Exception e) {
        // Si no carga el estructura PrKDF especifica de CERES probamos con la
        // generica PKCS#15, presente en las ultimas versiones de la tarjeta
        prkdf = new PrKdf();
        prkdf.setDerValue(prkdfValue);
    }
    this.keys = new LinkedHashMap<>();
    for (int i = 0; i < prkdf.getKeyCount(); i++) {
        final String alias = this.aliasByCertAndKeyId.get(HexUtils.hexify(prkdf.getKeyId(i), false));
        if (alias != null) {
            this.keys.put(alias, Byte.valueOf(prkdf.getKeyReference(i)));
        }
    }
    // Sincronizamos claves y certificados
    hideCertsWithoutKey();
}
Also used : CeresPrKdf(es.gob.jmulticard.card.fnmt.ceres.asn1.CeresPrKdf) Pkcs15Cdf(es.gob.jmulticard.asn1.der.pkcs15.Pkcs15Cdf) Pkcs15Cdf(es.gob.jmulticard.asn1.der.pkcs15.Pkcs15Cdf) Cdf(es.gob.jmulticard.asn1.der.pkcs15.Cdf) CeresCdf(es.gob.jmulticard.card.fnmt.ceres.asn1.CeresCdf) IOException(java.io.IOException) 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) X509Certificate(java.security.cert.X509Certificate) CeresCdf(es.gob.jmulticard.card.fnmt.ceres.asn1.CeresCdf) CeresPrKdf(es.gob.jmulticard.card.fnmt.ceres.asn1.CeresPrKdf) PrKdf(es.gob.jmulticard.asn1.der.pkcs15.PrKdf) Pkcs15PrKdf(es.gob.jmulticard.asn1.der.pkcs15.Pkcs15PrKdf) Pkcs15PrKdf(es.gob.jmulticard.asn1.der.pkcs15.Pkcs15PrKdf) Location(es.gob.jmulticard.card.Location)

Example 10 with Iso7816FourCardException

use of es.gob.jmulticard.card.iso7816four.Iso7816FourCardException in project jmulticard by ctt-gob-es.

the class CardOS method preloadCertificates.

private void preloadCertificates() throws FileNotFoundException, Iso7816FourCardException, IOException, Asn1Exception, TlvException {
    // Entramos en el directorio PKCS#15
    selectFileByName(PKCS15_NAME);
    // Seleccionamos el ODF, no nos devuelve FCI ni nada
    selectFileById(new byte[] { (byte) 0x50, (byte) 0x31 });
    // Leemos el ODF, que tiene esta estructura en cada uno de sus registros:
    // PKCS15Objects ::= CHOICE {
    // privateKeys         [0] PrivateKeys,
    // publicKeys          [1] PublicKeys,
    // trustedPublicKeys   [2] PublicKeys,
    // secretKeys          [3] SecretKeys,
    // certificates        [4] Certificates,
    // trustedCertificates [5] Certificates,
    // usefulCertificates  [6] Certificates,
    // dataObjects         [7] DataObjects,
    // authObjects         [8] AuthObjects,
    // ... -- For future extensions
    // }
    // A2
    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();
    // Seleccionamos el CDF
    selectFileById(cdfPath.getPathBytes());
    // Leemos el CDF mediante registros
    final List<byte[]> cdfRecords = readAllRecords();
    final CertificateFactory cf;
    try {
        // $NON-NLS-1$
        cf = CertificateFactory.getInstance("X.509");
    } catch (final CertificateException e1) {
        throw new IllegalStateException(// $NON-NLS-1$
        "No se ha podido obtener la factoria de certificados X.509: " + e1, // $NON-NLS-1$
        e1);
    }
    CertificateObject co;
    for (final byte[] b : cdfRecords) {
        try {
            co = new CertificateObject();
            co.setDerValue(HexUtils.subArray(b, 2, b.length - 2));
        } catch (final Exception e) {
            // $NON-NLS-1$
            LOGGER.warning("Omitido registro de certificado por no ser un CertificateObject de PKCS#15: " + e);
            continue;
        }
        final byte[] certPath = co.getPathBytes();
        if (certPath == null || certPath.length != 4) {
            // $NON-NLS-1$
            LOGGER.warning("Se omite una posicion de certificado porque su ruta no es de cuatro octetos: " + co.getAlias());
            continue;
        }
        final byte[] MASTER_FILE = new byte[] { (byte) 0x50, (byte) 0x15 };
        sendArbitraryApdu(new CommandApdu(// CLA
        getCla(), // INS
        (byte) 0xA4, // P1
        (byte) 0x08, // P2
        (byte) 0x0C, new byte[] { MASTER_FILE[0], MASTER_FILE[1], certPath[0], certPath[1], certPath[2], certPath[3] }, null));
        final byte[] certBytes = readBinaryComplete(9999);
        final X509Certificate cert;
        try {
            cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certBytes));
        } catch (final CertificateException e) {
            LOGGER.severe(// $NON-NLS-1$ //$NON-NLS-2$
            "No ha sido posible generar el certificado para el alias " + co.getAlias() + ": " + e);
            continue;
        }
        certificatesByAlias.put(co.getAlias(), cert);
    }
}
Also used : Odf(es.gob.jmulticard.asn1.der.pkcs15.Odf) Path(es.gob.jmulticard.asn1.der.pkcs15.Path) CommandApdu(es.gob.jmulticard.apdu.CommandApdu) ByteArrayInputStream(java.io.ByteArrayInputStream) CertificateObject(es.gob.jmulticard.asn1.der.pkcs15.CertificateObject) CertificateException(java.security.cert.CertificateException) CertificateFactory(java.security.cert.CertificateFactory) ApduConnectionException(es.gob.jmulticard.apdu.connection.ApduConnectionException) FileNotFoundException(es.gob.jmulticard.card.iso7816four.FileNotFoundException) InvalidCardException(es.gob.jmulticard.card.InvalidCardException) CardNotPresentException(es.gob.jmulticard.apdu.connection.CardNotPresentException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoReadersFoundException(es.gob.jmulticard.apdu.connection.NoReadersFoundException) TlvException(es.gob.jmulticard.asn1.TlvException) Iso7816FourCardException(es.gob.jmulticard.card.iso7816four.Iso7816FourCardException) Asn1Exception(es.gob.jmulticard.asn1.Asn1Exception) X509Certificate(java.security.cert.X509Certificate)

Aggregations

Iso7816FourCardException (es.gob.jmulticard.card.iso7816four.Iso7816FourCardException)11 ApduConnectionException (es.gob.jmulticard.apdu.connection.ApduConnectionException)9 BadPinException (es.gob.jmulticard.card.BadPinException)7 IOException (java.io.IOException)7 AuthenticationModeLockedException (es.gob.jmulticard.card.AuthenticationModeLockedException)6 CertificateException (java.security.cert.CertificateException)6 ResponseApdu (es.gob.jmulticard.apdu.ResponseApdu)5 CryptoCardException (es.gob.jmulticard.card.CryptoCardException)5 FileNotFoundException (es.gob.jmulticard.card.iso7816four.FileNotFoundException)5 CommandApdu (es.gob.jmulticard.apdu.CommandApdu)4 InvalidCardException (es.gob.jmulticard.card.InvalidCardException)4 PinException (es.gob.jmulticard.card.PinException)4 Asn1Exception (es.gob.jmulticard.asn1.Asn1Exception)3 TlvException (es.gob.jmulticard.asn1.TlvException)3 Cdf (es.gob.jmulticard.asn1.der.pkcs15.Cdf)3 Location (es.gob.jmulticard.card.Location)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 CertificateFactory (java.security.cert.CertificateFactory)3 UnsupportedCallbackException (javax.security.auth.callback.UnsupportedCallbackException)3 StatusWord (es.gob.jmulticard.apdu.StatusWord)2