Example usage for org.bouncycastle.asn1.cms SignedData getInstance

List of usage examples for org.bouncycastle.asn1.cms SignedData getInstance

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cms SignedData getInstance.

Prototype

public static SignedData getInstance(Object o) 

Source Link

Document

Return a SignedData object from the given object.

Usage

From source file:de.tsenger.animamea.Operator.java

License:Open Source License

private static SecurityInfos decodeEFCardSecurity(byte[] data) throws IOException, CertificateException,
        NoSuchProviderException, CMSException, OperatorCreationException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    ASN1Sequence asnSeq = (ASN1Sequence) ASN1Sequence.fromByteArray(data);
    ContentInfo contentInfo = ContentInfo.getInstance(asnSeq);
    DERSequence derSeq = (DERSequence) contentInfo.getContent();

    System.out.println("ContentType: " + contentInfo.getContentType().toString());
    SignedData cardSecurity = SignedData.getInstance(derSeq);

    //Get SecurityInfos
    ContentInfo encapContentInfo = cardSecurity.getEncapContentInfo();
    DEROctetString octString = (DEROctetString) encapContentInfo.getContent();
    SecurityInfos si = new SecurityInfos();
    si.decode(octString.getOctets());//  w w w.  j a  v a2  s.  c  o  m

    return si;
}

From source file:de.tsenger.sandbox.CardSecurityParser.java

License:Open Source License

/**
 * @param args/*from  w  w  w  .  java2 s  .  c  o m*/
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    byte[] efcsBytes = readBinaryFile("/home/tsenger/Desktop/EFCardSecurity.bin");
    ASN1Sequence asnSeq = (ASN1Sequence) ASN1Sequence.fromByteArray(efcsBytes);
    ContentInfo contentInfo = ContentInfo.getInstance(asnSeq);
    System.out.println(contentInfo.getContentType());
    DERSequence derSeq = (DERSequence) contentInfo.getContent();
    System.out.println(HexString.bufferToHex(derSeq.getEncoded(null)));
    SignedData signedData = SignedData.getInstance(derSeq);
    System.out.println("CMSVersion: " + signedData.getVersion().getValue().intValue());
    ContentInfo contentInfo2 = signedData.getEncapContentInfo();
    System.out.println(contentInfo2.getContentType());
    DEROctetString octString = (DEROctetString) contentInfo2.getContent();
    System.out.println("OctetString:\n" + HexString.bufferToHex(octString.getEncoded(null)));
    System.out.println("OctetString:\n" + HexString.bufferToHex(octString.getOctets()));

    SecurityInfos si = new SecurityInfos();
    si.decode(octString.getOctets());
    System.out.println(si);

    byte[] parameter = si.getChipAuthenticationPublicKeyInfoList().get(0).getPublicKey().getPublicKey();
    System.out.println(HexString.bufferToHex(parameter));
    System.out.println("Key Referenz: " + si.getChipAuthenticationPublicKeyInfoList().get(0).getKeyId());
    System.out.println("CA OID: "
            + si.getChipAuthenticationPublicKeyInfoList().get(0).getPublicKey().getAlgorithm().getAlgorithm());

}

From source file:dorkbox.build.util.jar.JarSignatureUtil.java

License:Apache License

/**
 * @return null if there is a problem with the certificate loading process.
 *//*from  w  w  w  .  j ava 2s  .  c o  m*/
public static final String extractSignatureHashFromSignatureBlock(byte[] signatureBlock) {
    ASN1InputStream sigStream = null;
    try {
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

        InputStream signatureIn = new ByteArrayInputStream(signatureBlock);
        sigStream = new ASN1InputStream(signatureIn);
        ASN1Primitive signatureASN = sigStream.readObject();
        ASN1Sequence seq = ASN1Sequence.getInstance(signatureASN);
        ASN1TaggedObject tagged = (ASN1TaggedObject) seq.getObjectAt(1);

        // Extract certificates
        SignedData newSignedData = SignedData.getInstance(tagged.getObject());

        @SuppressWarnings("rawtypes")
        Enumeration newSigOjects = newSignedData.getCertificates().getObjects();
        Object newSigElement = newSigOjects.nextElement();

        if (newSigElement instanceof DERSequence) {
            DERSequence newSigDERElement = (DERSequence) newSigElement;
            InputStream newSigIn = new ByteArrayInputStream(newSigDERElement.getEncoded());
            Certificate newSigCertificate = certFactory.generateCertificate(newSigIn);

            // certificate bytes
            byte[] newSigCertificateBytes = newSigCertificate.getEncoded();
            String encodeToString = Base64Fast.encodeToString(newSigCertificateBytes, false);
            return encodeToString;
        }
    } catch (IOException e) {
    } catch (CertificateException e) {
    } finally {
        Sys.close(sigStream);
    }
    return null;
}

From source file:dorkbox.build.util.jar.JarSignatureUtil.java

License:Apache License

/**
 * Verify that the two certificates MATCH from within a signature block (ie,
 * XXXXX.DSA in the META-INF directory).
 *
 * @return true if the two certificates are the same. false otherwise.
 *//* w  ww  .j av a 2 s .  c o  m*/
public static final boolean compareCertificates(byte[] newSignatureContainerBytes,
        byte[] oldSignatureContainerBytes) {
    ASN1InputStream newSigStream = null;
    ASN1InputStream oldSigStream = null;
    try {
        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

        InputStream newSignatureIn = new ByteArrayInputStream(newSignatureContainerBytes);
        newSigStream = new ASN1InputStream(newSignatureIn);
        ASN1Primitive newSigASNPrim = newSigStream.readObject();
        ContentInfo newSigContent = ContentInfo.getInstance(newSigASNPrim);

        InputStream oldSignatureIn = new ByteArrayInputStream(oldSignatureContainerBytes);
        oldSigStream = new ASN1InputStream(oldSignatureIn);
        ASN1Primitive oldSigASNPrim = oldSigStream.readObject();
        ContentInfo oldSigContent = ContentInfo.getInstance(oldSigASNPrim);

        // Extract certificates
        SignedData newSignedData = SignedData.getInstance(newSigContent.getContent());
        @SuppressWarnings("rawtypes")
        Enumeration newSigOjects = newSignedData.getCertificates().getObjects();

        SignedData oldSignedData = SignedData.getInstance(oldSigContent.getContent());
        @SuppressWarnings("rawtypes")
        Enumeration oldSigOjects = oldSignedData.getCertificates().getObjects();

        Object newSigElement = newSigOjects.nextElement();
        Object oldSigElement = oldSigOjects.nextElement();

        if (newSigElement instanceof DERSequence && oldSigElement instanceof DERSequence) {
            DERSequence newSigDERElement = (DERSequence) newSigElement;
            InputStream newSigIn = new ByteArrayInputStream(newSigDERElement.getEncoded());
            Certificate newSigCertificate = certFactory.generateCertificate(newSigIn);

            DERSequence oldSigDERElement = (DERSequence) oldSigElement;
            InputStream oldSigIn = new ByteArrayInputStream(oldSigDERElement.getEncoded());
            Certificate oldSigCertificate = certFactory.generateCertificate(oldSigIn);

            // certificate bytes
            byte[] newSigCertificateBytes = newSigCertificate.getEncoded();
            byte[] oldSigCertificateBytes = oldSigCertificate.getEncoded();

            return Arrays.equals(newSigCertificateBytes, oldSigCertificateBytes);
        }
    } catch (IOException e) {
    } catch (CertificateException e) {
    } finally {
        Sys.close(newSigStream);
        Sys.close(oldSigStream);
    }

    return false;
}

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

License:Open Source License

/**
 * Obtiene la información de diferentes tipos de formatos.
 * @param doj Etiqueta ASN.1 de la que se obtienen los datos.
 * @param envelopeType   Tipo de formato:
 * <li>0: EnvelopedData</li>
 * <li>1: AuthenticatedData</li>
 * <li>2: AuthEnvelopedData</li>
 * <li>3: SignedAndEnvelopedData</li>
 * <li>4: SignedData</li>/*from  w  w w.j av  a2 s.co m*/
 * <li>5: Encrypted</li>
 * @param tipoDetalle   Tipo de datos (literal)
 * @param signBinaryType Tipo de firmado binario (CADES o CMS)
 * @return  Representaci&oacute;n de los datos.
 */
private static String extractData(final ASN1TaggedObject doj, final int envelopeType, final String tipoDetalle,
        final int signBinaryType) {
    String detalle = ""; //$NON-NLS-1$
    detalle = detalle + tipoDetalle + CR;

    ASN1Set rins = null;
    EncryptedContentInfo encryptedContentInfo = null;
    ASN1Set unprotectedAttrs = null;
    ASN1Integer version = null;
    AlgorithmIdentifier aid = null;
    ContentInfo ci = null;
    ASN1Set authAttrs = null;
    ASN1Set ds = null;
    ASN1Set signerInfosSd = null;

    switch (envelopeType) {
    case TYPE_ENVELOPED_DATA:
        final EnvelopedData enveloped = EnvelopedData.getInstance(doj.getObject());
        version = enveloped.getVersion();
        rins = enveloped.getRecipientInfos();
        encryptedContentInfo = enveloped.getEncryptedContentInfo();
        unprotectedAttrs = enveloped.getUnprotectedAttrs();
        break;
    case TYPE_AUTHENTICATED_DATA:
        final AuthenticatedData authenticated = AuthenticatedData.getInstance(doj.getObject());
        version = authenticated.getVersion();
        rins = authenticated.getRecipientInfos();
        aid = authenticated.getMacAlgorithm();
        ci = authenticated.getEncapsulatedContentInfo();
        authAttrs = authenticated.getAuthAttrs();
        unprotectedAttrs = authenticated.getUnauthAttrs();
        break;
    case TYPE_AUTHENTICATED_ENVELOPED_DATA:
        final AuthEnvelopedData authEnveloped = AuthEnvelopedData.getInstance(doj.getObject());
        version = authEnveloped.getVersion();
        rins = authEnveloped.getRecipientInfos();
        encryptedContentInfo = authEnveloped.getAuthEncryptedContentInfo();
        authAttrs = authEnveloped.getAuthAttrs();
        unprotectedAttrs = authEnveloped.getUnauthAttrs();
        break;
    case TYPE_SIGNED_ENVELOPED_DATA:
        final SignedAndEnvelopedData signedEnv = new SignedAndEnvelopedData((ASN1Sequence) doj.getObject());
        version = signedEnv.getVersion();
        rins = signedEnv.getRecipientInfos();
        encryptedContentInfo = signedEnv.getEncryptedContentInfo();
        signerInfosSd = signedEnv.getSignerInfos();
        break;
    case TYPE_SIGNED_DATA:
        final SignedData signed = SignedData.getInstance(doj.getObject());
        version = signed.getVersion();
        ds = signed.getDigestAlgorithms();
        ci = signed.getEncapContentInfo();
        signerInfosSd = signed.getSignerInfos();
        break;
    case TYPE_ENCRYPTED_DATA:
        final ASN1Sequence encrypted = (ASN1Sequence) doj.getObject();
        version = ASN1Integer.getInstance(encrypted.getObjectAt(0));
        encryptedContentInfo = EncryptedContentInfo.getInstance(encrypted.getObjectAt(1));
        if (encrypted.size() == 3) {
            unprotectedAttrs = (ASN1Set) encrypted.getObjectAt(2);
        }
        break;
    default:
        throw new IllegalArgumentException("Tipo de sobre no soportado: " + envelopeType); //$NON-NLS-1$
    }

    //obtenemos la version
    detalle = detalle + AppletMessages.getString("CMSInformation.1") + SP + version + CR; //$NON-NLS-1$

    //recipientInfo
    if (rins != null) {
        if (envelopeType != TYPE_SIGNED_DATA && envelopeType != TYPE_ENCRYPTED_DATA && rins.size() > 0) {
            detalle = detalle + AppletMessages.getString("CMSInformation.13") + CR; //$NON-NLS-1$
        }
        for (int i = 0; i < rins.size(); i++) {
            final KeyTransRecipientInfo kti = KeyTransRecipientInfo
                    .getInstance(RecipientInfo.getInstance(rins.getObjectAt(i)).getInfo());
            detalle = detalle + AppletMessages.getString("CMSInformation.14") + SP + (i + 1) + ":" + CR; //$NON-NLS-1$//$NON-NLS-2$
            final AlgorithmIdentifier diAlg = kti.getKeyEncryptionAlgorithm();

            //issuer y serial
            final IssuerAndSerialNumber iss = (IssuerAndSerialNumber) SignerIdentifier
                    .getInstance(kti.getRecipientIdentifier().getId()).getId();
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.15") + SP //$NON-NLS-1$
                    + iss.getName().toString() + CR;
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.16") + SP + iss.getSerialNumber() //$NON-NLS-1$
                    + CR;

            // el algoritmo de cifrado de los datos
            AOCipherAlgorithm algorithm = null;
            final AOCipherAlgorithm[] algos = AOCipherAlgorithm.values();

            // obtenemos el algoritmo usado para cifrar la pass
            for (final AOCipherAlgorithm algo : algos) {
                if (algo.getOid().equals(diAlg.getAlgorithm().toString())) {
                    algorithm = algo;
                }
            }
            if (algorithm != null) {
                detalle = detalle + TB + AppletMessages.getString("CMSInformation.17") + SP //$NON-NLS-1$
                        + algorithm.getName() + CR;
            } else {
                detalle = detalle + TB + AppletMessages.getString("CMSInformation.18") + SP //$NON-NLS-1$
                        + diAlg.getAlgorithm() + CR;
            }
        }
    }

    if (envelopeType == TYPE_ENVELOPED_DATA || envelopeType == TYPE_ENCRYPTED_DATA) {
        //obtenemos datos de los datos cifrados.
        detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$
        detalle = detalle + getEncryptedContentInfo(encryptedContentInfo);
    } else if (envelopeType == TYPE_AUTHENTICATED_DATA && aid != null && ci != null) {
        // mac algorithm
        detalle = detalle + AppletMessages.getString("CMSInformation.20") + SP + aid.getAlgorithm() + CR; //$NON-NLS-1$

        //digestAlgorithm
        final ASN1Sequence seq = (ASN1Sequence) doj.getObject();
        final ASN1TaggedObject da = (ASN1TaggedObject) seq.getObjectAt(4);
        final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(da.getObject());
        detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$

        //obtenemos datos de los datos cifrados.
        detalle = detalle + AppletMessages.getString("CMSInformation.22") + SP + ci.getContentType() + CR; //$NON-NLS-1$

        detalle = getObligatorieAtrib(signBinaryType, detalle, authAttrs);
    } else if (envelopeType == TYPE_AUTHENTICATED_ENVELOPED_DATA) {
        detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$
        detalle = detalle + getEncryptedContentInfo(encryptedContentInfo);

        detalle = getObligatorieAtrib(signBinaryType, detalle, authAttrs);
    } else if (envelopeType == TYPE_SIGNED_ENVELOPED_DATA) {
        //algoritmo de firma
        final ASN1Sequence seq = (ASN1Sequence) doj.getObject();
        final ASN1Set da = (ASN1Set) seq.getObjectAt(2);
        final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(da.getObjectAt(0));
        detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$

        //obtenemos datos de los datos cifrados.
        detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$
        detalle = detalle + getEncryptedContentInfo(encryptedContentInfo);
    } else if (envelopeType == TYPE_SIGNED_DATA && ci != null && ds != null) {
        //algoritmo de firma
        final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(ds.getObjectAt(0));
        detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$
        detalle = detalle + AppletMessages.getString("CMSInformation.22") + SP + ci.getContentType() + CR; //$NON-NLS-1$
    }

    //obtenemos lo atributos opcionales
    if (envelopeType != TYPE_SIGNED_ENVELOPED_DATA) {
        if (unprotectedAttrs == null) {
            detalle = detalle + AppletMessages.getString("CMSInformation.28") + CR; //$NON-NLS-1$
        } else {
            final String atributos = getUnSignedAttributes(unprotectedAttrs.getObjects());
            detalle = detalle + AppletMessages.getString("CMSInformation.29") + CR; //$NON-NLS-1$
            detalle = detalle + atributos;
        }
    } else if ((envelopeType == TYPE_SIGNED_ENVELOPED_DATA || envelopeType == TYPE_SIGNED_DATA)
            && signerInfosSd != null) {
        //obtenemos el(los) firmate(s)
        if (signerInfosSd.size() > 0) {
            detalle = detalle + AppletMessages.getString("CMSInformation.30") + CR; //$NON-NLS-1$
        }
        for (int i = 0; i < signerInfosSd.size(); i++) {
            final SignerInfo si = SignerInfo.getInstance(signerInfosSd.getObjectAt(i));

            detalle = detalle + AppletMessages.getString("CMSInformation.31") + SP + (i + 1) + ":" + CR; //$NON-NLS-1$//$NON-NLS-2$
            // version
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.1") + SP + si.getVersion() + CR; //$NON-NLS-1$
            //signerIdentifier
            final SignerIdentifier sident = si.getSID();
            final IssuerAndSerialNumber iss = IssuerAndSerialNumber.getInstance(sident.getId());
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.15") + SP //$NON-NLS-1$
                    + iss.getName().toString() + CR;
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.16") + SP + iss.getSerialNumber() //$NON-NLS-1$
                    + CR;

            //digestAlgorithm
            final AlgorithmIdentifier algId = si.getDigestAlgorithm();
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.35") + SP + algId.getAlgorithm() //$NON-NLS-1$
                    + CR;

            //obtenemos lo atributos obligatorios
            final ASN1Set sa = si.getAuthenticatedAttributes();
            String satributes = ""; //$NON-NLS-1$
            if (sa != null) {
                satributes = getsignedAttributes(sa, signBinaryType);
            }
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.36") + CR; //$NON-NLS-1$
            detalle = detalle + satributes;
        }
    }
    return detalle;
}

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

License:Open Source License

/** M&eacute;todo que verifica que es una firma de tipo "Signed data"
 * @param data/*  www . j  a  v  a  2 s.c  om*/
 *        Datos CMS.
 * @return si es de este tipo. */
static boolean isCMSSignedData(final byte[] data) {
    boolean isValid = true;
    try {
        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();
        if (!doi.equals(PKCSObjectIdentifiers.signedData)) {
            isValid = false;
        } else {
            // Contenido de SignedData
            final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();
            final ASN1Sequence datos = (ASN1Sequence) doj.getObject();
            final SignedData sd = SignedData.getInstance(datos);
            final ASN1Set signerInfosSd = sd.getSignerInfos();

            for (int i = 0; isValid && i < signerInfosSd.size(); i++) {
                final SignerInfo si = SignerInfo.getInstance(signerInfosSd.getObjectAt(i));
                isValid = verifySignerInfo(si);
            }
        }
    } catch (final Exception ex) {
        isValid = false;
    }
    return isValid;
}

From source file:es.gob.afirma.signers.cades.CAdESValidator.java

License:Open Source License

/** Verifica si los datos proporcionados se corresponden con una estructura de tipo <i>SignedData</i>.
 * @param data Datos PKCS#7/CMS/CAdES./*w  w  w  .  j a  v a 2s .  co m*/
 * @param enforceCAdES Si se establece a <code>true</code> se comprueba que los SignerInfos sean expl&iacute;citamente
 *                     de tipo CAdES, si se establece a <code>false</code> no se comprueba, por lo que se aceptan
 *                     <code>SignedData</code> de CMS y PKCS#7.
 * @return <code>true</code> si los datos proporcionados se corresponden con una estructura de tipo <i>SignedData</i>,
 * <code>false</code> en caso contrario.
 * @throws IOException Si ocurren problemas leyendo los datos */
public static boolean isCAdESSignedData(final byte[] data, final boolean enforceCAdES) throws IOException {
    try {
        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.signedData)) {
            LOGGER.info(
                    "Los datos proporcionados no son de tipo SignedData de CAdES (no esta declarado el OID de SignedData)" //$NON-NLS-1$
            );
            return false;
        }

        // Contenido de SignedData
        final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();
        final ASN1Sequence datos = (ASN1Sequence) doj.getObject();
        final SignedData sd = SignedData.getInstance(datos);

        final ASN1Set signerInfosSd = sd.getSignerInfos();

        if (enforceCAdES) {
            for (int i = 0; i < signerInfosSd.size(); i++) {
                if (!verifySignerInfo(SignerInfo.getInstance(signerInfosSd.getObjectAt(i)))) {
                    LOGGER.info(
                            "Los datos proporcionados no son de tipo SignedData de CAdES (al menos un SignerInfo no se ha declarado de tipo CAdES)" //$NON-NLS-1$
                    );
                    return false;
                }
            }
        }

    } catch (final Exception ex) {
        LOGGER.info("Los datos proporcionados no son de tipo SignedData de CAdES: " + ex); //$NON-NLS-1$
        return false;
    }

    return true;
}

From source file:es.gob.afirma.signers.cms.CoSigner.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 sign Archivo que contiene las firmas.
 * @param omitContent Si se omite el contenido o no, es decir,si se hace de forma
 *                    Expl&iacute;cita o Impl&iacute;cita.
 * @param dataType Identifica el tipo del contenido a firmar.
 * @param key Clave privada del firmante.
 * @param certChain Cadena de certificados del firmante
 * @param atrib Atributos firmados opcionales.
 * @param uatrib Atributos no autenticados firmados opcionales.
 * @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 P7ContentSignerParameters parameters, final byte[] sign, final boolean omitContent,
        final String dataType, final PrivateKey key, final java.security.cert.Certificate[] certChain,
        final Map<String, byte[]> atrib, final Map<String, byte[]> uatrib, final byte[] messageDigest)
        throws IOException, NoSuchAlgorithmException, CertificateException {

    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    final ASN1InputStream is = new ASN1InputStream(sign);
    final ASN1Sequence dsq = (ASN1Sequence) is.readObject();
    is.close();//  ww w  .  ja va 2 s  .c om
    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();// contenido
    // del
    // SignedData

    final SignedData sd = SignedData.getInstance(contentSignedData);

    // 3. CONTENTINFO
    // si se introduce el contenido o no
    ContentInfo encInfo = null;
    final ASN1ObjectIdentifier contentTypeOID = new ASN1ObjectIdentifier(dataType);

    // Ya que el contenido puede ser grande, lo recuperamos solo una vez
    byte[] content2 = null;

    if (!omitContent) {
        final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        content2 = parameters.getContent();
        final CMSProcessable msg = new CMSProcessableByteArray(content2);
        try {
            msg.write(bOut);
        } catch (final Exception ex) {
            throw new IOException("Error en la escritura del procesable CMS: " + ex, ex); //$NON-NLS-1$
        }
        encInfo = new ContentInfo(contentTypeOID, new BEROctetString(bOut.toByteArray()));
    } else {
        encInfo = new ContentInfo(contentTypeOID, 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 (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);
    }

    // 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(((X509Certificate) certChain[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, content2 != null ? content2 : parameters.getContent(),
                dataType, atrib);
    } else {
        signedAttr = generateSignerInfoFromHash((X509Certificate) certChain[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 SignedData
    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, key);
    } catch (final Exception ex) {
        throw new IOException("Error al generar la firma: " + ex, ex); //$NON-NLS-1$
    }

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

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

}

From source file:es.gob.afirma.signers.cms.CoSigner.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   w ww.ja v a2 s  .  com*/
 * @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 key Clave privada del firmante.
 * @param atrib Atributos firmados adicionales.
 * @param uatrib Atributos no firmados adicionales.
 * @param digest 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.
 * @throws ContainsNoDataException Cuando la firma no contiene los datos
 *                                 ni fue generada con el mismo algoritmo de firma. */
byte[] coSigner(final String signatureAlgorithm, final X509Certificate[] signerCertificateChain,
        final byte[] sign, final String dataType, final PrivateKey key, final Map<String, byte[]> atrib,
        final Map<String, byte[]> uatrib, final byte[] digest)
        throws IOException, NoSuchAlgorithmException, CertificateException, ContainsNoDataException {

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

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

    final SignedData sd = SignedData.getInstance(contentSignedData);

    // 3. CONTENTINFO
    // si se introduce el contenido o no
    final ContentInfo encInfo = sd.getEncapContentInfo();

    final DEROctetString contenido = (DEROctetString) encInfo.getContent();
    byte[] contenidoDatos = null;
    if (contenido != null) {
        contenidoDatos = AOUtil.getDataFromInputStream(contenido.getOctetStream());
    }

    // 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 SignedData
    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);
                    messageDigest = derHash.getOctets();
                }
            }
        }
        signerInfos.add(si);
    }

    // atributos firmados
    if (contenidoDatos != null) {
        signedAttr = generateSignerInfo(digestAlgorithm, contenidoDatos, dataType, atrib);
    } else if (messageDigest != null) {
        signedAttr = generateSignerInfoFromHash(signerCertificateChain[0], messageDigest, dataType, atrib);
    } else {
        // 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
        throw new ContainsNoDataException(
                "No se puede crear la cofirma ya que no se han encontrado ni los datos firmados ni una huella digital compatible con el algoritmo de firma"); //$NON-NLS-1$
    }

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

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

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

}

From source file:es.gob.afirma.signers.cms.CounterSigner.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 ww. jav  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 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 AOException Cuando ocurre cualquier error no contemplado por el resto de
 *                     las 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 String dataType, final Map<String, byte[]> atri,
        final Map<String, byte[]> uatri)
        throws IOException, NoSuchAlgorithmException, CertificateException, AOException {

    this.atrib2 = atri;
    this.uatrib2 = uatri;

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

    if (certChain.length != 0) {
        vCertsSig.add(Certificate.getInstance(ASN1Primitive.fromByteArray(certChain[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, key, certChain);
    } // FIRMA DE LAS HOJAS
    else if (targetType.equals(CounterSignTarget.LEAFS)) {
        signerInfos = counterLeaf(signerInfosSd, parameters, key, certChain);
    } // 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, nodo);
            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);
    } 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, nodo);
            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);

}