Search in sources :

Example 41 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception 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();
    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[] masterFile = { (byte) 0x50, (byte) 0x15 };
        sendArbitraryApdu(new CommandApdu(// CLA
        getCla(), // INS
        (byte) 0xA4, // P1
        (byte) 0x08, // P2
        (byte) 0x0C, new byte[] { masterFile[0], masterFile[1], certPath[0], certPath[1], certPath[2], certPath[3] }, null));
        final byte[] certBytes = readBinaryComplete(9999);
        final X509Certificate cert;
        try {
            cert = CertificateUtils.generateCertificate(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;
        }
        CERTIFICATES_BY_ALIAS.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) CertificateObject(es.gob.jmulticard.asn1.der.pkcs15.CertificateObject) CertificateException(java.security.cert.CertificateException) 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)

Example 42 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception in project jmulticard by ctt-gob-es.

the class Record method decodeValue.

@Override
protected void decodeValue() throws Asn1Exception, TlvException {
    if (getRawDerValue().length == 0) {
        // $NON-NLS-1$
        throw new Asn1Exception("El valor del objeto ASN.1 esta vacio");
    }
    int offset = 0;
    Tlv tlv;
    byte[] remainingBytes;
    DecoderObject tmpDo;
    for (int i = 0; i < this.elementsTypes.length; i++) {
        try {
            remainingBytes = new byte[getRawDerValue().length - offset];
            System.arraycopy(getRawDerValue(), offset, remainingBytes, 0, remainingBytes.length);
            tlv = new Tlv(remainingBytes);
            try {
                tmpDo = this.elementsTypes[i].getElementType().getConstructor().newInstance();
            } catch (final Exception e) {
                throw new Asn1Exception(// $NON-NLS-1$
                "No se ha podido instanciar un " + this.elementsTypes[i].getElementType().getName() + " en la posicion " + Integer.toString(i) + // $NON-NLS-1$ //$NON-NLS-2$
                " del registro", // $NON-NLS-1$ //$NON-NLS-2$
                e);
            }
            tmpDo.checkTag(tlv.getTag());
        } catch (final Exception e) {
            if (this.elementsTypes[i].isOptional()) {
                // Como no ha avanzado el offset, se reutilizara el tipo en el proximo elemento
                continue;
            }
            // $NON-NLS-1$ //$NON-NLS-2$
            throw new Asn1Exception("Error en el elemento " + i + " del registro ASN.1", e);
        }
        offset = offset + tlv.getBytes().length;
        tmpDo.setDerValue(tlv.getBytes());
        this.elements.add(tmpDo);
    }
}
Also used : DecoderObject(es.gob.jmulticard.asn1.DecoderObject) Asn1Exception(es.gob.jmulticard.asn1.Asn1Exception) TlvException(es.gob.jmulticard.asn1.TlvException) Asn1Exception(es.gob.jmulticard.asn1.Asn1Exception) Tlv(es.gob.jmulticard.asn1.Tlv)

Example 43 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception in project jmulticard by ctt-gob-es.

the class Com method decodeValue.

@Override
protected void decodeValue() throws Asn1Exception, TlvException {
    BerTlv tlv = BerTlv.createInstance(getRawDerValue());
    checkTag(tlv.getTag());
    final ByteArrayInputStream tlvs = new ByteArrayInputStream(tlv.getValue());
    tlv = BerTlv.createInstance(tlvs);
    if (tlv.getLength() != 4) {
        throw new Asn1Exception(// $NON-NLS-1$
        "El valor del TLV de version LDS debe tener exactamente cuarto octetos, pero se han encontrado " + tlv.getLength());
    }
    if (tlv.getTag() != 0x01) {
        throw new Asn1Exception(// $NON-NLS-1$
        "El valor del TLV de version LDS debe tener etiqueta '01', pero se ha encontrado '" + HexUtils.hexify(new byte[] { tlv.getTag() }, false) + // $NON-NLS-1$
        "'");
    }
    this.ldsVersion = new String(new byte[] { tlv.getValue()[0], tlv.getValue()[1] }) + DOT + new String(new byte[] { tlv.getValue()[2], tlv.getValue()[3] });
    tlv = BerTlv.createInstance(tlvs);
    if (tlv.getLength() != 6) {
        throw new Asn1Exception(// $NON-NLS-1$
        "El valor del TLV de version Unicode debe tener exactamente seis octetos, pero se han encontrado " + tlv.getLength());
    }
    if (tlv.getTag() != 0x36) {
        throw new Asn1Exception(// $NON-NLS-1$
        "El valor del TLV de version Unicode debe tener etiqueta '36', pero se ha encontrado '" + HexUtils.hexify(new byte[] { tlv.getTag() }, false) + // $NON-NLS-1$
        "'");
    }
    this.unicodeVersion = new String(new byte[] { tlv.getValue()[0], tlv.getValue()[1] }) + DOT + new String(new byte[] { tlv.getValue()[2], tlv.getValue()[3] }) + DOT + new String(new byte[] { tlv.getValue()[4], tlv.getValue()[5] });
    tlv = BerTlv.createInstance(tlvs);
    if (tlv.getTag() != 0x5c) {
        throw new Asn1Exception(// $NON-NLS-1$
        "El valor del TLV de lista de rotulos debe tener etiqueta '5C', pero se han encontrado '" + HexUtils.hexify(new byte[] { tlv.getTag() }, false) + // $NON-NLS-1$
        "'");
    }
    final byte[] dgList = tlv.getValue();
    for (final byte dgTag : dgList) {
        this.presentDgs.add(DGTAGS.get(Byte.valueOf(dgTag)));
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) BerTlv(es.gob.jmulticard.asn1.bertlv.BerTlv) Asn1Exception(es.gob.jmulticard.asn1.Asn1Exception)

Example 44 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception 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
        // $NON-NLS-1$
        LOGGER.info("El CDF no es de tipo FNMT, se intenta en modo PKCS#15: " + e);
        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 PrKdf();
    try {
        prkdf.setDerValue(prkdfValue);
    } catch (final Exception e) {
        // Si no carga el estructura PrKDF probamos con la generica PKCS#15
        // especifica de CERES, presente en las versiones antiguas de la tarjeta
        // $NON-NLS-1$
        LOGGER.info("El PrKDF no es de tipo PKCS#15, se intenta en modo FNMT: " + e);
        prkdf = new CeresPrKdf();
        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.asn1.custom.fnmt.ceres.CeresPrKdf) Pkcs15Cdf(es.gob.jmulticard.asn1.der.pkcs15.Pkcs15Cdf) Pkcs15Cdf(es.gob.jmulticard.asn1.der.pkcs15.Pkcs15Cdf) CeresCdf(es.gob.jmulticard.asn1.custom.fnmt.ceres.CeresCdf) Cdf(es.gob.jmulticard.asn1.der.pkcs15.Cdf) 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.asn1.custom.fnmt.ceres.CeresCdf) CeresPrKdf(es.gob.jmulticard.asn1.custom.fnmt.ceres.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 45 with ASN1Exception

use of com.github.zhenwei.core.asn1.ASN1Exception in project jmulticard by ctt-gob-es.

the class TestDerBoolean method testCheckTagWithWrongTagMustThrowException.

/**
 * Test method for {@link es.gob.jmulticard.asn1.DecoderObject#checkTag(byte)}.
 */
public static final void testCheckTagWithWrongTagMustThrowException() {
    try {
        final DerBoolean db = new DerBoolean();
        db.checkTag((byte) 0x02);
    } catch (final Asn1Exception e) {
        // $NON-NLS-1$
        System.out.println("Todo normal, ha saltado " + e);
    } catch (final Exception e) {
        // $NON-NLS-1$ //$NON-NLS-2$
        Assert.fail("Se esperaba " + Asn1Exception.class.getName() + " pero se obtuvo " + e.getClass().getName());
    }
}
Also used : DerBoolean(es.gob.jmulticard.asn1.der.DerBoolean) Asn1Exception(es.gob.jmulticard.asn1.Asn1Exception) TlvException(es.gob.jmulticard.asn1.TlvException) Asn1Exception(es.gob.jmulticard.asn1.Asn1Exception)

Aggregations

IOException (java.io.IOException)18 Asn1Exception (es.gob.jmulticard.asn1.Asn1Exception)16 ASN1Exception (com.unboundid.asn1.ASN1Exception)12 TlvException (es.gob.jmulticard.asn1.TlvException)12 Asn1Exception (sun.security.krb5.Asn1Exception)11 ASN1Element (com.unboundid.asn1.ASN1Element)7 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)7 NotNull (com.unboundid.util.NotNull)7 Iso7816FourCardException (es.gob.jmulticard.card.iso7816four.Iso7816FourCardException)7 CertificateException (java.security.cert.CertificateException)7 X509Certificate (java.security.cert.X509Certificate)7 Asn1Exception (org.kse.utilities.asn1.Asn1Exception)7 ASN1Exception (org.wildfly.security.asn1.ASN1Exception)6 ApduConnectionException (es.gob.jmulticard.apdu.connection.ApduConnectionException)5 Cdf (es.gob.jmulticard.asn1.der.pkcs15.Cdf)5 CryptoCardException (es.gob.jmulticard.card.CryptoCardException)5 ASN1Sequence (com.unboundid.asn1.ASN1Sequence)4 DecoderObject (es.gob.jmulticard.asn1.DecoderObject)4 InvalidCardException (es.gob.jmulticard.card.InvalidCardException)4 DerValue (sun.security.util.DerValue)4