Example usage for org.bouncycastle.asn1.cms SignerInfo getUnauthenticatedAttributes

List of usage examples for org.bouncycastle.asn1.cms SignerInfo getUnauthenticatedAttributes

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cms SignerInfo getUnauthenticatedAttributes.

Prototype

public ASN1Set getUnauthenticatedAttributes() 

Source Link

Usage

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

License:Open Source License

/** Método para obtener las contrafirmas.
 * @param signerInfouAtrib/*from   w  w  w . ja  v  a  2  s .  co m*/
 *        Atributos en los que puede estar la contrafirma.
 * @param ramahija
 *        Rama hija donde buscar los siguientes nodos.
 * @param certificates
 *        Certificados. */
private void getUnsignedAtributesWithCertificates(final ASN1Set signerInfouAtrib, final AOTreeNode ramahija,
        final ASN1Set certificates) {

    if (signerInfouAtrib != null) {
        final Enumeration<?> eAtributes = signerInfouAtrib.getObjects();
        while (eAtributes.hasMoreElements()) {
            final Attribute data = Attribute.getInstance(eAtributes.nextElement());
            if (!data.getAttrType().equals(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken)) {
                final ASN1Set setInto = data.getAttrValues();
                final Enumeration<?> eAtributesData = setInto.getObjects();
                while (eAtributesData.hasMoreElements()) {
                    final Object obj = eAtributesData.nextElement();
                    if (obj instanceof ASN1Sequence) {
                        final ASN1Sequence atrib = (ASN1Sequence) obj;
                        final IssuerAndSerialNumber issuerSerial = IssuerAndSerialNumber
                                .getInstance(atrib.getObjectAt(1));
                        final SignerInfo si = SignerInfo.getInstance(atrib);
                        final X509Certificate[] nameSigner = searchCert(certificates,
                                issuerSerial.getSerialNumber());
                        final Date signingTime = getSigningTime(si);
                        final AOSimpleSignInfo aossi = new AOSimpleSignInfo(nameSigner, signingTime);
                        aossi.setPkcs1(si.getEncryptedDigest().getOctets());
                        this.rama2 = new AOTreeNode(aossi);
                        this.listaCert.add(nameSigner);
                        ramahija.add(this.rama2);
                        getUnsignedAtributesWithCertificates(si.getUnauthenticatedAttributes(), this.rama2,
                                certificates);
                    }
                }
            }
        }

    }
}

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

License:Open Source License

/** M&eacute;todo para obtener las contrafirmas.
 * @param signerInfouAtrib//w  ww  . j a va  2 s .co  m
 *        Atributos en los que puede estar la contrafirma.
 * @param ramahija
 *        Rama hija donde buscar los siguientes nodos.
 * @param certificates
 *        Certificados. */
private void getUnsignedAtributes(final ASN1Set signerInfouAtrib, final AOTreeNode ramahija,
        final ASN1Set certificates) {

    if (signerInfouAtrib != null) {
        final Enumeration<?> eAtributes = signerInfouAtrib.getObjects();
        while (eAtributes.hasMoreElements()) {
            final Attribute data = Attribute.getInstance(eAtributes.nextElement());
            if (!data.getAttrType().equals(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken)) {
                final ASN1Set setInto = data.getAttrValues();
                final Enumeration<?> eAtributesData = setInto.getObjects();
                while (eAtributesData.hasMoreElements()) {
                    final Object obj = eAtributesData.nextElement();
                    if (obj instanceof ASN1Sequence) {
                        final ASN1Sequence atrib = (ASN1Sequence) obj;
                        final IssuerAndSerialNumber issuerSerial = IssuerAndSerialNumber
                                .getInstance(atrib.getObjectAt(1));
                        final SignerInfo si = SignerInfo.getInstance(atrib);
                        final String nameSigner = searchName(certificates, issuerSerial.getSerialNumber());
                        this.rama2 = new AOTreeNode(nameSigner);
                        this.lista.add(nameSigner);
                        ramahija.add(this.rama2);
                        getUnsignedAtributes(si.getUnauthenticatedAttributes(), this.rama2, certificates);
                    }
                }
            }
        }

    }
}

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  . c o  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 w w  .  j  a  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;
    }
}