Example usage for org.bouncycastle.asn1 ASN1InputStream readObject

List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1InputStream readObject.

Prototype

public ASN1Primitive readObject() throws IOException 

Source Link

Usage

From source file:es.gob.afirma.signers.multi.cades.CAdESCounterSigner.java

License:Open Source License

/** Crea una contrafirma a partir de los datos
 * del firmante, el archivo que se firma y del archivo que contiene las
 * firmas.<br>/*from   ww  w. j a v  a2  s.  c  o  m*/
 * @param parameters
 *        par&aacute;metros necesarios que contienen tanto la firma del
 *        archivo a firmar como los datos del firmante.
 * @param data
 *        Archivo que contiene las firmas.
 * @param targetType
 *        Lo que se quiere firmar. Puede ser el &aacute;rbol completo,
 *        las hojas, un nodo determinado o unos determinados firmantes.
 * @param targets
 *        Nodos objetivos a firmar.
 * @param key Clave privada a usar para firmar.
 * @param certChain Cadena de certificados del firmante.
 * @param policy Pol&iacute;tica de firma
 * @param signingCertificateV2
 *        <code>true</code> si se desea usar la versi&oacute;n 2 del
 *        atributo <i>Signing Certificate</i> <code>false</code> para
 *        usar la versi&oacute;n 1
 * @param contentDescription Descripci&oacute;n textual del tipo de contenido firmado.
 * @param ctis Indicaciones sobre los tipos de compromisos adquiridos con la firma.
 * @param csm Metadatos sobre el firmante.
 * @return El archivo de firmas con la nueva firma.
 * @throws IOException Cuando se produce algun error con la lectura o escritura de datos.
 * @throws NoSuchAlgorithmException Excepci&oacute;n cuando no se encuentra el algoritmo de
 *                                  firma.
 * @throws CertificateException Si se produce alguna excepci&oacute;n con los certificados de
 *                              firma.
 * @throws AOException Cuando ocurre alguno error con contemplado por las otras
 *                     excepciones declaradas */
byte[] counterSigner(final P7ContentSignerParameters parameters, final byte[] data,
        final CounterSignTarget targetType, final int[] targets, final PrivateKey key,
        final java.security.cert.Certificate[] certChain, final AdESPolicy policy,
        final boolean signingCertificateV2, final String contentDescription,
        final List<CommitmentTypeIndicationBean> ctis, final CAdESSignerMetadata csm)
        throws IOException, NoSuchAlgorithmException, CertificateException, AOException {

    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    final ASN1InputStream is = new ASN1InputStream(data);
    final ASN1Sequence dsq = (ASN1Sequence) is.readObject();
    is.close();
    final Enumeration<?> e = dsq.getObjects();
    // Elementos que contienen los elementos OID SignedData
    e.nextElement();
    // Contenido de SignedData
    final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();
    final ASN1Sequence contentSignedData = (ASN1Sequence) doj.getObject();

    final SignedData sd = SignedData.getInstance(contentSignedData);

    // Obtenemos los signerInfos del SignedData
    final ASN1Set signerInfosSd = sd.getSignerInfos();

    // 4. CERTIFICADOS
    // obtenemos la lista de certificados
    ASN1Set certificates = null;

    final ASN1Set certificatesSigned = sd.getCertificates();
    final ASN1EncodableVector vCertsSig = new ASN1EncodableVector();
    final Enumeration<?> certs = certificatesSigned.getObjects();

    // COGEMOS LOS CERTIFICADOS EXISTENTES EN EL FICHERO
    while (certs.hasMoreElements()) {
        vCertsSig.add((ASN1Encodable) certs.nextElement());
    }
    // e introducimos los del firmante actual.
    if (certChain.length != 0) {
        final List<ASN1Encodable> ce = new ArrayList<ASN1Encodable>();
        for (final java.security.cert.Certificate element : certChain) {
            ce.add(Certificate.getInstance(ASN1Primitive.fromByteArray(element.getEncoded())));
        }
        certificates = SigUtils.fillRestCerts(ce, vCertsSig);
    }

    // CRLS no usado
    final ASN1Set certrevlist = null;

    // 5. SIGNERINFO
    // raiz de la secuencia de SignerInfo
    ASN1EncodableVector signerInfos = new ASN1EncodableVector();

    // FIRMA EN ARBOL
    if (targetType.equals(CounterSignTarget.TREE)) {
        signerInfos = counterTree(signerInfosSd, parameters, key, certChain, contentDescription, policy,
                signingCertificateV2, ctis, csm);
    }
    // FIRMA DE LAS HOJAS
    else if (targetType.equals(CounterSignTarget.LEAFS)) {
        signerInfos = counterLeaf(signerInfosSd, parameters, key, certChain, contentDescription, policy,
                signingCertificateV2, ctis, csm);
    }
    // FIRMA DE NODOS
    else if (targetType.equals(CounterSignTarget.NODES)) {
        // Firma de Nodos
        SignedData sigDat;
        SignedData aux = sd;

        int nodo = 0;
        for (int i = targets.length - 1; i >= 0; i--) {
            nodo = targets[i];
            signerInfos = counterNode(aux, parameters, key, certChain, contentDescription, nodo, policy,
                    signingCertificateV2, ctis, csm);
            sigDat = new SignedData(sd.getDigestAlgorithms(), sd.getEncapContentInfo(), certificates,
                    certrevlist, new DERSet(signerInfos));

            // Esto se realiza asi por problemas con los casting.
            final ASN1InputStream sd2 = new ASN1InputStream(sigDat.getEncoded(ASN1Encoding.DER));
            final ASN1Sequence contentSignedData2 = (ASN1Sequence) sd2.readObject();// contenido del SignedData
            sd2.close();
            aux = SignedData.getInstance(contentSignedData2);
        }

        // construimos el Signed Data y lo devolvemos
        return new ContentInfo(PKCSObjectIdentifiers.signedData, aux).getEncoded(ASN1Encoding.DER);
    }
    // FIRMA DE LOS SIGNERS
    else if (targetType.equals(CounterSignTarget.SIGNERS)) {
        // Firma de Nodos
        SignedData sigDat;
        SignedData aux = sd;

        int nodo = 0;
        for (int i = targets.length - 1; i >= 0; i--) {
            nodo = targets[i];
            signerInfos = counterNode(aux, parameters, key, certChain, contentDescription, nodo, policy,
                    signingCertificateV2, ctis, csm);
            sigDat = new SignedData(sd.getDigestAlgorithms(), sd.getEncapContentInfo(), certificates,
                    certrevlist, new DERSet(signerInfos));

            // Esto se realiza as&iacute; por problemas con los casting.
            final ASN1InputStream sd2 = new ASN1InputStream(sigDat.getEncoded(ASN1Encoding.DER));
            final ASN1Sequence contentSignedData2 = (ASN1Sequence) sd2.readObject();// contenido del SignedData
            sd2.close();

            aux = SignedData.getInstance(contentSignedData2);
        }

        // construimos el Signed Data y lo devolvemos
        return new ContentInfo(PKCSObjectIdentifiers.signedData, aux).getEncoded(ASN1Encoding.DER);
    }

    // construimos el Signed Data y lo devolvemos
    return new ContentInfo(PKCSObjectIdentifiers.signedData, new SignedData(sd.getDigestAlgorithms(),
            sd.getEncapContentInfo(), certificates, certrevlist, new DERSet(signerInfos)))
                    .getEncoded(ASN1Encoding.DER);

}

From source file:es.gob.afirma.signers.multi.cades.CAdESCounterSignerEnveloped.java

License:Open Source License

/** Constructor de la clase. Se crea una contrafirma a partir de los datos
 * del firmante, el archivo que se firma y del archivo que contiene las
 * firmas.<br>//from   ww  w .  j a v a  2s  . c  o  m
 * @param parameters Par&aacute;metros necesarios que contienen tanto la firma del
 *                   archivo a firmar como los datos del firmante.
 * @param data Archivo que contiene las firmas.
 * @param targetType
 *        Lo que se quiere firmar. Puede ser el &aacute;rbol completo,
 *        las hojas, un nodo determinado o unos determinados firmantes.
 * @param targets
 *        Nodos objetivos a firmar.
 * @param key Clave privada a usar para firmar.
 * @param certChain Cadena de certificados del firmante.
 * @param policy Pol&iacute;tica de firma
 * @param signingCertificateV2
 *        <code>true</code> si se desea usar la versi&oacute;n 2 del
 *        atributo <i>Signing Certificate</i> <code>false</code> para
 *        usar la versi&oacute;n 1
 * @param contentDescription Descripci&oacute;n textual del tipo de contenido firmado.
 * @param ctis Indicaciones sobre los tipos de compromisos adquiridos con la firma.
 * @param csm Metadatos sobre el firmante.
 * @return El archivo de firmas con la nueva firma.
 * @throws IOException Cuando se produce algun error con la lectura o escritura de datos.
 * @throws java.security.NoSuchAlgorithmException
 *         Excepci&oacute;n cuando no se encuentra el algoritmo de
 *         firma.
 * @throws java.security.cert.CertificateException
 *         Si se produce alguna excepci&oacute;n con los certificados de
 *         firma.
 * @throws AOException
 *         Cuando ocurre alguno error con contemplado por las otras
 *         excepciones declaradas */
byte[] counterSigner(final P7ContentSignerParameters parameters, final byte[] data,
        final CounterSignTarget targetType, final int[] targets, final PrivateKey key,
        final java.security.cert.Certificate[] certChain, final AdESPolicy policy,
        final boolean signingCertificateV2, final String contentDescription,
        final List<CommitmentTypeIndicationBean> ctis, final CAdESSignerMetadata csm)
        throws IOException, NoSuchAlgorithmException, CertificateException, AOException {

    // Introducimos la politica en variable global por comodidad.
    // Esta no varia.
    this.setGlobalPolicy(policy);
    this.setGlobalsigningCertificateV2(signingCertificateV2);

    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    final ASN1InputStream is = new ASN1InputStream(data);
    final ASN1Sequence dsq = (ASN1Sequence) is.readObject();
    is.close();
    final Enumeration<?> e = dsq.getObjects();
    // Elementos que contienen los elementos OID SignedAndEnvelopedData
    e.nextElement();
    // Contenido de SignedAndEnvelopedData
    final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();
    final ASN1Sequence contentSignedData = (ASN1Sequence) doj.getObject();

    final SignedAndEnvelopedData sd = new SignedAndEnvelopedData(contentSignedData);

    // Obtenemos los signerInfos del SignedAndEnvelopedData
    final ASN1Set signerInfosSd = sd.getSignerInfos();

    // 4. CERTIFICADOS
    // obtenemos la lista de certificados
    ASN1Set certificates = null;

    final ASN1Set certificatesSigned = sd.getCertificates();
    final ASN1EncodableVector vCertsSig = new ASN1EncodableVector();
    final Enumeration<?> certs = certificatesSigned.getObjects();

    // COGEMOS LOS CERTIFICADOS EXISTENTES EN EL FICHERO
    while (certs.hasMoreElements()) {
        vCertsSig.add((ASN1Encodable) certs.nextElement());
    }
    // e introducimos los del firmante actual.
    if (certChain.length != 0) {
        final List<ASN1Encodable> ce = new ArrayList<ASN1Encodable>();
        for (final java.security.cert.Certificate element : certChain) {
            ce.add(Certificate.getInstance(ASN1Primitive.fromByteArray(element.getEncoded())));
        }
        certificates = SigUtils.fillRestCerts(ce, vCertsSig);
    }

    // CRLS no usado
    final ASN1Set certrevlist = null;

    // 5. SIGNERINFO
    // raiz de la secuencia de SignerInfo
    ASN1EncodableVector signerInfos = new ASN1EncodableVector();

    // FIRMA EN ARBOL
    if (targetType.equals(CounterSignTarget.TREE)) {
        signerInfos = counterTree(signerInfosSd, parameters, key, certChain, contentDescription, ctis, csm);
    }
    // FIRMA DE LAS HOJAS
    else if (targetType.equals(CounterSignTarget.LEAFS)) {
        signerInfos = counterLeaf(signerInfosSd, parameters, key, certChain, contentDescription, ctis, csm);
    }
    // FIRMA DE NODOS
    else if (targetType.equals(CounterSignTarget.NODES)) {
        // Firma de Nodos
        SignedAndEnvelopedData sigDat;
        SignedAndEnvelopedData aux = sd;

        int nodo = 0;
        for (int i = targets.length - 1; i >= 0; i--) {
            nodo = targets[i];
            signerInfos = counterNode(aux, parameters, key, certChain, contentDescription, nodo, ctis, csm);
            sigDat = new SignedAndEnvelopedData(sd.getRecipientInfos(), sd.getDigestAlgorithms(),
                    sd.getEncryptedContentInfo(), certificates, certrevlist, new DERSet(signerInfos));

            // Esto se realiza as&iacute; por problemas con los casting.
            final ASN1InputStream sd2 = new ASN1InputStream(
                    sigDat.toASN1Primitive().getEncoded(ASN1Encoding.DER));
            final ASN1Sequence contentSignedData2 = (ASN1Sequence) sd2.readObject();// contenido del SignedAndEnvelopedData
            sd2.close();
            aux = new SignedAndEnvelopedData(contentSignedData2);
        }

        // construimos el Signed Data y lo devolvemos
        return new ContentInfo(PKCSObjectIdentifiers.signedAndEnvelopedData, aux).getEncoded(ASN1Encoding.DER);
    }
    // FIRMA DE LOS SIGNERS
    else if (targetType.equals(CounterSignTarget.SIGNERS)) {
        // Firma de Nodos
        SignedAndEnvelopedData sigDat;
        SignedAndEnvelopedData aux = sd;

        int nodo = 0;
        for (int i = targets.length - 1; i >= 0; i--) {
            nodo = targets[i];
            signerInfos = counterNode(aux, parameters, key, certChain, contentDescription, nodo, ctis, csm);
            sigDat = new SignedAndEnvelopedData(sd.getRecipientInfos(), sd.getDigestAlgorithms(),
                    sd.getEncryptedContentInfo(), certificates, certrevlist, new DERSet(signerInfos));

            // Esto se realiza as&iacute; por problemas con los casting.
            final ASN1InputStream sd2 = new ASN1InputStream(sigDat.getEncoded(ASN1Encoding.DER));
            final ASN1Sequence contentSignedData2 = (ASN1Sequence) sd2.readObject();// contenido del SignedAndEnvelopedData
            sd2.close();

            aux = new SignedAndEnvelopedData(contentSignedData2);
        }

        // construimos el Signed Data y lo devolvemos
        return new ContentInfo(PKCSObjectIdentifiers.signedAndEnvelopedData, aux).getEncoded(ASN1Encoding.DER);
    }

    // construimos el Signed Data y lo devolvemos
    return new ContentInfo(PKCSObjectIdentifiers.signedAndEnvelopedData,
            new SignedAndEnvelopedData(sd.getRecipientInfos(), sd.getDigestAlgorithms(),
                    sd.getEncryptedContentInfo(), certificates, certrevlist, new DERSet(signerInfos)))
                            .getEncoded(ASN1Encoding.DER);

}

From source file:es.gob.afirma.signers.multi.cades.CAdESTriPhaseCounterSigner.java

License:Open Source License

/** Crea una contrafirma a partir de los datos
 * del firmante, el archivo que se firma y del archivo que contiene las
 * firmas.<br>//w  w w  . j ava  2s. c  o  m
 * @param parameters
 *        par&aacute;metros necesarios que contienen tanto la firma del
 *        archivo a firmar como los datos del firmante.
 * @param data
 *        Archivo que contiene las firmas.
 * @param targetType
 *        Lo que se quiere firmar. Puede ser el &aacute;rbol completo,
 *        las hojas, un nodo determinado o unos determinados firmantes.
 * @param key Clave privada a usar para firmar.
 * @param certChain Cadena de certificados del firmante
 * @param policy Pol&iacute;tica de firma
 * @param signingCertificateV2
 *        <code>true</code> si se desea usar la versi&oacute;n 2 del
 *        atributo <i>Signing Certificate</i> <code>false</code> para
 *        usar la versi&oacute;n 1
 * @param contentType
 *         Tipo de contenido definido por su OID.
 * @param contentDescription
 *         Descripci&oacute;n textual del tipo de contenido firmado.
 * @return El archivo de firmas con la nueva firma.
 * @throws java.io.IOException
 *         Excepci&oacute;n cuando se produce algun error con lectura
 *         escritura de ficheros.
 * @throws java.security.NoSuchAlgorithmException
 *         Excepci&oacute;n cuando no se encuentra el algoritmo de
 *         firma.
 * @throws java.security.cert.CertificateException
 *         Si se produce alguna excepci&oacute;n con los certificados de
 *         firma.
 * @throws AOException
 *         Cuando ocurre alguno error con contemplado por las otras
 *         excepciones declaradas */
public CAdESPreCounterSignResult preCounterSign(final P7ContentSignerParameters parameters, final byte[] data,
        final CounterSignTarget targetType, final PrivateKey key,
        final java.security.cert.Certificate[] certChain, final AdESPolicy policy,
        final boolean signingCertificateV2, final String contentType, final String contentDescription)
        throws IOException, NoSuchAlgorithmException, CertificateException, AOException {

    // Inicializamos el contador global y la lista de SignedDatas
    this.counterIndex = 0;
    this.signedDatas = new ArrayList<byte[]>();

    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    final ASN1InputStream is = new ASN1InputStream(data);
    final ASN1Sequence dsq = (ASN1Sequence) is.readObject();
    is.close();
    final Enumeration<?> e = dsq.getObjects();
    // Elementos que contienen los elementos OID SignedData
    e.nextElement();
    // Contenido de SignedData
    final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();
    final ASN1Sequence contentSignedData = (ASN1Sequence) doj.getObject();

    final SignedData sd = SignedData.getInstance(contentSignedData);

    // Obtenemos los signerInfos del SignedData
    final ASN1Set signerInfosSd = sd.getSignerInfos();

    // 4. CERTIFICADOS
    // obtenemos la lista de certificados
    ASN1Set certificates = null;

    final ASN1Set certificatesSigned = sd.getCertificates();
    final ASN1EncodableVector vCertsSig = new ASN1EncodableVector();
    final Enumeration<?> certs = certificatesSigned.getObjects();

    // COGEMOS LOS CERTIFICADOS EXISTENTES EN EL FICHERO
    while (certs.hasMoreElements()) {
        vCertsSig.add((ASN1Encodable) certs.nextElement());
    }
    // e introducimos los del firmante actual.
    if (certChain.length != 0) {
        final List<ASN1Encodable> ce = new ArrayList<ASN1Encodable>();
        for (final java.security.cert.Certificate element : certChain) {
            ce.add(Certificate.getInstance(ASN1Primitive.fromByteArray(element.getEncoded())));
        }
        certificates = SigUtils.fillRestCerts(ce, vCertsSig);
    }

    // CRLS no usado
    final ASN1Set certrevlist = null;

    // 5. SIGNERINFO
    // raiz de la secuencia de SignerInfo
    ASN1EncodableVector signerInfos = new ASN1EncodableVector();

    // FIRMA EN ARBOL
    if (CounterSignTarget.TREE.equals(targetType)) {
        signerInfos = counterTree(signerInfosSd, parameters, key, certChain, contentType, contentDescription,
                policy, signingCertificateV2);
    }
    // FIRMA DE LAS HOJAS
    else if (CounterSignTarget.LEAFS.equals(targetType)) {
        signerInfos = counterLeaf(signerInfosSd, parameters, key, certChain, contentType, contentDescription,
                policy, signingCertificateV2);
    } else {
        throw new IllegalArgumentException("Modo de contrafirma no soportado: " + targetType); //$NON-NLS-1$
    }

    // construimos el Signed Data y lo devolvemos dentro del resultado
    return new CAdESPreCounterSignResult(
            new ContentInfo(PKCSObjectIdentifiers.signedData,
                    new SignedData(sd.getDigestAlgorithms(), sd.getEncapContentInfo(), certificates,
                            certrevlist, new DERSet(signerInfos))).getEncoded(ASN1Encoding.DER),
            this.signedDatas);
}

From source file:es.gob.afirma.signers.pkcs7.ObtainContentSignedData.java

License:Open Source License

/** M&eacute;todo que obtiene el contenido firmado de un tipo Signed Data
 * tanto en CADES como en CMS. Si la firma no contiene los datos, devuelve <code>null</code>.
 * @param data//from   www. j a  v  a2s .c o m
 *        datos que contienen la firma.
 * @return el contenido firmado.
 * @throws IOException Si no se pueden leer los datos */
public static byte[] obtainData(final byte[] data) throws IOException {
    byte[] contenido = null;

    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    final ASN1InputStream is = new ASN1InputStream(data);
    final ASN1Sequence dsq = (ASN1Sequence) is.readObject();
    is.close();

    final Enumeration<?> e = dsq.getObjects();
    // Elementos que contienen los elementos OID Data
    final ASN1ObjectIdentifier doi = (ASN1ObjectIdentifier) e.nextElement();
    // Contenido a obtener informacion
    final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();

    // buscamos si es signedData
    if (doi.equals(PKCSObjectIdentifiers.signedData)) {
        // obtenemos el signed Data
        final SignedData sd = SignedData.getInstance(doj.getObject());
        final ContentInfo ci = sd.getEncapContentInfo();
        // obtenemos el contenido si lo tiene.
        if (ci.getContent() != null) {
            contenido = ((DEROctetString) ci.getContent()).getOctets();
        } else {
            LOGGER.warning("No existe contenido en esta firma."); //$NON-NLS-1$
        }
    } else {
        LOGGER.warning("No se puede obtener el contenido de esta firma."); //$NON-NLS-1$
    }

    return contenido;
}

From source file:es.gob.afirma.signers.pkcs7.ObtainContentSignedData.java

License:Open Source License

/** M&eacute;todo que obtiene la huella digital de los datos firmados en una firma CMS/CAdES.
 * La huella se obtenida estar&aacute; generada con el algoritmo de huella indicado, si este
 * algoritmo es el que se utiliz&oacute; en alguna de las operaci&oacute;nes de firma con la
 * que se gener&oacute; esta firma. Si no se utiliz&oacute; este algoritmo, se devuelve
 * {@code null}.//from   w  w w .  java 2s  .com
 * @param signature Firma de la que obtener la huella digital.
 * @param digestAlgorithm Algoritmo con el que se gener&oacute; la huella digital que buscamos.
 * @return La huella digital de los datos firmados generada con el algoritmo indicado, o
 * {@code null} si esta no se encuentra en la firma.
 * @throws IOException Si no se pueden leer los datos */
public static byte[] obtainMessageDigest(final byte[] signature, final String digestAlgorithm)
        throws IOException {

    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    final ASN1InputStream is = new ASN1InputStream(signature);
    final ASN1Sequence dsq = (ASN1Sequence) is.readObject();
    is.close();

    final Enumeration<?> e = dsq.getObjects();

    // Elementos que contienen los elementos OID Data
    final ASN1ObjectIdentifier doi = (ASN1ObjectIdentifier) e.nextElement();

    // Comprobamos que sea una firma
    if (!doi.equals(PKCSObjectIdentifiers.signedData)) {
        LOGGER.warning("No se puede obtener el contenido de esta firma."); //$NON-NLS-1$
        return null;
    }

    // Contenido a obtener informacion
    final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();
    final SignedData sd = SignedData.getInstance(doj.getObject());
    final ASN1Set signerInfosSd = sd.getSignerInfos();

    byte[] messageDigest = null;

    for (int i = 0; i < signerInfosSd.size(); i++) {
        final SignerInfo si = SignerInfo.getInstance(signerInfosSd.getObjectAt(i));
        final AlgorithmIdentifier algHash = si.getDigestAlgorithm();
        if (algHash.getAlgorithm().toString().equals(AOAlgorithmID.getOID(digestAlgorithm))) {
            final ASN1Set signedAttrib = si.getAuthenticatedAttributes();
            for (int s = 0; s < signedAttrib.size(); s++) {
                final ASN1Sequence elemento = (ASN1Sequence) signedAttrib.getObjectAt(s);
                final ASN1ObjectIdentifier oids = (ASN1ObjectIdentifier) elemento.getObjectAt(0);
                if (CMSAttributes.messageDigest.getId().equals(oids.toString())) {
                    final DERSet derSetHash = (DERSet) elemento.getObjectAt(1);
                    final DEROctetString derHash = (DEROctetString) derSetHash.getObjectAt(0);
                    messageDigest = derHash.getOctets();
                    break;
                }
            }
            if (messageDigest != null) {
                break;
            }
        }
    }
    if (messageDigest == null) {
        LOGGER.warning("No se ha encontrado en la firma una huella digital generada con el algoritmo: " //$NON-NLS-1$
                + digestAlgorithm);
    }
    return messageDigest;
}

From source file:es.gob.afirma.signers.pkcs7.ReadNodesTree.java

License:Open Source License

/** Genera el &aacute;rbol que representa las firmas.
 * @param data/* www . jav  a2s  .c o m*/
 *        Archivo que contiene la firma.
 * @param asSimpleSignInfo
 *        Indica si deben extraerse informacion b&aacute;sica de la
 *        firma o solo los nombres.
 * @return Un modelo de &aacute;rbol.
 * @throws java.io.IOException
 *         Si ocurre alg&uacute;n problema leyendo o escribiendo los
 *         datos */
public AOTreeModel readNodesTree(final byte[] data, final boolean asSimpleSignInfo) throws IOException {

    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    final ASN1InputStream is = new ASN1InputStream(data);
    final ASN1Sequence dsq = (ASN1Sequence) is.readObject();
    is.close();
    final Enumeration<?> contentsData = dsq.getObjects();

    // Elementos que contienen los elementos OID SignedData
    contentsData.nextElement();

    // Contenido de SignedData
    final ASN1TaggedObject doj = (ASN1TaggedObject) contentsData.nextElement();
    final ASN1Sequence contentSignedData = (ASN1Sequence) doj.getObject();

    // Raiz de la secuencia de SignerInfo
    // Obtenemos los signerInfos del SignedData
    ASN1Set signerInfosSd = null;
    ASN1Set certificates = null;
    try {
        final SignedData sd = SignedData.getInstance(contentSignedData);
        signerInfosSd = sd.getSignerInfos();
        certificates = sd.getCertificates();
    } catch (final Exception e) {
        LOGGER.severe("Error obteniendo los SignerInfos del SignedData: " + e); //$NON-NLS-1$
    }

    // Para la creacion del arbol
    final AOTreeNode raiz = new AOTreeNode("Datos"); //$NON-NLS-1$

    // introducimos el nuevo SignerInfo del firmante actual.

    if (asSimpleSignInfo && signerInfosSd != null) {
        for (int i = 0; i < signerInfosSd.size(); i++) {
            final ASN1Sequence atribute = (ASN1Sequence) signerInfosSd.getObjectAt(i);
            final IssuerAndSerialNumber issuerSerial = IssuerAndSerialNumber
                    .getInstance(atribute.getObjectAt(1));
            final X509Certificate[] nameSigner = searchCert(certificates, issuerSerial.getSerialNumber());
            final SignerInfo si = SignerInfo.getInstance(atribute);
            final Date signingTime = getSigningTime(si);
            final AOSimpleSignInfo aossi = new AOSimpleSignInfo(nameSigner, signingTime);
            aossi.setPkcs1(si.getEncryptedDigest().getOctets());
            this.rama = new AOTreeNode(aossi);
            this.listaCert.add(nameSigner);
            getUnsignedAtributesWithCertificates(si.getUnauthenticatedAttributes(), this.rama, certificates);
            raiz.add(this.rama);
        }
    } else if (signerInfosSd != null) {
        for (int i = 0; i < signerInfosSd.size(); i++) {
            final ASN1Sequence atribute = (ASN1Sequence) signerInfosSd.getObjectAt(i);
            final IssuerAndSerialNumber issuerSerial = IssuerAndSerialNumber
                    .getInstance(atribute.getObjectAt(1));
            final String nameSigner = searchName(certificates, issuerSerial.getSerialNumber());
            final SignerInfo si = SignerInfo.getInstance(atribute);
            this.rama = new AOTreeNode(nameSigner);
            this.lista.add(nameSigner);
            getUnsignedAtributes(si.getUnauthenticatedAttributes(), this.rama, certificates);

            raiz.add(this.rama);
        }
    }

    return new AOTreeModel(raiz);
}

From source file:es.gob.afirma.signers.tsp.pkcs7.CMSTimestamper.java

License:Open Source License

/** A&ntilde;ade un sello de tiempo a las firmas encontradas dentro de una estructura PKCS#7.
 * @param pkcs7 Estructura que contiene las firmas a estampar un sello de tiempo
 * @param hashAlgorithm Algoritmo de huella digital a usar en los sellos de tiempo (si se indica <code>null</code> se usa SHA-1)
 * @param time Tiempo del sello/*from   w  w w .  j  a va  2  s  .  com*/
 * @return Nueva estructura PKCS#7 con los sellos de tiempo a&ntilde;adidos
 * @throws NoSuchAlgorithmException Si no se soporta el algoritmo de huella digital del sello de tiempo
 * @throws AOException Cuando ocurren errores gen&eacute;ricos
 * @throws IOException Si hay errores de entrada / salida */
public byte[] addTimestamp(final byte[] pkcs7, final String hashAlgorithm, final Calendar time)
        throws NoSuchAlgorithmException, AOException, IOException {

    final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(hashAlgorithm);

    final CMSSignedData signedData;
    try {
        signedData = new CMSSignedData(pkcs7);
    } catch (final Exception e) {
        throw new IllegalArgumentException("Los datos de entrada no son un SignedData de CMS: " + e); //$NON-NLS-1$
    }

    final SignerInformationStore origSignerInfoStore = signedData.getSignerInfos();

    // Insertamos un sello de tiempo en cada una de las firmas encontradas en el PKCS#7
    final List<SignerInformation> vNewSigners = new ArrayList<SignerInformation>();

    final Collection<?> ovSigners = origSignerInfoStore.getSigners();
    for (final Object name : ovSigners) {

        final SignerInformation si = (SignerInformation) name;

        final byte[] tsToken = getTimeStampToken(
                MessageDigest.getInstance(digestAlgorithm).digest(si.getSignature()), digestAlgorithm, time);

        final ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(tsToken));
        final ASN1Primitive derObj = is.readObject();
        is.close();
        final DERSet derSet = new DERSet(derObj);

        final Attribute unsignAtt = new Attribute(new ASN1ObjectIdentifier(SIGNATURE_TIMESTAMP_TOKEN_OID),
                derSet);

        final Hashtable<ASN1ObjectIdentifier, Attribute> ht = new Hashtable<ASN1ObjectIdentifier, Attribute>();
        ht.put(new ASN1ObjectIdentifier(SIGNATURE_TIMESTAMP_TOKEN_OID), unsignAtt);

        final AttributeTable unsignedAtts = new AttributeTable(ht);

        vNewSigners.add(SignerInformation.replaceUnsignedAttributes(si, unsignedAtts));
    }

    return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(vNewSigners)).getEncoded();

}

From source file:es.mityc.firmaJava.libreria.utilidades.UtilidadFirmaElectronica.java

License:LGPL

/**
 * //w ww. j av a  2s .  c  om
 * @param listaCertificadosTemp Lista de certificados temporales
 * @return
 */
public static Vector<X509Certificate> filtraDNIe(Vector<X509Certificate> listaCertificadosTemp) {
    if (log.isTraceEnabled())
        log.trace("Filtrando certificados del DNIe...");
    Vector<X509Certificate> returnCertificates = new Vector<X509Certificate>();
    ASN1InputStream asn1IS = null;
    int longitudCertificados = listaCertificadosTemp.size();
    for (int a = 0; a < longitudCertificados; a++) {
        X509Certificate certTemp = listaCertificadosTemp.get(a);
        if (UtilidadDNIe.isCertDNIe(certTemp.getIssuerDN().toString())) {
            try {
                // El certificado de autenticacin tiene una certificate policy 2.16.724.1.2.2.2.4
                // El certificado de firma tiene una certificate policy 2.16.724.1.2.2.2.3
                // Recupera la certificate policy de este certificado
                byte[] policies = certTemp.getExtensionValue(CERTIFICATE_POLICIES_OID);
                if (policies != null) {
                    //Falsos positivos
                    asn1IS = new ASN1InputStream(policies);
                    // Una extensin de certificado va como DER-encoded OCTET (ver getExtensionValue de X509Extension)
                    ASN1OctetString ext = (ASN1OctetString) ((ASN1InputStream) asn1IS).readObject();
                    //asn1IS.close();
                    asn1IS = new ASN1InputStream(ext.getOctets());
                    ASN1Sequence seq = (ASN1Sequence) asn1IS.readObject();
                    // Solo hay una PolicyInformation para el DNIe
                    PolicyInformation pi = new PolicyInformation((ASN1Sequence) seq.getObjectAt(0));
                    if (UtilidadDNIe.POLICY_OID_CERTIFICADO_AUTENTICACION_DNIE
                            .equals(pi.getPolicyIdentifier().getId()))
                        continue;
                }
                returnCertificates.add(certTemp);
            } catch (Exception ex) {
                returnCertificates.add(certTemp);
            }

            finally {
                if (asn1IS != null) {
                    try {
                        asn1IS.close();
                    } catch (IOException e) {
                        log.error(e);
                    }
                }
            }
        } else
            returnCertificates.add(certTemp);
    }
    return returnCertificates;
}

From source file:es.mityc.firmaJava.ts.TSCliente.java

License:LGPL

/**
 * Este mtodo genera el Sello de Tiempo//from w w  w .  ja  va 2 s  .  c  o m
 * @param binarioaSellar fichero binario que se va a sellar
 * @return TimeStampToken en formato binario
 * @throws TSClienteError
 */
public byte[] generarSelloTiempo(byte[] binarioaSellar) throws TSClienteError {

    if (binarioaSellar == null) {
        log.error(MENSAJE_NO_DATOS_SELLO_TIEMPO);
        throw new TSClienteError(I18n.getResource(LIBRERIA_TSA_ERROR_1));
    } else {
        log.info(MENSAJE_GENERANDO_SELLO_TIEMPO);
        TimeStampRequestGenerator generadorPeticion = new TimeStampRequestGenerator();
        TimeStampRequest peticion = null;
        TimeStampResponse respuesta = null;

        try {
            MessageDigest resumen = MessageDigest.getInstance(algoritmoHash);
            resumen.update(binarioaSellar);
            peticion = generadorPeticion.generate(TSPAlgoritmos.getOID(algoritmoHash), resumen.digest());
            log.info(MENSAJE_PETICION_TSA_GENERADA);
        } catch (Exception e) {
            log.error(MENSAJE_ERROR_PETICION_TSA);
            throw new TSClienteError(I18n.getResource(LIBRERIA_TSA_ERROR_10));
        }

        cliente.getParams().setParameter(HttpClientParams.SO_TIMEOUT, INT5000);

        // Comprueba si hay configurado un proxy
        String servidorProxy = System.getProperty("http.proxyHost");
        if (servidorProxy != null && !servidorProxy.trim().equals(CADENA_VACIA)) {
            int puertoProxy = 80;
            try {
                puertoProxy = Integer.parseInt(System.getProperty("http.proxyPort"));
            } catch (NumberFormatException ex) {
            }
            cliente.getHostConfiguration().setProxy(servidorProxy, puertoProxy);

            Credentials defaultcreds = new AuthenticatorProxyCredentials(servidorProxy, CADENA_VACIA);
            cliente.getState().setProxyCredentials(AuthScope.ANY, defaultcreds);
        }

        PostMethod metodo = new PostMethod(servidorTSA);
        metodo.addRequestHeader(CONTENT_TYPE, APPLICATION_TIMESTAMP_QUERY);
        ByteArrayInputStream datos = null;
        try {
            datos = new ByteArrayInputStream(peticion.getEncoded());
        } catch (IOException e) {
            log.error(MENSAJE_ERROR_PETICION + e.getMessage());
            throw new TSClienteError(
                    I18n.getResource(LIBRERIA_TSA_ERROR_11) + DOS_PUNTOS_ESPACIO + e.getMessage());
        }

        InputStreamRequestEntity rq = new InputStreamRequestEntity(datos);
        metodo.setRequestEntity(rq);

        metodo.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        byte[] cuerpoRespuesta = null;
        try {
            int estadoCodigo = cliente.executeMethod(metodo);
            log.info(MENSAJE_PETICION_TSA_ENVIADA);

            if (estadoCodigo != HttpStatus.SC_OK) {

                log.error(MENSAJE_FALLO_EJECUCION_METODO + metodo.getStatusLine());
                throw new TSClienteError(
                        I18n.getResource(LIBRERIA_TSA_ERROR_12) + DOS_PUNTOS_ESPACIO + metodo.getStatusLine());
            }

            cuerpoRespuesta = metodo.getResponseBody();
            log.info(MENSAJE_RESPUESTA_TSA_OBTENIDA);

            try {
                respuesta = new TimeStampResponse(cuerpoRespuesta);
                try {

                    respuesta.validate(peticion);

                    log.info(MENSAJE_RESPUESTA_TSA_VALIDADA_OK);
                    // Para solucionar bug en libreria bouncycastle
                    //return respuesta.getTimeStampToken().getEncoded();
                    //AppPerfect: Falso positivo
                    ASN1InputStream is = new ASN1InputStream(cuerpoRespuesta);
                    ASN1Sequence seq = ASN1Sequence.getInstance(is.readObject());
                    DEREncodable enc = seq.getObjectAt(1);
                    if (enc == null)
                        return null;
                    return enc.getDERObject().getEncoded();
                    //Fin Para solucionar bug en libreria bouncycastle
                } catch (TSPException e) {
                    log.error(MENSAJE_RESPUESTA_NO_VALIDA + e.getMessage());
                    throw new TSClienteError(
                            I18n.getResource(LIBRERIA_TSA_ERROR_9) + DOS_PUNTOS_ESPACIO + e.getMessage());
                }
            } catch (TSPException e) {
                log.error(MENSAJE_RESPUESTA_MAL_FORMADA + e.getMessage());
                throw new TSClienteError(
                        I18n.getResource(LIBRERIA_TSA_ERROR_8) + DOS_PUNTOS_ESPACIO + e.getMessage());
            } catch (IOException e) {

                log.error(MENSAJE_SECUENCIA_BYTES_MAL_CODIFICADA + e.getMessage());
                throw new TSClienteError(
                        I18n.getResource(LIBRERIA_TSA_ERROR_7) + DOS_PUNTOS_ESPACIO + e.getMessage());
            }
        } catch (HttpException e) {
            log.error(MENSAJE_VIOLACION_PROTOCOLO_HTTP + e.getMessage());
            throw new TSClienteError(
                    I18n.getResource(LIBRERIA_TSA_ERROR_6) + DOS_PUNTOS_ESPACIO + e.getMessage());
        } catch (IOException e) {
            String mensajeError = I18n.getResource(LIBRERIA_TSA_ERROR_4) + DOS_PUNTOS_ESPACIO + servidorTSA;
            log.error(MENSAJE_ERROR_CONEXION_SERVIDOR_OCSP + e.getMessage());

            throw new TSClienteError(mensajeError);
        } finally {
            // Termina la conexin
            metodo.releaseConnection();
        }
    }
}

From source file:es.uji.security.crypto.pdf.PdfPKCS7TSA.java

License:Mozilla Public License

/**                                                                       
 * Verifies a signature using the sub-filter adbe.x509.rsa_sha1.          
 * @param contentsKey the /Contents key                                   
 * @param certsKey the /Cert key                                          
 * @param provider the provider or <code>null</code> for the default provider
 *//*from  ww w  . j a  v  a2s.com*/
public PdfPKCS7TSA(byte[] contentsKey, byte[] certsKey, Provider provider) {
    try {
        this.provider = provider;
        X509CertParser cr = new X509CertParser();
        cr.engineInit(new ByteArrayInputStream(certsKey));
        certs = cr.engineReadAll();
        signCerts = certs;
        signCert = (X509Certificate) certs.iterator().next();
        crls = new ArrayList();
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(contentsKey));
        digest = ((DEROctetString) in.readObject()).getOctets();
        if (provider == null)
            sig = Signature.getInstance("SHA1withRSA");
        else
            sig = Signature.getInstance("SHA1withRSA", provider);
        sig.initVerify(signCert.getPublicKey());
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}