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

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

Introduction

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

Prototype

ASN1ObjectIdentifier data

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

Click Source Link

Document

PKCS#7: 1.2.840.113549.1.7.1

Usage

From source file:es.gob.afirma.signers.cms.AOCMSSigner.java

License:Open Source License

/** {@inheritDoc} */
@Override//w  ww  . j a  va2s  .  c o  m
public byte[] cosign(final byte[] data, final byte[] sign, final String algorithm, final PrivateKey key,
        final java.security.cert.Certificate[] certChain, final Properties xParams)
        throws AOException, IOException {

    new BCChecker().checkBouncyCastle();

    final Properties extraParams = xParams != null ? xParams : new Properties();

    final String precalculatedDigest = extraParams.getProperty("precalculatedHashAlgorithm"); //$NON-NLS-1$

    byte[] messageDigest = null;
    if (precalculatedDigest != null) {
        messageDigest = data;
    }

    final P7ContentSignerParameters csp = new P7ContentSignerParameters(data, algorithm);

    // tipos de datos a firmar.
    if (this.dataType == null) {
        this.dataType = PKCSObjectIdentifiers.data.getId();
    }

    final String mode = extraParams.getProperty("mode", AOSignConstants.DEFAULT_SIGN_MODE); //$NON-NLS-1$

    final boolean omitContent = mode.equals(AOSignConstants.SIGN_MODE_EXPLICIT) || precalculatedDigest != null;

    // Si la firma que nos introducen es SignedData
    if (ValidateCMSSignedData.isCMSSignedData(sign)) {
        try {
            return new CoSigner().coSigner(csp, sign, omitContent, this.dataType, key, certChain, this.atrib,
                    this.uatrib, messageDigest);
        } catch (final Exception e) {
            throw new AOException("Error generando la Cofirma PKCS#7", e); //$NON-NLS-1$
        }
    }
    throw new AOException("Los datos no se corresponden con una firma CMS valida"); //$NON-NLS-1$
}

From source file:es.gob.afirma.signers.cms.AOCMSSigner.java

License:Open Source License

/** {@inheritDoc} */
@Override/*from  www. j  av  a  2 s.c om*/
public byte[] cosign(final byte[] sign, final String algorithm, final PrivateKey key,
        final java.security.cert.Certificate[] certChain, final Properties extraParams)
        throws AOException, IOException {

    new BCChecker().checkBouncyCastle();

    // tipos de datos a firmar.
    if (this.dataType == null) {
        this.dataType = PKCSObjectIdentifiers.data.getId();
    }

    // Si la firma que nos introducen es SignedData
    if (ValidateCMSSignedData.isCMSSignedData(sign)) {
        // Cofirma de la firma usando unicamente el fichero de firmas.
        try {
            // No habra messageDigest porque no nos pueden dar un hash
            // en este metodo, tendria que ser en el que incluye datos
            return new CoSigner().coSigner(algorithm, (X509Certificate[]) certChain, sign, this.dataType, key,
                    this.atrib, this.uatrib, null);
        } catch (final Exception e) {
            throw new AOException("Error generando la Cofirma PKCS#7", e); //$NON-NLS-1$
        }
    }
    throw new AOException("Los datos no se corresponden con una firma CMS valida"); //$NON-NLS-1$
}

From source file:es.gob.afirma.signers.cms.AOCMSSigner.java

License:Open Source License

/** {@inheritDoc} */
@Override/*  w  w  w . j  a v  a 2s .  c  o  m*/
public byte[] countersign(final byte[] sign, final String algorithm, final CounterSignTarget targetType,
        final Object[] targets, final PrivateKey key, final java.security.cert.Certificate[] certChain,
        final Properties extraParams) throws AOException, IOException {

    new BCChecker().checkBouncyCastle();

    final P7ContentSignerParameters csp = new P7ContentSignerParameters(sign, algorithm);

    // tipos de datos a firmar.
    if (this.dataType == null) {
        this.dataType = PKCSObjectIdentifiers.data.getId();
    }

    // Datos firmados.
    byte[] dataSigned = null;

    // Si la firma que nos introducen es SignedData

    if (ValidateCMSSignedData.isCMSSignedData(sign)) {
        try {
            // CASO DE FIRMA DE ARBOL
            if (targetType == CounterSignTarget.TREE) {
                final int[] nodes = { 0 };
                dataSigned = new CounterSigner().counterSigner(csp, sign, CounterSignTarget.TREE, nodes, key,
                        certChain, this.dataType, this.atrib, this.uatrib);
            }
            // CASO DE FIRMA DE HOJAS
            else if (targetType == CounterSignTarget.LEAFS) {
                final int[] nodes = { 0 };
                dataSigned = new CounterSigner().counterSigner(csp, sign, CounterSignTarget.LEAFS, nodes, key,
                        certChain, this.dataType, this.atrib, this.uatrib);
            }
            // CASO DE FIRMA DE NODOS
            else if (targetType == CounterSignTarget.NODES) {
                int[] nodesID = new int[targets.length];
                for (int i = 0; i < targets.length; i++) {
                    nodesID[i] = ((Integer) targets[i]).intValue();
                }
                nodesID = ReadNodesTree.simplyArray(nodesID);
                dataSigned = new CounterSigner().counterSigner(csp, sign, CounterSignTarget.NODES, nodesID, key,
                        certChain, this.dataType, this.atrib, this.uatrib);
            }
            // CASO DE FIRMA DE NODOS DE UNO O VARIOS FIRMANTES
            else if (targetType == CounterSignTarget.SIGNERS) {

                // clase que lee los nodos de un fichero firmado (p7s)
                final String[] signers = new String[targets.length];
                for (int i = 0; i < targets.length; i++) {
                    signers[i] = (String) targets[i];
                }
                final ReadNodesTree rn2 = new ReadNodesTree();
                final int[] nodes2 = rn2.readNodesFromSigners(signers, sign);
                dataSigned = new CounterSigner().counterSigner(csp, sign, CounterSignTarget.SIGNERS, nodes2,
                        key, certChain, this.dataType, this.atrib, this.uatrib);

            }
        } catch (final Exception e) {
            throw new AOException("Error generando la Contrafirma PKCS#7", e); //$NON-NLS-1$
        }
    } else {
        throw new AOException("Los datos no se corresponden con una firma CMS valida"); //$NON-NLS-1$
    }

    return dataSigned;
}

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

License:Open Source License

/** Se crea una cofirma a partir de los datos del firmante, el archivo
 * que se firma y el archivo que contiene las firmas.
 * @param parameters/*from ww w. j a v  a 2  s .  c o m*/
 *        Par&aacute;metros necesarios que contienen tanto la firma del
 *        archivo a firmar como los datos del firmante.
 * @param signature
 *        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 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 key Clave privada usada para firmar.
 * @param certChain Cadena de certificados del firmante.
 * @param messageDigest
 *        Hash espec&iacute;fico para una firma.
 * @param contentType Tipo de contenido definido por su OID.
 * @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 Si ocurre alg&uacute;n problema leyendo o escribiendo los datos
 * @throws NoSuchAlgorithmException Si no se soporta alguno de los algoritmos de firma o huella
 *                                  digital
 * @throws CertificateException Si se produce alguna excepci&oacute;n con los certificados de
 *                              firma.*/
byte[] coSigner(final P7ContentSignerParameters parameters, final byte[] signature, final boolean omitContent,
        final AdESPolicy policy, final boolean signingCertificateV2, final PrivateKey key,
        final java.security.cert.Certificate[] certChain, final byte[] messageDigest, final String contentType,
        final String contentDescription, final List<CommitmentTypeIndicationBean> ctis,
        final CAdESSignerMetadata csm) throws IOException, NoSuchAlgorithmException, CertificateException {
    // 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 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(PKCSObjectIdentifiers.data.getId());

    // Ya que el contenido puede ser grande, lo recuperamos solo una vez porque se clona
    // al recuperarlo
    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 CMSException 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 tipo 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(AOSignConstants.getDigestAlgorithmName(signatureAlgorithm)));

    // 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

    ASN1Set signedAttr = null;
    if (messageDigest == null) {
        final ASN1EncodableVector contextExpecific = CAdESUtils.generateSignerInfo(certChain[0],
                digestAlgorithm, content2 != null ? content2 : parameters.getContent(), policy,
                signingCertificateV2, null, new Date(), false, contentType, contentDescription, ctis, csm);
        this.signedAttr2 = SigUtils.getAttributeSet(new AttributeTable(contextExpecific));
        signedAttr = SigUtils.getAttributeSet(new AttributeTable(contextExpecific));
    } else {
        final ASN1EncodableVector contextExpecific = CAdESUtils.generateSignerInfo(certChain[0],
                digestAlgorithm, null, policy, signingCertificateV2, messageDigest, new Date(), false,
                contentType, contentDescription, ctis, csm);
        this.signedAttr2 = SigUtils.getAttributeSet(new AttributeTable(contextExpecific));
        signedAttr = SigUtils.getAttributeSet(new AttributeTable(contextExpecific));
    }

    // 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++) {
        signerInfos.add(SignerInfo.getInstance(signerInfosSd.getObjectAt(i)));
    }

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

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

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

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

License:Open Source License

private static ContentInfo getContentInfoFromContent(final byte[] content) throws IOException {
    // Ya que el contenido puede ser grande, lo recuperamos solo una vez
    final ASN1ObjectIdentifier contentTypeOID = new ASN1ObjectIdentifier(PKCSObjectIdentifiers.data.getId());
    // si se introduce el contenido o no
    if (content != null) {
        final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        final CMSProcessable msg = new CMSProcessableByteArray(content);
        try {//w  w  w. jav  a  2 s  .co m
            msg.write(bOut);
        } catch (final CMSException ex) {
            throw new IOException("Error en la escritura del procesable CMS: " + ex, ex); //$NON-NLS-1$
        }
        return new ContentInfo(contentTypeOID, new BEROctetString(bOut.toByteArray()));
    }
    return new ContentInfo(contentTypeOID, null);
}

From source file:eu.europa.ec.markt.dss.validation102853.cades.CAdESSignature.java

License:Open Source License

/**
 * This method handles the archive-timestamp-v2
 * <p/>//from   w  w w.  ja  v a  2s . co m
 * The value of the messageImprint field within TimeStampToken shall be a hash of the concatenation of:
 *  the encapContentInfo element of the SignedData sequence;
 *  any external content being protected by the signature, if the eContent element of the encapContentInfo is omitted;
 *  the Certificates and crls elements of the SignedData sequence, when present; and
 *  all data elements in the SignerInfo sequence including all signed and unsigned attributes.
 * <p/>
 * NOTE 1: An alternative archiveTimestamp attribute, identified by an object identifier { iso(1) member-body(2)
 * us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) id-aa(2) 27, is defined in prior versions of
 * TS 101 733. The archiveTimestamp attribute, defined in versions of TS 101 733 prior to 1.5.1, is not
 * compatible with the attribute defined in the present document. The archiveTimestamp attribute, defined in
 * versions 1.5.1 to 1.6.3 of TS 101 733, is compatible with the present document if the content is internal to
 * encapContentInfo. Unless the version of TS 101 733 employed by the signing party is known by all
 * recipients, use of the archiveTimestamp attribute defined in prior versions of TS 101 733 is deprecated.
 * NOTE 2: Counter signatures held as countersignature attributes do not require independent archive time-stamps as
 * they are protected by the archive time-stamp against the containing SignedData structure.
 * NOTE 3: Unless DER is used throughout, it is recommended that the binary encoding of the ASN.1 structures
 * being time-stamped be preserved when being archived to ensure that the recalculation of the data hash is
 * consistent.
 * NOTE 4: The hash is calculated over the concatenated data elements as received /stored including the Type and
 * Length encoding.
 * NOTE 5: Whilst it is recommended that unsigned attributes be DER encoded, it cannot generally be so guaranteed
 * except by prior arrangement.
 *
 * @param timestampToken
 * @return
 * @throws DSSException
 */
private byte[] getArchiveTimestampDataV2(TimestampToken timestampToken) throws DSSException {

    try {

        final ByteArrayOutputStream data = new ByteArrayOutputStream();

        final ContentInfo contentInfo = cmsSignedData.toASN1Structure();
        final SignedData signedData = SignedData.getInstance(contentInfo.getContent());

        ContentInfo content = signedData.getEncapContentInfo();
        if (content == null || content.getContent() == null) {
            /* Detached signatures have either no encapContentInfo in signedData, or it exists but has no eContent */
            if (getOriginalDocumentBytes() != null) {
                data.write(content.toASN1Primitive().getEncoded());
                data.write(getOriginalDocumentBytes());
            } else {
                throw new DSSException("Signature is detached and no original data provided.");
            }
        } else {

            ASN1OctetString octet = (ASN1OctetString) content.getContent();

            ContentInfo info2 = new ContentInfo(PKCSObjectIdentifiers.data, octet);
            final byte[] contentInfoBytes = info2.getEncoded();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Content Info: {}", DSSUtils.toHex(contentInfoBytes));
            }
            data.write(contentInfoBytes);
        }
        final ASN1Set certificates = signedData.getCertificates();
        if (certificates != null) {

            final byte[] certificatesBytes = new DERTaggedObject(false, 0,
                    new DERSequence(certificates.toArray())).getEncoded();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Certificates: {}", DSSUtils.toHex(certificatesBytes));
            }
            data.write(certificatesBytes);
        }
        if (signedData.getCRLs() != null) {

            final byte[] crlBytes = signedData.getCRLs().getEncoded();
            if (LOG.isTraceEnabled()) {
                LOG.trace("CRLs: {}", DSSUtils.toHex(crlBytes));
            }
            data.write(crlBytes);
        }
        final SignerInfo signerInfo = signerInformation.toASN1Structure();
        final ByteArrayOutputStream signerByteArrayOutputStream = new ByteArrayOutputStream();
        final ASN1Set unauthenticatedAttributes = signerInfo.getUnauthenticatedAttributes();
        final ASN1Sequence filteredUnauthenticatedAttributes = filterUnauthenticatedAttributes(
                unauthenticatedAttributes, timestampToken);
        final ASN1Sequence asn1Object = getSignerInfoEncoded(signerInfo, filteredUnauthenticatedAttributes);
        for (int ii = 0; ii < asn1Object.size(); ii++) {

            final byte[] signerInfoBytes = DSSASN1Utils
                    .getDEREncoded(asn1Object.getObjectAt(ii).toASN1Primitive());
            signerByteArrayOutputStream.write(signerInfoBytes);
        }
        final byte[] signerInfoBytes = signerByteArrayOutputStream.toByteArray();
        if (LOG.isTraceEnabled()) {
            LOG.trace("SignerInfoBytes: {}", DSSUtils.toHex(signerInfoBytes));
        }
        data.write(signerInfoBytes);

        final byte[] result = data.toByteArray();
        return result;

    } catch (IOException e) {
        throw new DSSException(e);
    } catch (Exception e) {
        // When error in computing or in format the algorithm just continues.
        LOG.warn("When error in computing or in format the algorithm just continue...", e);
        return DSSUtils.EMPTY_BYTE_ARRAY;
    }
}

From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java

License:Open Source License

/**
 * This method handles the archive-timestamp-v2
 * The value of the messageImprint field within TimeStampToken shall be a
 * hash of the concatenation of:  the encapContentInfo element of the
 * SignedData sequence;  any external content being protected by the
 * signature, if the eContent element of the encapContentInfo is omitted; 
 * the Certificates and crls elements of the SignedData sequence, when
 * present; and  all data elements in the SignerInfo sequence including all
 * signed and unsigned attributes./*from   w ww.ja v  a 2 s  .co  m*/
 * NOTE 1: An alternative archiveTimestamp attribute, identified by an
 * object identifier { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1)
 * pkcs-9(9) smime(16) id-aa(2) 27, is defined in prior versions of TS 101
 * 733. The archiveTimestamp attribute, defined in versions of TS 101 733
 * prior to 1.5.1, is not compatible with the attribute defined in the
 * present document. The archiveTimestamp attribute, defined in versions
 * 1.5.1 to 1.6.3 of TS 101 733, is compatible with the present document if
 * the content is internal to encapContentInfo. Unless the version of TS 101
 * 733 employed by the signing party is known by all recipients, use of the
 * archiveTimestamp attribute defined in prior versions of TS 101 733 is
 * deprecated. NOTE 2: Counter signatures held as countersignature
 * attributes do not require independent archive time-stamps as they are
 * protected by the archive time-stamp against the containing SignedData
 * structure. NOTE 3: Unless DER is used throughout, it is recommended that
 * the binary encoding of the ASN.1 structures being time-stamped be
 * preserved when being archived to ensure that the recalculation of the
 * data hash is consistent. NOTE 4: The hash is calculated over the
 * concatenated data elements as received /stored including the Type and
 * Length encoding. NOTE 5: Whilst it is recommended that unsigned
 * attributes be DER encoded, it cannot generally be so guaranteed except by
 * prior arrangement.
 *
 * @param timestampToken
 * @return
 * @throws DSSException
 */
private byte[] getArchiveTimestampDataV2(TimestampToken timestampToken) throws DSSException {

    try {

        final ByteArrayOutputStream data = new ByteArrayOutputStream();

        final ContentInfo contentInfo = cmsSignedData.toASN1Structure();
        final SignedData signedData = SignedData.getInstance(contentInfo.getContent());

        ContentInfo content = signedData.getEncapContentInfo();
        if ((content == null) || (content.getContent() == null)) {
            /*
             * Detached signatures have either no encapContentInfo in
             * signedData, or it exists but has no eContent
             */
            if (getOriginalDocumentStream() != null) {
                data.write(content.toASN1Primitive().getEncoded());
                IOUtils.copy(getOriginalDocumentStream(), data);
            } else {
                throw new DSSException("Signature is detached and no original data provided.");
            }
        } else {

            ASN1OctetString octet = (ASN1OctetString) content.getContent();

            ContentInfo info2 = new ContentInfo(PKCSObjectIdentifiers.data, octet);
            final byte[] contentInfoBytes = info2.getEncoded();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Content Info: {}", DSSUtils.toHex(contentInfoBytes));
            }
            data.write(contentInfoBytes);
        }
        final ASN1Set certificates = signedData.getCertificates();
        if (certificates != null) {

            final byte[] certificatesBytes = new DERTaggedObject(false, 0,
                    new DERSequence(certificates.toArray())).getEncoded();
            if (LOG.isTraceEnabled()) {
                LOG.trace("Certificates: {}", DSSUtils.toHex(certificatesBytes));
            }
            data.write(certificatesBytes);
        }
        if (signedData.getCRLs() != null) {

            final byte[] crlBytes = signedData.getCRLs().getEncoded();
            if (LOG.isTraceEnabled()) {
                LOG.trace("CRLs: {}", DSSUtils.toHex(crlBytes));
            }
            data.write(crlBytes);
        }
        final SignerInfo signerInfo = signerInformation.toASN1Structure();
        final ByteArrayOutputStream signerByteArrayOutputStream = new ByteArrayOutputStream();
        final ASN1Set unauthenticatedAttributes = signerInfo.getUnauthenticatedAttributes();
        final ASN1Sequence filteredUnauthenticatedAttributes = filterUnauthenticatedAttributes(
                unauthenticatedAttributes, timestampToken);
        final ASN1Sequence asn1Object = getSignerInfoEncoded(signerInfo, filteredUnauthenticatedAttributes);
        for (int ii = 0; ii < asn1Object.size(); ii++) {

            final byte[] signerInfoBytes = DSSASN1Utils
                    .getDEREncoded(asn1Object.getObjectAt(ii).toASN1Primitive());
            signerByteArrayOutputStream.write(signerInfoBytes);
        }
        final byte[] signerInfoBytes = signerByteArrayOutputStream.toByteArray();
        if (LOG.isTraceEnabled()) {
            LOG.trace("SignerInfoBytes: {}", DSSUtils.toHex(signerInfoBytes));
        }
        data.write(signerInfoBytes);

        final byte[] result = data.toByteArray();
        return result;

    } catch (IOException e) {
        throw new DSSException(e);
    } catch (Exception e) {
        // When error in computing or in format the algorithm just
        // continues.
        LOG.warn("When error in computing or in format the algorithm just continue...", e);
        return DSSUtils.EMPTY_BYTE_ARRAY;
    }
}

From source file:eu.europa.esig.dss.pades.InfiniteLoopDSS621Test.java

License:Open Source License

/**
 * These signatures are invalid because of non ordered signed attributes
 *///ww w.j  av a2s.co  m
@Test
public void manualTest() throws Exception {

    File pdfFile = new File(FILE_PATH);

    FileInputStream fis = new FileInputStream(pdfFile);
    byte[] pdfBytes = IOUtils.toByteArray(fis);

    PDDocument document = PDDocument.load(pdfFile);
    List<PDSignature> signatures = document.getSignatureDictionaries();
    assertEquals(6, signatures.size());

    int idx = 0;
    for (PDSignature pdSignature : signatures) {
        byte[] contents = pdSignature.getContents(pdfBytes);
        byte[] signedContent = pdSignature.getSignedContent(pdfBytes);

        logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange()));

        IOUtils.write(contents, new FileOutputStream("target/sig" + (idx++) + ".p7s"));

        ASN1InputStream asn1sInput = new ASN1InputStream(contents);
        ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

        logger.info("SEQ : " + asn1Seq.toString());

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
        assertEquals(PKCSObjectIdentifiers.signedData, oid);

        SignedData signedData = SignedData
                .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject());

        ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms();
        ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier
                .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0));
        DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId());
        logger.info("DIGEST ALGO : " + digestAlgorithm);

        ContentInfo encapContentInfo = signedData.getEncapContentInfo();
        ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType();
        logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID);

        if (!PKCSObjectIdentifiers.id_ct_TSTInfo.equals(contentTypeOID)) { // If not timestamp
            assertEquals(PKCSObjectIdentifiers.data, contentTypeOID);

            ASN1Encodable content = encapContentInfo.getContent();
            logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content);
            assertNull(content);

            List<X509Certificate> certificates = extractCertificates(signedData);

            ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
            logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
            SignerInfo signedInfo = SignerInfo
                    .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

            ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes();
            logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet);

            Attribute attributeDigest = null;
            for (int i = 0; i < authenticatedAttributeSet.size(); i++) {
                Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i));
                if (PKCSObjectIdentifiers.pkcs_9_at_messageDigest.equals(attribute.getAttrType())) {
                    attributeDigest = attribute;
                    break;
                }
            }

            assertNotNull(attributeDigest);

            ASN1OctetString asn1ObjString = ASN1OctetString
                    .getInstance(attributeDigest.getAttrValues().getObjectAt(0));
            String embeddedDigest = Base64.encodeBase64String(asn1ObjString.getOctets());
            logger.info("MESSAGE DIGEST : " + embeddedDigest);

            byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
            String computedDigestSignedContentEncodeBase64 = Base64.encodeBase64String(digestSignedContent);
            logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64);
            assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64);

            SignerIdentifier sid = signedInfo.getSID();
            logger.info("SIGNER IDENTIFIER : " + sid.getId());

            IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber
                    .getInstance(signedInfo.getSID());
            ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber();
            logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber);

            BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();
            X509Certificate signerCertificate = null;
            for (X509Certificate x509Certificate : certificates) {
                if (serial.equals(x509Certificate.getSerialNumber())) {
                    signerCertificate = x509Certificate;
                }
            }
            assertNotNull(signerCertificate);

            String algorithm = signerCertificate.getPublicKey().getAlgorithm();
            EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm);

            ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
            String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

            logger.info("SIGNATURE VALUE : " + signatureValue);

            Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName());
            cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
            byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

            ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

            ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
            logger.info("DECRYPTED : " + seqDecrypt);

            DigestInfo digestInfo = new DigestInfo(seqDecrypt);
            assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

            String decryptedDigestEncodeBase64 = Base64.encodeBase64String(digestInfo.getDigest());
            logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

            byte[] encoded = authenticatedAttributeSet.getEncoded();
            byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
            String computedDigestFromSignatureEncodeBase64 = Base64.encodeBase64String(digest);
            logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64);

            assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64);

            IOUtils.closeQuietly(inputDecrypted);

        }

        IOUtils.closeQuietly(asn1sInput);
    }

    IOUtils.closeQuietly(fis);
    document.close();
}

From source file:eu.europa.esig.dss.pades.signature.PAdESLevelBTest.java

License:Open Source License

@Override
protected void onDocumentSigned(byte[] byteArray) {

    try {//from w  w  w .j av a 2  s  . co  m
        InputStream inputStream = new ByteArrayInputStream(byteArray);

        PDDocument document = PDDocument.load(inputStream);
        List<PDSignature> signatures = document.getSignatureDictionaries();
        assertEquals(1, signatures.size());

        for (PDSignature pdSignature : signatures) {
            byte[] contents = pdSignature.getContents(byteArray);
            byte[] signedContent = pdSignature.getSignedContent(byteArray);

            logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange()));

            // IOUtils.write(contents, new FileOutputStream("sig.p7s"));

            ASN1InputStream asn1sInput = new ASN1InputStream(contents);
            ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();

            logger.info("SEQ : " + asn1Seq.toString());

            ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
            assertEquals(PKCSObjectIdentifiers.signedData, oid);

            SignedData signedData = SignedData
                    .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject());

            ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms();
            ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier
                    .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0));
            DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId());
            logger.info("DIGEST ALGO : " + digestAlgorithm);

            ContentInfo encapContentInfo = signedData.getEncapContentInfo();
            ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType();
            logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID);
            assertEquals(PKCSObjectIdentifiers.data, contentTypeOID);

            ASN1Encodable content = encapContentInfo.getContent();
            logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content);
            assertNull(content);

            List<X509Certificate> certificates = extractCertificates(signedData);

            ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
            logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString());
            SignerInfo signedInfo = SignerInfo
                    .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

            ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes();
            logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet);

            List<ASN1ObjectIdentifier> attributeOids = new ArrayList<ASN1ObjectIdentifier>();
            int previousSize = 0;
            for (int i = 0; i < authenticatedAttributeSet.size(); i++) {
                Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i));
                ASN1ObjectIdentifier attrTypeOid = attribute.getAttrType();
                attributeOids.add(attrTypeOid);
                int size = attrTypeOid.getEncoded().length + attribute.getEncoded().length;
                assertTrue(size >= previousSize);

                previousSize = size;
            }
            logger.info("List of OID for Auth Attrb : " + attributeOids);

            Attribute attributeDigest = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(1));
            assertEquals(PKCSObjectIdentifiers.pkcs_9_at_messageDigest, attributeDigest.getAttrType());

            ASN1OctetString asn1ObjString = ASN1OctetString
                    .getInstance(attributeDigest.getAttrValues().getObjectAt(0));
            String embeddedDigest = Base64.encodeBase64String(asn1ObjString.getOctets());
            logger.info("MESSAGE DIGEST : " + embeddedDigest);

            byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent);
            String computedDigestSignedContentEncodeBase64 = Base64.encodeBase64String(digestSignedContent);
            logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64);
            assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64);

            SignerIdentifier sid = signedInfo.getSID();
            logger.info("SIGNER IDENTIFIER : " + sid.getId());

            IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber
                    .getInstance(signedInfo.getSID());
            ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber();
            logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber);

            BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue();
            X509Certificate signerCertificate = null;
            for (X509Certificate x509Certificate : certificates) {
                if (serial.equals(x509Certificate.getSerialNumber())) {
                    signerCertificate = x509Certificate;
                }
            }
            assertNotNull(signerCertificate);

            String algorithm = signerCertificate.getPublicKey().getAlgorithm();
            EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm);

            ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest();
            String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets());

            logger.info("SIGNATURE VALUE : " + signatureValue);

            Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName());
            cipher.init(Cipher.DECRYPT_MODE, signerCertificate);
            byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets());

            ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted);

            ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject();
            logger.info("DECRYPTED : " + seqDecrypt);

            DigestInfo digestInfo = new DigestInfo(seqDecrypt);
            assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm());

            String decryptedDigestEncodeBase64 = Base64.encodeBase64String(digestInfo.getDigest());
            logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64);

            byte[] encoded = authenticatedAttributeSet.getEncoded();
            byte[] digest = DSSUtils.digest(digestAlgorithm, encoded);
            String computedDigestFromSignatureEncodeBase64 = Base64.encodeBase64String(digest);
            logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64);

            assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64);

            IOUtils.closeQuietly(inputDecrypted);
            IOUtils.closeQuietly(asn1sInput);
        }

        IOUtils.closeQuietly(inputStream);
        document.close();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        fail(e.getMessage());
    }
}

From source file:it.trento.comune.j4sign.cms.utils.CMSBuilder.java

License:Open Source License

/**
 * //from   www . j  av a 2s.  c  o m
 * Calculates data to be signed.
 * <p>
 * Builds the CMS authenticated attributes; ContentType and MessageDigest
 * are mandatory, optional SigningTime (taken from current system time) is
 * added by default. This method waits for the completion of the
 * synchronized {@link streamAndHashContent} method, so that bytes to sign
 * is returned only when the streamed content is identical to the original
 * one.
 * </p>
 * 
 * @return the byte[] containing the calculated authenticated attributes;
 */
private synchronized byte[] getAuthenticatedAttributesBytes() {

    System.out.println("Building AuthenticatedAttributes from content.");
    byte[] bytesToSign = null;

    long timeout = 10000;

    try {

        long millisBefore = System.currentTimeMillis();
        long millisWaited = 0;

        if (this.streamHash == null) {

            System.out.println("getAuthenticatedAttributesBytes: Thread '" + Thread.currentThread().getName()
                    + "' starts waiting; timeout " + timeout + " ms.");

            /*
             * // Notify streamAndHashContent System.out
             * .println("getAuthenticatedAttributesBytes: Thread '" +
             * Thread.currentThread().getName() + "' issues notify.");
             * notify();
             */

            wait(timeout);

            millisWaited = System.currentTimeMillis() - millisBefore;

            if (millisWaited < timeout)
                System.out.println("getAuthenticatedAttributesBytes: Thread '"
                        + Thread.currentThread().getName() + "' waited: " + millisWaited + "ms");
            else
                System.out.println("getAuthenticatedAttributesBytes: Thread '"
                        + Thread.currentThread().getName() + " " + timeout + "ms timeout expired!");

        }

        if (this.streamHash != null) {

            if (Arrays.equals(this.streamHash, this.dataHash)) {

                this.signingTime = new Date();

                bytesToSign = this.infoGen.getBytesToSign(PKCSObjectIdentifiers.data, this.dataHash,
                        this.signingTime, "BC");

                this.streamHash = null;

            } else
                System.out.println(
                        "getAuthenticatedAttributesBytes: Error - stream Hash is different from data Hash");
        } else
            System.out.println("getAuthenticatedAttributesBytes: Error - stream Hash is null!!!");

    } catch (Exception e) {
        System.out.println("getAuthenticatedAttributesBytes: Error - " + e);
    }

    if (bytesToSign != null) {

        StringWriter printout = new StringWriter();
        PrintWriter pw = new PrintWriter(printout);

        // Now signingTime is explicitly set in getBytesToSign(), see above
        // this.signingTime = parseSigningTime(bytesToSign, pw);

        // System.out.println(printout);
    }

    return bytesToSign;
}