Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

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

Introduction

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

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

From source file:ee.ria.xroad.proxy.messagelog.TimestamperUtil.java

License:Open Source License

static TimeStampResponse getTimestampResponse(InputStream in) throws Exception {
    TimeStampResp response = TimeStampResp.getInstance(new ASN1InputStream(in).readObject());

    if (response == null) {
        throw new RuntimeException("Could not read time-stamp response");
    }// www  . j a  v a 2s .c  om

    BigInteger status = response.getStatus().getStatus();

    log.trace("getTimestampDer() - TimeStampResp.status: {}", status);

    if (!PKIStatus.granted.getValue().equals(status) && !PKIStatus.grantedWithMods.getValue().equals(status)) {
        PKIFreeText statusString = response.getStatus().getStatusString();

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < statusString.size(); i++) {
            if (i > 0) {
                sb.append(", ");
            }

            sb.append("\"" + statusString.getStringAt(i) + "\"");
        }

        log.error("getTimestampDer() - TimeStampResp.status is not "
                + "\"granted\" neither \"grantedWithMods\": {}, {}", status, sb);

        throw new RuntimeException("TimeStampResp.status: " + status + ", .statusString: " + sb);
    }

    return new TimeStampResponse(response);
}

From source file:es.gob.afirma.applet.CMSInformation.java

License:Open Source License

/**
 * M&eacute;todo principal que obtiene la informaci&oacute;n a partir de un fichero firmado
 * de tipo CMS./*www  . j  a  v  a 2s.c  o m*/
 * @param data Objeto CMS.
 * @return Texto descriptivo del objeto CMS.
 * @throws IOException Si ocurre alg&uacute;n problema leyendo o escribiendo los datos
 * @throws AOInvalidFormatException Error de formato no v&aacute;lido.
 */
static String getInformation(final byte[] data) throws IOException, AOInvalidFormatException {

    final ASN1InputStream is = new ASN1InputStream(data);

    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    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();

    final String datos;
    if (doi.equals(PKCSObjectIdentifiers.data)) {
        datos = AppletMessages.getString("CMSInformation.0") + SP + DATA + CR; //$NON-NLS-1$
    } else if (doi.equals(PKCSObjectIdentifiers.digestedData)) {
        datos = getFromDigestedData(doj);
    } else if (doi.equals(PKCSObjectIdentifiers.encryptedData)) {

        datos = extractData(doj, TYPE_ENCRYPTED_DATA,
                AppletMessages.getString("CMSInformation.0") + SP + ENCRYPTED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$
    } else if (doi.equals(PKCSObjectIdentifiers.signedData)) {
        datos = extractData(doj, TYPE_SIGNED_DATA,
                AppletMessages.getString("CMSInformation.0") + SP + SIGNED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$
    } else if (doi.equals(PKCSObjectIdentifiers.envelopedData)) {
        datos = extractData(doj, TYPE_ENVELOPED_DATA,
                AppletMessages.getString("CMSInformation.0") + SP + ENVELOPED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$
    } else if (doi.equals(PKCSObjectIdentifiers.signedAndEnvelopedData)) {
        datos = extractData(doj, TYPE_SIGNED_ENVELOPED_DATA,
                AppletMessages.getString("CMSInformation.0") + SP + SIGNED_ENVELOPED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$
    } else if (doi.equals(PKCSObjectIdentifiers.id_ct_authData)) {
        datos = extractData(doj, TYPE_AUTHENTICATED_DATA,
                AppletMessages.getString("CMSInformation.0") + SP + AUTHENTICATED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$
    } else if (doi.equals(PKCSObjectIdentifiers.id_ct_authEnvelopedData)) {
        datos = extractData(doj, TYPE_AUTHENTICATED_ENVELOPED_DATA,
                AppletMessages.getString("CMSInformation.0") + SP + AUTH_ENVELOPED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$
    } else if (doi.equals(CMSObjectIdentifiers.compressedData)) {
        datos = getFromCompressedData(doj);
    } else {
        throw new AOInvalidFormatException(
                "Los datos introducidos no se corresponden con un tipo de objeto CMS soportado"); //$NON-NLS-1$
    }

    return datos;
}

From source file:es.gob.afirma.envelopers.cades.CAdESEPESSignedAndEnvelopedData.java

License:Open Source License

/** M&eacute;todo que inserta remitentes en el "OriginatorInfo" de un sobre
 * de tipo AuthenticatedEnvelopedData.//from   w w  w  . ja v a  2s  .c o m
 * @return La nueva firma AuthenticatedEnvelopedData con los remitentes que
 *         ten&iacute;a (si los tuviera) con la cadena de certificados
 *         nueva.
 * @throws IOException */
byte[] addOriginatorInfo(final InputStream data, final P7ContentSignerParameters parameters,
        final X509Certificate[] signerCertificateChain, final PrivateKeyEntry keyEntry, final AdESPolicy policy)
        throws IOException {
    // boolean isValid = false;
    byte[] retorno = 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 DERObjectIdentifier doi = (DERObjectIdentifier) e.nextElement();
    if (doi.equals(PKCSObjectIdentifiers.signedAndEnvelopedData)) {
        // Contenido de Data
        final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();

        final SignedAndEnvelopedData signEnv = new SignedAndEnvelopedData((ASN1Sequence) doj.getObject());

        // Obtenemos los originatorInfo
        final ASN1EncodableVector signerInfos = new ASN1EncodableVector();
        final Enumeration<?> signers = signEnv.getSignerInfos().getObjects();
        while (signers.hasMoreElements()) {
            signerInfos.add((ASN1Sequence) signers.nextElement());
        }

        ASN1EncodableVector signCerts = new ASN1EncodableVector();

        // Si no hay certificados, se deja como esta.
        if (signerCertificateChain.length != 0) {

            // algoritmo
            final String signatureAlgorithm;
            final String digestAlgorithm;
            final ASN1EncodableVector digestAlgs = new ASN1EncodableVector();

            signatureAlgorithm = parameters.getSignatureAlgorithm();
            digestAlgorithm = AOSignConstants.getDigestAlgorithmName(signatureAlgorithm);

            AlgorithmIdentifier digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm));
            digestAlgs.add(digAlgId);

            final TBSCertificateStructure tbs2;
            try {
                tbs2 = TBSCertificateStructure.getInstance(
                        ASN1Primitive.fromByteArray(signerCertificateChain[0].getTBSCertificate()));
            } catch (final CertificateEncodingException ex) {
                throw new IOException("Error en la codificacion del certificado del firmante", ex); //$NON-NLS-1$
            }

            final IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(
                    X500Name.getInstance(tbs2.getIssuer()), tbs2.getSerialNumber().getValue());

            final SignerIdentifier identifier = new SignerIdentifier(encSid);

            // AlgorithmIdentifier
            digAlgId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(AOAlgorithmID.getOID(digestAlgorithm)),
                    new DERNull());

            // // ATRIBUTOS
            final ASN1EncodableVector contextExpecific;
            try {
                contextExpecific = CAdESUtils.generateSignerInfo(signerCertificateChain[0], digestAlgorithm,
                        parameters.getContent(), policy, null);
            } catch (final CertificateEncodingException ex) {
                throw new IOException("Error en la codificacion del certificado del firmante", ex); //$NON-NLS-1$
            } catch (final NoSuchAlgorithmException ex) {
                throw new IOException("Error generacion del SignerInfo", ex); //$NON-NLS-1$
            }

            this.signedAttr2 = SigUtils.getAttributeSet(new AttributeTable(contextExpecific));
            final ASN1Set signedAttr = SigUtils.getAttributeSet(new AttributeTable(contextExpecific));

            final ASN1Set unSignedAttr = null;

            // digEncryptionAlgorithm
            final SignerInfo nuevoSigner = CAdESUtils.signAndEnvelope(keyEntry, signatureAlgorithm, digAlgId,
                    identifier, signedAttr, unSignedAttr, "RSA", //$NON-NLS-1$
                    this.signedAttr2);

            // introducimos el nuevo Signer
            signerInfos.add(nuevoSigner);

            // LISTA DE CERTIFICADOS: obtenemos la lista de certificados
            try {
                signCerts = CAdESUtils.loadCertificatesList(signEnv, signerCertificateChain);
            } catch (final CertificateEncodingException ex) {
                throw new IOException("Error en la codificacion de los certificados del firmante", ex); //$NON-NLS-1$
            }
        } else {
            LOGGER.warning("No se ha podido obtener el certificado del nuevo firmante "); //$NON-NLS-1$
        }

        final ASN1Set certrevlist = null;

        // Se crea un nuevo AuthenticatedEnvelopedData a partir de los
        // datos anteriores con los nuevos originantes.
        retorno = new ContentInfo(PKCSObjectIdentifiers.signedAndEnvelopedData,
                new SignedAndEnvelopedData(signEnv.getRecipientInfos(), signEnv.getDigestAlgorithms(),
                        signEnv.getEncryptedContentInfo(), // encInfo,
                        new DERSet(signCerts), // certificates,
                        certrevlist, // certrevlist,
                        new DERSet(signerInfos))).getEncoded(ASN1Encoding.DER);
    }

    return retorno;
}

From source file:es.gob.afirma.envelopers.cades.CAdESUtils.java

License:Open Source License

/** Obtiene el contenido de un archivo encriptado
 * @param file Archivo con los datos/*from  w  ww.  j  a  va 2 s.  co m*/
 * @param config Configuracion de cifrado
 * @param params Parametros
 * @param cipher Encriptador */
private static EncryptedContentInfo getEncryptedContentInfo(final byte[] file, final AOCipherConfig config,
        final AlgorithmParameterSpec params, final Cipher cipher) throws IOException {
    final byte[] ciphered;
    try {
        ciphered = cipher.doFinal(file);
    } catch (final Exception e) {
        LOGGER.severe("No se ha podido completar el cifrado, se devolvera null: " + e); //$NON-NLS-1$
        return null;
    }

    ASN1Encodable asn1Params;
    if (params != null) {
        final ASN1InputStream aIn = new ASN1InputStream(cipher.getParameters().getEncoded("ASN.1")); //$NON-NLS-1$
        asn1Params = aIn.readObject();
        aIn.close();
    } else {
        asn1Params = new DERNull();
    }

    // obtenemos el OID del algoritmo de cifrado
    final AlgorithmIdentifier encAlgId = new AlgorithmIdentifier(
            new ASN1ObjectIdentifier(config.getAlgorithm().getOid()), asn1Params);

    // Obtenemos el identificador
    final ASN1ObjectIdentifier contentType = PKCSObjectIdentifiers.encryptedData;
    return new EncryptedContentInfo(contentType, encAlgId, new DEROctetString(ciphered));
}

From source file:es.gob.afirma.envelopers.cms.CMSAuthenticatedData.java

License:Open Source License

/** M&eacute;todo que inserta remitentes en el "OriginatorInfo" de un sobre
 * de tipo AuthenticatedData.//from www. ja v  a 2  s.  com
 * @param data
 *        fichero que tiene la firma.
 * @param signerCertificateChain
 *        Cadena de certificados a agregar.
 * @return La nueva firma AuthenticatedData con los remitentes que
 *         ten&iacute;a (si los tuviera) con la cadena de certificados
 *         nueva.
 * @throws IOException Si hay errores de lectura o escritura de datos
 * @throws CertificateEncodingException Si el certificado del remitente es invalido */
static byte[] addOriginatorInfo(final InputStream data, final X509Certificate[] signerCertificateChain)
        throws IOException, CertificateEncodingException {

    final ASN1InputStream is = new ASN1InputStream(data);
    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    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();
    if (doi.equals(PKCSObjectIdentifiers.id_ct_authData)) {
        // Contenido de Data
        final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();

        final AuthenticatedData auth = AuthenticatedData.getInstance(doj.getObject());

        final AlgorithmIdentifier digAlg = extractAOIfromAuth((ASN1Sequence) doj.getObject());

        // Obtenemos los originatorInfo
        OriginatorInfo origInfo = auth.getOriginatorInfo();
        ASN1Set certs = null;
        if (origInfo != null) {
            certs = origInfo.getCertificates();
        }

        final OriginatorInfo origInfoChecked = Utils.checkCertificates(signerCertificateChain, certs);
        if (origInfoChecked != null) {
            origInfo = origInfoChecked;
        }

        // Se crea un nuevo AuthenticatedData a partir de los datos
        // anteriores con los nuevos originantes.
        return new ContentInfo(PKCSObjectIdentifiers.id_ct_authData, new AuthenticatedData(origInfo, // OriginatorInfo
                auth.getRecipientInfos(), // ASN1Set
                auth.getMacAlgorithm(), // macAlgorithm
                digAlg, // AlgorithmIdentifier se les ha olvidado a BC implementar el getDigestAlgorithm
                auth.getEncapsulatedContentInfo(), // ContentInfo
                auth.getAuthAttrs(), // ASN1Set
                auth.getMac(), // ASN1OctetString
                auth.getUnauthAttrs() // ASN1Set
        )).getEncoded(ASN1Encoding.DER);
    }
    return null;
}

From source file:es.gob.afirma.envelopers.cms.CMSAuthenticatedEnvelopedData.java

License:Open Source License

/** M&eacute;todo que inserta remitentes en el "OriginatorInfo" de un sobre
 * de tipo AuthenticatedEnvelopedData./*from w w w. j av a 2 s  .c o m*/
 * @param data
 *        Datos CMS de tipo AuthenticatedEnvelopedData.
 * @param signerCertificateChain
 *        Cadena de certificados a agregar.
 * @return La nueva firma AuthenticatedEnvelopedData con los remitentes que
 *         ten&iacute;a (si los tuviera) con la cadena de certificados
 *         nueva.
 * @throws IOException Cuando hay errores de lectura o escritura de datos
 * @throws CertificateEncodingException Si hay alg&uacute;n certificado inv&aacute;lido en la cadena */
public static byte[] addOriginatorInfo(final byte[] data, final X509Certificate[] signerCertificateChain)
        throws IOException, CertificateEncodingException {

    final ASN1InputStream is = new ASN1InputStream(data);
    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    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();

    if (doi.equals(PKCSObjectIdentifiers.id_ct_authEnvelopedData)) {
        // Contenido de Data
        final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();

        final AuthEnvelopedData authEnv = AuthEnvelopedData.getInstance(doj.getObject());

        // Obtenemos los originatorInfo
        OriginatorInfo origInfo = authEnv.getOriginatorInfo();
        ASN1Set certs = null;
        if (origInfo != null) {
            certs = origInfo.getCertificates();
        }

        final OriginatorInfo origInfoChecked = Utils.checkCertificates(signerCertificateChain, certs);
        if (origInfoChecked != null) {
            origInfo = origInfoChecked;
        }

        // Se crea un nuevo AuthenticatedEnvelopedData a partir de los
        // datos anteriores con los nuevos originantes.
        return new ContentInfo(PKCSObjectIdentifiers.id_ct_authEnvelopedData, new AuthEnvelopedData(origInfo, // OriginatorInfo
                authEnv.getRecipientInfos(), // ASN1Set
                authEnv.getAuthEncryptedContentInfo(), authEnv.getAuthAttrs(), authEnv.getMac(),
                authEnv.getUnauthAttrs())).getEncoded(ASN1Encoding.DER);
    }

    return null;
}

From source file:es.gob.afirma.envelopers.cms.CMSEnvelopedData.java

License:Open Source License

/** M&eacute;todo que inserta remitentes en el "OriginatorInfo" de un sobre
 * de tipo envelopedData.//from w w  w  .j  a  v  a2 s .com
 * @param data
 *        Datos CMS que admiten multiples remitentes/firmantes.
 * @param signerCertificateChain
 *        Cadena de certificados a agregar.
 * @return La nueva firma enveloped con los remitentes que ten&iacute;a (si
 *         los tuviera) con la cadena de certificados nueva.
 * @throws IOException Si hay errores de lectura de datos
 * @throws CertificateEncodingException Cuando el certificado proporcionado es inv&aacute;lido */
public static byte[] addOriginatorInfo(final byte[] data, final X509Certificate[] signerCertificateChain)
        throws IOException, CertificateEncodingException {

    final ASN1InputStream is = new ASN1InputStream(data);
    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    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();
    if (doi.equals(PKCSObjectIdentifiers.envelopedData)) {
        // Contenido de Data
        final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();

        final EnvelopedData ed = EnvelopedData.getInstance(doj.getObject());

        // Obtenemos los originatorInfo
        OriginatorInfo origInfo = ed.getOriginatorInfo();
        ASN1Set certs = null;
        if (origInfo != null) {
            certs = origInfo.getCertificates();
        }

        // Si no hay certificados, se deja como esta.
        final OriginatorInfo origInfoChecked = Utils.checkCertificates(signerCertificateChain, certs);
        if (origInfoChecked != null) {
            origInfo = origInfoChecked;
        }

        // Se crea un nuevo EnvelopedData a partir de los datos
        // anteriores con los nuevos originantes.
        return new ContentInfo(PKCSObjectIdentifiers.envelopedData, new EnvelopedData(origInfo,
                ed.getRecipientInfos(), ed.getEncryptedContentInfo(), ed.getUnprotectedAttrs()))
                        .getEncoded(ASN1Encoding.DER);
    }

    return null;
}

From source file:es.gob.afirma.envelopers.cms.CoSignerEnveloped.java

License:Open Source License

/** Constructor de la clase. Se crea una cofirma a partir de los datos del
 * firmante, el archivo que se firma y del archivo que contiene las firmas.
 * @param parameters par&aacute;metros necesarios que contienen tanto la firma del
 *                   archivo a firmar como los datos del firmante.
 * @param signerCertificateChain Cadena de certificados del firmante.
 * @param sign Archivo que contiene las firmas.
 * @param dataType Identifica el tipo del contenido a firmar.
 * @param keyEntry Clave privada del firmante.
 * @param atrib Atributos firmados opcion   ales.
 * @param uatrib Atributos no autenticados firmados opcionales.
 * @param messageDigest Huella digital a aplicar en la firma.
 * @return El archivo de firmas con la nueva firma.
 * @throws java.io.IOException Si ocurre alg&uacute;n problema leyendo o escribiendo los
 *                             datos//from   w  ww.  j  a va 2 s  .  com
 * @throws java.security.NoSuchAlgorithmException Si no se soporta alguno de los algoritmos de firma o huella
 *                                                digital
 * @throws java.security.cert.CertificateException Si se produce alguna excepci&oacute;n con los certificados de
 *                                                 firma. */
byte[] coSigner(final P7ContentSignerParameters parameters, final X509Certificate[] signerCertificateChain,
        final byte[] sign, final String dataType, final PrivateKeyEntry keyEntry,
        final Map<String, byte[]> atrib, final Map<String, byte[]> uatrib, final byte[] messageDigest)
        throws IOException, NoSuchAlgorithmException, CertificateException {

    final ASN1InputStream is = new ASN1InputStream(sign);

    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    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();// contenido
    // del
    // signedAndEnvelopedData

    final SignedAndEnvelopedData sd = new SignedAndEnvelopedData(contentSignedData);

    // 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());
    }

    if (signerCertificateChain.length != 0) {
        final List<ASN1Encodable> ce = new ArrayList<ASN1Encodable>();
        for (final X509Certificate element : signerCertificateChain) {
            ce.add(Certificate.getInstance(ASN1Primitive.fromByteArray(element.getEncoded())));
        }
        certificates = SigUtils.fillRestCerts(ce, vCertsSig);
    }

    // buscamos que timo de algoritmo es y lo codificamos con su OID
    final String signatureAlgorithm = parameters.getSignatureAlgorithm();
    final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(signatureAlgorithm);
    final AlgorithmIdentifier digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm));

    // Identificador del firmante ISSUER AND SERIAL-NUMBER
    final TBSCertificateStructure tbs = TBSCertificateStructure
            .getInstance(ASN1Primitive.fromByteArray(signerCertificateChain[0].getTBSCertificate()));
    final IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(X500Name.getInstance(tbs.getIssuer()),
            tbs.getSerialNumber().getValue());
    final SignerIdentifier identifier = new SignerIdentifier(encSid);

    // // ATRIBUTOS

    // atributos firmados
    ASN1Set signedAttr = null;
    if (messageDigest == null) {
        signedAttr = generateSignerInfo(digestAlgorithm, parameters.getContent(), dataType, atrib);
    } else {
        signedAttr = generateSignerInfoFromHash(signerCertificateChain[0], messageDigest, dataType, atrib);
    }

    // atributos no firmados.
    final ASN1Set unSignedAttr = generateUnsignerInfo(uatrib);

    // // FIN ATRIBUTOS

    // digEncryptionAlgorithm
    final AlgorithmIdentifier encAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID("RSA")); //$NON-NLS-1$

    // 5. SIGNERINFO
    // raiz de la secuencia de SignerInfo
    // Obtenemos los signerInfos del signedAndEnvelopedData
    final ASN1Set signerInfosSd = sd.getSignerInfos();

    // introducimos los SignerInfos Existentes
    final ASN1EncodableVector signerInfos = new ASN1EncodableVector();
    // introducimos el nuevo SignerInfo del firmante actual.

    for (int i = 0; i < signerInfosSd.size(); i++) {
        final SignerInfo si = SignerInfo.getInstance(signerInfosSd.getObjectAt(i));
        signerInfos.add(si);
    }

    final ASN1OctetString sign2;
    try {
        sign2 = firma(signatureAlgorithm, keyEntry);
    } catch (final Exception ex) {
        throw new IOException("Error al generar la firma: " + ex, ex); //$NON-NLS-1$
    }

    // Creamos los signerInfos del signedAndEnvelopedData
    signerInfos.add(new SignerInfo(identifier, digAlgId, signedAttr, encAlgId, sign2, unSignedAttr));

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

}

From source file:es.gob.afirma.envelopers.cms.CoSignerEnveloped.java

License:Open Source License

/** Constructor de la clase. Se crea una cofirma a partir de los datos del
 * firmante y el archivo que se firma./*from   ww w  .java 2  s .c  o  m*/
 * @param signatureAlgorithm
 *        Algoritmo para la firma
 * @param signerCertificateChain
 *        Cadena de certificados para la construccion de los parametros
 *        de firma.
 * @param sign
 *        Archivo que contiene las firmas.
 * @param dataType
 *        Identifica el tipo del contenido a firmar.
 * @param keyEntry
 *        Clave privada del firmante.
 * @param atrib
 *        Atributos firmados adicionales.
 * @param uatrib
 *        Atributos no firmados adicionales.
 * @param messageDigest
 *        Hash a aplicar en la firma.
 * @return El archivo de firmas con la nueva firma.
 * @throws java.io.IOException
 *         Si ocurre alg&uacute;n problema leyendo o escribiendo los
 *         datos
 * @throws java.security.NoSuchAlgorithmException
 *         Si no se soporta alguno de los algoritmos de firma o huella
 *         digital
 * @throws java.security.cert.CertificateException
 *         Si se produce alguna excepci&oacute;n con los certificados de
 *         firma. */
byte[] coSigner(final String signatureAlgorithm, final X509Certificate[] signerCertificateChain,
        final byte[] sign, final String dataType, final PrivateKeyEntry keyEntry,
        final Map<String, byte[]> atrib, final Map<String, byte[]> uatrib, final byte[] messageDigest)
        throws IOException, NoSuchAlgorithmException, CertificateException {

    final ASN1InputStream is = new ASN1InputStream(sign);

    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    ASN1Sequence dsq = null;
    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();// contenido
    // del
    // signedAndEnvelopedData

    final SignedAndEnvelopedData sd = new SignedAndEnvelopedData(contentSignedData);

    byte[] md = messageDigest != null ? messageDigest.clone() : null;

    // 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());
    }

    if (signerCertificateChain.length != 0) {
        final List<ASN1Encodable> ce = new ArrayList<ASN1Encodable>();
        for (final X509Certificate element : signerCertificateChain) {
            ce.add(Certificate.getInstance(ASN1Primitive.fromByteArray(element.getEncoded())));
        }
        certificates = SigUtils.fillRestCerts(ce, vCertsSig);
    }

    // buscamos que tipo de algoritmo es y lo codificamos con su OID
    final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(signatureAlgorithm);
    final AlgorithmIdentifier digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm));

    // Identificador del firmante ISSUER AND SERIAL-NUMBER
    final TBSCertificateStructure tbs = TBSCertificateStructure
            .getInstance(ASN1Primitive.fromByteArray(signerCertificateChain[0].getTBSCertificate()));
    final IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(X500Name.getInstance(tbs.getIssuer()),
            tbs.getSerialNumber().getValue());
    final SignerIdentifier identifier = new SignerIdentifier(encSid);

    // // ATRIBUTOS

    // atributos firmados
    ASN1Set signedAttr = null;

    // atributos no firmados.
    final ASN1Set unSignedAttr = generateUnsignerInfo(uatrib);

    // // FIN ATRIBUTOS

    // digEncryptionAlgorithm
    final AlgorithmIdentifier encAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID("RSA")); //$NON-NLS-1$

    // 5. SIGNERINFO
    // raiz de la secuencia de SignerInfo
    // Obtenemos los signerInfos del signedAndEnvelopedData
    final ASN1Set signerInfosSd = sd.getSignerInfos();

    // introducimos los SignerInfos Existentes
    final ASN1EncodableVector signerInfos = new ASN1EncodableVector();
    // introducimos el nuevo SignerInfo del firmante actual.

    // Secuencia:
    // 1.- Si cofirmamos sin datos en el mismo algoritmo de hash que la firma
    //     original sacamos el messagedigest de la firma previa.
    // 2.- Si no es el mismo algoritmo, miramos si nos ha llegado un messagedigest
    //     como parametro del metodo, que quiere decir que se ha calculado externamente
    //     (en el fondo sera que no se ha sobreescrito el parametro, con lo que
    //     si llego != null, seguira siendo != null)
    // 3.- Si no es ninguno de los dos casos, no podemos firmar
    for (int i = 0; i < signerInfosSd.size(); i++) {
        final SignerInfo si = SignerInfo.getInstance(signerInfosSd.getObjectAt(i));
        final AlgorithmIdentifier algHash = si.getDigestAlgorithm();
        // Solo si coninciden los algos puedo sacar el hash de dentro
        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().toString().equals(oids.toString())) {
                    final DERSet derSetHash = (DERSet) elemento.getObjectAt(1);
                    final DEROctetString derHash = (DEROctetString) derSetHash.getObjectAt(0);
                    md = derHash.getOctets();
                }
            }
        }
        signerInfos.add(si);
    }

    // En este caso no puedo usar un hash de fuera, ya que no me han
    // pasado datos ni huellas digitales, solo un fichero de firma
    if (md == null) {
        throw new IllegalStateException("No se puede crear la firma ya que no se ha encontrado un hash valido"); //$NON-NLS-1$
    }

    signedAttr = generateSignerInfoFromHash(signerCertificateChain[0], messageDigest, dataType, atrib);

    final ASN1OctetString sign2;
    try {
        sign2 = firma(signatureAlgorithm, keyEntry);
    } catch (final Exception ex) {
        throw new IOException("Error al generar la firma: " + ex, ex); //$NON-NLS-1$
    }

    // Creamos los signerInfos del signedAndEnvelopedData
    signerInfos.add(new SignerInfo(identifier, digAlgId, signedAttr, encAlgId, sign2, unSignedAttr// null //unsignedAttr
    ));

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

}

From source file:es.gob.afirma.envelopers.cms.CounterSignerEnveloped.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   w w  w . j av  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 signerCertificateChain Cadena de certificados 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 keyEntry Clave privada a usar para firmar.
 * @param dataType Identifica el tipo del contenido a firmar.
 * @param atri Atributo firmado que agregar a la firma.
 * @param uatri Atributo no firmado que agregar a la firma.
 * @return El archivo de firmas con la nueva firma.
 * @throws java.io.IOException Si ocurre alg&uacute;n problema leyendo o escribiendo los
 *                             datos
 * @throws java.security.NoSuchAlgorithmException Si no se soporta alguno de los algoritmos de firma o huella
 *                                                digital.
 * @throws java.security.cert.CertificateException Si se produce alguna excepci&oacute;n con los certificados de
 *                                                 firma.
 * @throws SignatureException Cuando ocurren problemas en la firma PKCS#1.
 * @throws InvalidKeyException Cuando hay problemas de adecuaci&oacute;n de la clave. */
byte[] counterSignerEnveloped(final P7ContentSignerParameters parameters,
        final X509Certificate[] signerCertificateChain, final byte[] data, final CounterSignTarget targetType,
        final int[] targets, final PrivateKeyEntry keyEntry, final String dataType,
        final Map<String, byte[]> atri, final Map<String, byte[]> uatri) throws IOException,
        NoSuchAlgorithmException, CertificateException, InvalidKeyException, SignatureException {

    // Inicializamos el Oid
    this.atrib2 = atri;
    this.uatrib2 = uatri;

    final ASN1InputStream is = new ASN1InputStream(data);

    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    final Enumeration<?> e = ((ASN1Sequence) is.readObject()).getObjects();
    is.close();
    // Elementos que contienen los elementos OID signedAndEnvelopedData
    e.nextElement();
    // Contenido de signedAndEnvelopedData
    final ASN1Sequence contentSignedData = (ASN1Sequence) ((ASN1TaggedObject) e.nextElement()).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());
    }
    if (signerCertificateChain.length != 0) {
        vCertsSig.add(
                Certificate.getInstance(ASN1Primitive.fromByteArray(signerCertificateChain[0].getEncoded())));
        certificates = new BERSet(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, signerCertificateChain[0], keyEntry);
    } // FIRMA DE LAS HOJAS
    else if (targetType.equals(CounterSignTarget.LEAFS)) {
        signerInfos = counterLeaf(signerInfosSd, parameters, signerCertificateChain[0], keyEntry);
    } // 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, signerCertificateChain[0], keyEntry, nodo);
            sigDat = new SignedAndEnvelopedData(sd.getRecipientInfos(), sd.getDigestAlgorithms(),
                    sd.getEncryptedContentInfo(), certificates, certrevlist, new DERSet(signerInfos));

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

        // construimos el Signed Data y lo devolvemos
        return new ContentInfo(PKCSObjectIdentifiers.signedAndEnvelopedData, aux).getEncoded(ASN1Encoding.DER);
    } 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, signerCertificateChain[0], keyEntry, nodo);
            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);

}