Example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers signedAndEnvelopedData

List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers signedAndEnvelopedData

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers signedAndEnvelopedData.

Prototype

ASN1ObjectIdentifier signedAndEnvelopedData

To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers signedAndEnvelopedData.

Click Source Link

Document

PKCS#7: 1.2.840.113549.1.7.4

Usage

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  av a  2  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 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);

}