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

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

Introduction

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

Prototype

ASN1ObjectIdentifier id_aa_ets_certificateRefs

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

Click Source Link

Document

PKCS#9: 1.2.840.113549.1.9.16.2.21 - <a href="http://tools.ietf.org/html/rfc3126">RFC 3126</a>

Usage

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileC.java

License:Open Source License

private Hashtable<ASN1ObjectIdentifier, ASN1Encodable> extendUnsignedAttributes(
        Hashtable<ASN1ObjectIdentifier, ASN1Encodable> unsignedAttrs, X509Certificate signingCertificate,
        SignatureParameters parameters, Date signingTime, CertificateSource optionalCertificateSource)
        throws IOException {

    ValidationContext validationContext = certificateVerifier.validateCertificate(signingCertificate,
            signingTime,/*from  www  . j a  va  2  s . c  o m*/
            new CompositeCertificateSource(new ListCertificateSource(parameters.getCertificateChain()),
                    optionalCertificateSource),
            null, null);

    try {

        ArrayList<OtherCertID> completeCertificateRefs = new ArrayList<OtherCertID>();
        ArrayList<CrlOcspRef> completeRevocationRefs = new ArrayList<CrlOcspRef>();

        /*
         * The ETSI TS 101 733 stipulates (6.2.1): "It references the full set of CA certificates that have been
         * used to validate an ES with Complete validation data up to (but not including) the signer's certificate.
         * [...] NOTE 1: The signer's certificate is referenced in the signing certificate attribute (see clause
         * 5.7.3)." (6.2.1)
         * 
         * "The second and subsequent CrlOcspRef fields shall be in the same order as the OtherCertID to which they
         * relate." (6.2.2)
         * 
         * Also, no mention of the way to order those second and subsequent fields, so we add the certificates as
         * provided by the context.
         */

        /* The SignedCertificate is in validationContext.getCertificate() */

        for (CertificateAndContext c : validationContext.getNeededCertificates()) {

            /*
             * Add every certificate except the signing certificate
             */
            if (!c.equals(signingCertificate)) {
                completeCertificateRefs.add(makeOtherCertID(c.getCertificate()));
                // certificateValues.add(new X509CertificateStructure((ASN1Sequence) ASN1Object.fromByteArray(c
                // .getCertificate().getEncoded())));
            }

            ArrayList<CrlValidatedID> crlListIdValues = new ArrayList<CrlValidatedID>();
            ArrayList<OcspResponsesID> ocspListIDValues = new ArrayList<OcspResponsesID>();

            /*
             * Record each CRL and OCSP with a reference to the corresponding certificate
             */
            for (CRL relatedcrl : validationContext.getRelatedCRLs(c)) {
                crlListIdValues.add(makeCrlValidatedID((X509CRL) relatedcrl));
            }

            for (BasicOCSPResp relatedocspresp : validationContext.getRelatedOCSPResp(c)) {
                ocspListIDValues.add(makeOcspResponsesID(relatedocspresp));
            }

            CrlValidatedID[] crlListIdArray = new CrlValidatedID[crlListIdValues.size()];
            OcspResponsesID[] ocspListIDArray = new OcspResponsesID[ocspListIDValues.size()];

            completeRevocationRefs.add(new CrlOcspRef(new CrlListID(crlListIdValues.toArray(crlListIdArray)),
                    new OcspListID(ocspListIDValues.toArray(ocspListIDArray)), null));
        }

        OtherCertID[] otherCertIDArray = new OtherCertID[completeCertificateRefs.size()];
        CrlOcspRef[] crlOcspRefArray = new CrlOcspRef[completeRevocationRefs.size()];

        unsignedAttrs.put(PKCSObjectIdentifiers.id_aa_ets_certificateRefs,
                new Attribute(PKCSObjectIdentifiers.id_aa_ets_certificateRefs,
                        new DERSet(new DERSequence(completeCertificateRefs.toArray(otherCertIDArray)))));
        unsignedAttrs.put(PKCSObjectIdentifiers.id_aa_ets_revocationRefs,
                new Attribute(PKCSObjectIdentifiers.id_aa_ets_revocationRefs,
                        new DERSet(new DERSequence(completeRevocationRefs.toArray(crlOcspRefArray)))));

    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (CertificateEncodingException e) {
        throw new RuntimeException(e);
    } catch (OCSPException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (CRLException e) {
        throw new RuntimeException(e);
    }

    return unsignedAttrs;
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileX.java

License:Open Source License

@Override
protected SignerInformation extendCMSSignature(CMSSignedData signedData, SignerInformation si,
        SignatureParameters parameters, Document originalData) throws IOException {

    si = super.extendCMSSignature(signedData, si, parameters, originalData);

    ASN1ObjectIdentifier attributeId = null;
    ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream();

    switch (getExtendedValidationType()) {
    case 1:/*from ww  w .  ja va2s .c om*/
        attributeId = PKCSObjectIdentifiers.id_aa_ets_escTimeStamp;

        toTimestamp.write(si.getSignature());

        // We don't include the outer SEQUENCE, only the attrType and attrValues as stated by the TS 6.3.5,
        // NOTE 2)
        toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken)
                .getAttrType().getDEREncoded());
        toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken)
                .getAttrValues().getDEREncoded());
        break;
    case 2:
        attributeId = PKCSObjectIdentifiers.id_aa_ets_certCRLTimestamp;
        break;
    default:
        throw new IllegalStateException(
                "CAdES-X Profile: Extended validation is set but no valid type (1 or 2)");
    }

    /* Those are common to Type 1 and Type 2 */
    toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs)
            .getAttrType().getDEREncoded());
    toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs)
            .getAttrValues().getDEREncoded());
    toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_revocationRefs)
            .getAttrType().getDEREncoded());
    toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_revocationRefs)
            .getAttrValues().getDEREncoded());

    @SuppressWarnings("unchecked")
    Hashtable<ASN1ObjectIdentifier, Attribute> unsignedAttrHash = si.getUnsignedAttributes().toHashtable();
    Attribute extendedTimeStamp = getTimeStampAttribute(attributeId, getSignatureTsa(), digestAlgorithm,
            toTimestamp.toByteArray());
    unsignedAttrHash.put(attributeId, extendedTimeStamp);

    return SignerInformation.replaceUnsignedAttributes(si, new AttributeTable(unsignedAttrHash));

}

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

License:Open Source License

@Override
public List<CertificateRef> getCertificateRefs() {
    List<CertificateRef> list = new ArrayList<CertificateRef>();

    if (signerInformation.getUnsignedAttributes() != null) {
        Attribute completeCertRefsAttr = signerInformation.getUnsignedAttributes()
                .get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs);
        if (completeCertRefsAttr != null && completeCertRefsAttr.getAttrValues().size() > 0) {
            DERSequence completeCertificateRefs = (DERSequence) completeCertRefsAttr.getAttrValues()
                    .getObjectAt(0);/*from w  w  w  .  j a va 2  s  .  c  o m*/
            for (int i1 = 0; i1 < completeCertificateRefs.size(); i1++) {
                OtherCertID otherCertId = OtherCertID.getInstance(completeCertificateRefs.getObjectAt(i1));
                CertificateRef certId = new CertificateRef();
                certId.setDigestAlgorithm(otherCertId.getAlgorithmHash().getAlgorithm().getId());
                certId.setDigestValue(otherCertId.getCertHash());
                if (otherCertId.getIssuerSerial() != null) {
                    if (otherCertId.getIssuerSerial().getIssuer() != null) {
                        certId.setIssuerName(otherCertId.getIssuerSerial().getIssuer().toString());
                    }
                    if (otherCertId.getIssuerSerial().getSerial() != null) {
                        certId.setIssuerSerial(otherCertId.getIssuerSerial().getSerial().toString());
                    }
                }
                list.add(certId);
            }
        }
    }

    return list;
}

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

License:Open Source License

@Override
public byte[] getTimestampX2Data() {
    try {//from  www  . j a v a 2 s .  c  o m
        ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream();

        /* Those are common to Type 1 and Type 2 */
        if (signerInformation.getUnsignedAttributes() != null) {
            toTimestamp.write(signerInformation.getUnsignedAttributes()
                    .get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs).getAttrType().getDEREncoded());
            toTimestamp.write(signerInformation.getUnsignedAttributes()
                    .get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs).getAttrValues().getDEREncoded());
            toTimestamp.write(signerInformation.getUnsignedAttributes()
                    .get(PKCSObjectIdentifiers.id_aa_ets_revocationRefs).getAttrType().getDEREncoded());
            toTimestamp.write(signerInformation.getUnsignedAttributes()
                    .get(PKCSObjectIdentifiers.id_aa_ets_revocationRefs).getAttrValues().getDEREncoded());
        }

        return toTimestamp.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

}

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

License:Open Source License

@Override
public List<CertificateRef> getCertificateRefs() {

    final List<CertificateRef> list = new ArrayList<CertificateRef>();

    final AttributeTable attributes = signerInformation.getUnsignedAttributes();
    if (attributes == null) {

        return list;
    }//from  w  w  w.  ja  va  2  s. c o m

    final Attribute attribute = attributes.get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs);

    if (attribute == null) {
        return list;
    }

    final ASN1Set attrValues = attribute.getAttrValues();
    if (attrValues.size() <= 0) {
        return list;
    }

    final ASN1Encodable attrValue = attrValues.getObjectAt(0);
    final ASN1Sequence completeCertificateRefs = (ASN1Sequence) attrValue;

    for (int i = 0; i < completeCertificateRefs.size(); i++) {

        final OtherCertID otherCertId = OtherCertID.getInstance(completeCertificateRefs.getObjectAt(i));
        final CertificateRef certId = new CertificateRef();
        certId.setDigestAlgorithm(otherCertId.getAlgorithmHash().getAlgorithm().getId());
        certId.setDigestValue(otherCertId.getCertHash());

        final IssuerSerial issuer = otherCertId.getIssuerSerial();
        if (issuer != null) {
            final GeneralNames issuerName = issuer.getIssuer();
            if (issuerName != null) {
                certId.setIssuerName(issuerName.toString());
            }
            final ASN1Integer issuerSerial = issuer.getSerial();
            if (issuerSerial != null) {
                certId.setIssuerSerial(issuerSerial.toString());
            }
        }
        list.add(certId);
    }
    return list;
}

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

License:Open Source License

@Override
public byte[] getTimestampX2Data(final TimestampToken timestampToken) {

    try {/*from  w  ww  .j a v  a 2s.c  o m*/
        @SuppressWarnings("resource")
        final ByteArrayOutputStream data = new ByteArrayOutputStream();

        /* Those are common to Type 1 and Type 2 */
        final AttributeTable attributes = signerInformation.getUnsignedAttributes();

        if (attributes != null) {

            final Attribute certAttribute = attributes.get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs);
            if (certAttribute != null) {

                data.write(DSSASN1Utils.getDEREncoded(certAttribute.getAttrType()));
                data.write(DSSASN1Utils.getDEREncoded(certAttribute.getAttrValues()));
            }

            final Attribute revAttribute = attributes.get(PKCSObjectIdentifiers.id_aa_ets_revocationRefs);
            if (revAttribute != null) {

                data.write(DSSASN1Utils.getDEREncoded(revAttribute.getAttrType()));
                data.write(DSSASN1Utils.getDEREncoded(revAttribute.getAttrValues()));
            }
        }
        return data.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

}

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

License:Open Source License

public boolean isDataForSignatureLevelPresent(final SignatureLevel signatureLevel) {

    /**/*from w  w  w. j ava2 s. c o m*/
     * This list contains the detail information collected during the check. It is reset for each call.
     */
    info = new ArrayList<String>();

    final AttributeTable unsignedAttributes = getUnsignedAttributes(signerInformation);
    final AttributeTable signedAttributes = getSignedAttributes(signerInformation);
    boolean dataForProfilePresent = true;
    switch (signatureLevel) {
    case CAdES_BASELINE_LTA:
        dataForProfilePresent = unsignedAttributes.get(OID.id_aa_ets_archiveTimestampV3) != null;
        // break omitted purposely
    case CAdES_101733_A:
        if (signatureLevel != SignatureLevel.CAdES_BASELINE_LTA) {
            dataForProfilePresent &= unsignedAttributes.get(OID.id_aa_ets_archiveTimestampV2) != null;
        }
        // break omitted purposely
    case CAdES_BASELINE_LT:
        final Store certificateStore = cmsSignedData.getCertificates();
        final Store crlStore = cmsSignedData.getCRLs();
        final Store ocspStore = cmsSignedData.getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response);
        final Store ocspBasicStore = cmsSignedData
                .getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
        final int certificateStoreSize = certificateStore.getMatches(null).size();
        final int crlStoreSize = crlStore.getMatches(null).size();
        info.add("CRL founds: " + crlStoreSize);
        final int ocspStoreSize = ocspStore.getMatches(null).size();
        info.add("OCSP founds: " + ocspStoreSize);
        final int basicOcspStoreSize = ocspBasicStore.getMatches(null).size();
        info.add("BasicOCSP founds: " + basicOcspStoreSize);
        final int ltInfoSize = crlStoreSize + ocspStoreSize + basicOcspStoreSize;
        dataForProfilePresent &= (ltInfoSize > 0);
        // break omitted purposely
    case CAdES_101733_X:
        if (!signatureLevel.toString().contains("BASELINE")) {
            dataForProfilePresent &= (unsignedAttributes
                    .get(PKCSObjectIdentifiers.id_aa_ets_certCRLTimestamp) != null
                    || unsignedAttributes.get(PKCSObjectIdentifiers.id_aa_ets_escTimeStamp) != null);
        }
        // break omitted purposely
    case CAdES_101733_C:
        if (!signatureLevel.toString().contains("BASELINE")) {
            dataForProfilePresent &= unsignedAttributes
                    .get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs) != null;
            dataForProfilePresent &= isDataForSignatureLevelPresent(SignatureLevel.CAdES_BASELINE_T);
        }
        // break omitted purposely
    case CAdES_BASELINE_T:
        dataForProfilePresent &= unsignedAttributes
                .get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken) != null;
        // break omitted purposely
    case CAdES_BASELINE_B:
        dataForProfilePresent &= ((signedAttributes.get(PKCSObjectIdentifiers.id_aa_signingCertificate) != null)
                || (signedAttributes.get(PKCSObjectIdentifiers.id_aa_signingCertificateV2) != null));
        break; // break placed purposely
    case CMS:
        dataForProfilePresent = true;
        break;
    default:
        throw new IllegalArgumentException("Unknown level " + signatureLevel);
    }
    return dataForProfilePresent;
}

From source file:eu.europa.esig.dss.validation.CAdESCertificateSource.java

License:Open Source License

private List<CertificateToken> extractEncapsulatedCertificates() {
    final List<CertificateToken> encapsulatedCerts = new ArrayList<CertificateToken>();
    // Gets certificates from CAdES-XL certificate-values inside SignerInfo attribute if present
    if ((signerInformation != null) && (signerInformation.getUnsignedAttributes() != null)) {
        extractCertificateFromUnsignedAttribute(encapsulatedCerts, PKCSObjectIdentifiers.id_aa_ets_certValues);
        extractCertificateFromUnsignedAttribute(encapsulatedCerts,
                PKCSObjectIdentifiers.id_aa_ets_certificateRefs);
    }/*from  www.  ja  v  a2 s .  c o m*/
    return encapsulatedCerts;
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSigner.java

License:Open Source License

private byte[] doSign(byte[] content, byte[] previewSignature) {
    try {//from  w ww.  j a  v  a 2  s.c om
        Security.addProvider(new BouncyCastleProvider());

        // Completa os certificados ausentes da cadeia, se houver
        if (this.certificate == null && this.certificateChain != null && this.certificateChain.length > 0) {
            this.certificate = (X509Certificate) this.certificateChain[0];
        }

        this.certificateChain = CAManager.getInstance().getCertificateChainArray(this.certificate);

        if (this.certificateChain.length < 3) {
            throw new SignerException(
                    cadesMessagesBundle.getString("error.no.ca", this.certificate.getIssuerDN()));
        }

        Certificate[] certStore = new Certificate[] {};

        CMSSignedData cmsPreviewSignedData = null;
        // Caso seja co-assinatura ou contra-assinatura
        // Importar todos os certificados da assinatura anterior
        if (previewSignature != null && previewSignature.length > 0) {
            cmsPreviewSignedData = new CMSSignedData(new CMSAbsentContent(), previewSignature);
            Collection<X509Certificate> previewCerts = this.getSignersCertificates(cmsPreviewSignedData);
            //previewCerts.add(this.certificate);
            certStore = previewCerts.toArray(new Certificate[] {});
        }

        setCertificateManager(new CertificateManager(this.certificate));

        // Recupera a lista de algoritmos da politica e o tamanho minimo da
        // chave
        List<AlgAndLength> listOfAlgAndLength = new ArrayList<AlgAndLength>();

        for (AlgAndLength algLength : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy()
                .getCommonRules().getAlgorithmConstraintSet().getSignerAlgorithmConstraints()
                .getAlgAndLengths()) {
            listOfAlgAndLength.add(algLength);
        }
        AlgAndLength algAndLength = null;

        // caso o algoritmo tenha sido informado como parmetro ir
        // verificar se o mesmo  permitido pela politica
        if (this.pkcs1.getAlgorithm() != null) {
            String varSetedAlgorithmOID = AlgorithmNames.getOIDByAlgorithmName(this.pkcs1.getAlgorithm());
            for (AlgAndLength algLength : listOfAlgAndLength) {
                if (algLength.getAlgID().getValue().equalsIgnoreCase(varSetedAlgorithmOID)) {
                    algAndLength = algLength;
                    SignerAlgorithmEnum varSignerAlgorithmEnum = SignerAlgorithmEnum
                            .valueOf(this.pkcs1.getAlgorithm());
                    String varOIDAlgorithmHash = varSignerAlgorithmEnum.getOIDAlgorithmHash();
                    ObjectIdentifier varObjectIdentifier = signaturePolicy.getSignPolicyHashAlg()
                            .getAlgorithm();
                    varObjectIdentifier.setValue(varOIDAlgorithmHash);
                    AlgorithmIdentifier varAlgorithmIdentifier = signaturePolicy.getSignPolicyHashAlg();
                    varAlgorithmIdentifier.setAlgorithm(varObjectIdentifier);
                    signaturePolicy.setSignPolicyHashAlg(varAlgorithmIdentifier);
                }
            }
        } else {
            algAndLength = listOfAlgAndLength.get(1);
            this.pkcs1.setAlgorithm(AlgorithmNames.getAlgorithmNameByOID(algAndLength.getAlgID().getValue()));
            SignerAlgorithmEnum varSignerAlgorithmEnum = SignerAlgorithmEnum.valueOf(this.pkcs1.getAlgorithm());
            String varOIDAlgorithmHash = varSignerAlgorithmEnum.getOIDAlgorithmHash();
            ObjectIdentifier varObjectIdentifier = signaturePolicy.getSignPolicyHashAlg().getAlgorithm();
            varObjectIdentifier.setValue(varOIDAlgorithmHash);
            AlgorithmIdentifier varAlgorithmIdentifier = signaturePolicy.getSignPolicyHashAlg();
            varAlgorithmIdentifier.setAlgorithm(varObjectIdentifier);
            signaturePolicy.setSignPolicyHashAlg(varAlgorithmIdentifier);

        }
        if (algAndLength == null) {
            throw new SignerException(cadesMessagesBundle.getString("error.no.algorithm.policy"));
        }
        logger.info(cadesMessagesBundle.getString("info.algorithm.id", algAndLength.getAlgID().getValue()));
        logger.info(cadesMessagesBundle.getString("info.algorithm.name",
                AlgorithmNames.getAlgorithmNameByOID(algAndLength.getAlgID().getValue())));
        logger.info(cadesMessagesBundle.getString("info.min.key.length", algAndLength.getMinKeyLength()));
        // Recupera o tamanho minimo da chave para validacao
        logger.info(cadesMessagesBundle.getString("info.validating.key.length"));
        int keyLegth = ((RSAKey) certificate.getPublicKey()).getModulus().bitLength();
        if (keyLegth < algAndLength.getMinKeyLength()) {
            throw new SignerException(cadesMessagesBundle.getString("error.min.key.length",
                    algAndLength.getMinKeyLength().toString(), keyLegth));
        }

        AttributeFactory attributeFactory = AttributeFactory.getInstance();

        // Consulta e adiciona os atributos assinados
        ASN1EncodableVector signedAttributes = new ASN1EncodableVector();

        logger.info(cadesMessagesBundle.getString("info.signed.attribute"));
        if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules()
                .getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr()
                .getObjectIdentifiers() != null) {
            for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo()
                    .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules()
                    .getMandatedSignedAttr().getObjectIdentifiers()) {

                SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory
                        .factory(objectIdentifier.getValue());
                signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), certificateChain, content,
                        signaturePolicy, this.hash);
                signedAttributes.add(signedOrUnsignedAttribute.getValue());
            }
        }

        // Monta a tabela de atributos assinados
        AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);

        // Create the table table generator that will added to the Signer
        // builder
        CMSAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                signedAttributesTable);

        // Recupera o(s) certificado(s) de confianca para validacao
        Collection<X509Certificate> trustedCAs = new HashSet<X509Certificate>();

        Collection<CertificateTrustPoint> ctp = signaturePolicy.getSignPolicyInfo()
                .getSignatureValidationPolicy().getCommonRules().getSigningCertTrustCondition()
                .getSignerTrustTrees().getCertificateTrustPoints();
        for (CertificateTrustPoint certificateTrustPoint : ctp) {
            logger.info(cadesMessagesBundle.getString("info.trust.point",
                    certificateTrustPoint.getTrustpoint().getSubjectDN().toString()));
            trustedCAs.add(certificateTrustPoint.getTrustpoint());
        }

        // Efetua a validacao das cadeias do certificado baseado na politica
        Collection<X509Certificate> certificateChainTrusted = new HashSet<X509Certificate>();
        for (Certificate certCA : certificateChain) {
            certificateChainTrusted.add((X509Certificate) certCA);
        }
        X509Certificate rootOfCertificate = null;
        for (X509Certificate tcac : certificateChainTrusted) {
            logger.info(tcac.getIssuerDN().toString());
            if (CAManager.getInstance().isRootCA(tcac)) {
                rootOfCertificate = tcac;
            }
        }
        if (trustedCAs.contains(rootOfCertificate)) {
            logger.info(cadesMessagesBundle.getString("info.trust.in.point", rootOfCertificate.getSubjectDN()));
        } else {
            // No encontrou na poltica, verificar nas cadeias do
            // componente chain-icp-brasil provavelmente certificado de
            // homologao.
            logger.warn(cadesMessagesBundle.getString("info.trust.poin.homolog"));
            CAManager.getInstance().validateRootCAs(certificateChainTrusted, certificate);
        }

        //  validade da politica
        logger.info(cadesMessagesBundle.getString("info.policy.valid.period"));
        PolicyValidator pv = new PolicyValidator(this.signaturePolicy, this.policyName);
        pv.validate();
        // Realiza a assinatura do conteudo
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        gen.addCertificates(this.generatedCertStore(certStore));
        String algorithmOID = algAndLength.getAlgID().getValue();

        logger.info(cadesMessagesBundle.getString("info.algorithm.id", algorithmOID));
        SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder()
                .setSignedAttributeGenerator(signedAttributeGenerator).setUnsignedAttributeGenerator(null)
                .build(AlgorithmNames.getAlgorithmNameByOID(algorithmOID), this.pkcs1.getPrivateKey(),
                        this.certificate);
        gen.addSignerInfoGenerator(signerInfoGenerator);

        CMSTypedData cmsTypedData;
        // para assinatura do hash, content nulo
        if (content == null) {
            cmsTypedData = new CMSAbsentContent();
        } else {
            cmsTypedData = new CMSProcessableByteArray(content);
        }

        // Efetua a assinatura digital do contedo
        CMSSignedData cmsSignedData = gen.generate(cmsTypedData, this.attached);
        setAttached(false);

        // Consulta e adiciona os atributos no assinados//

        ASN1EncodableVector unsignedAttributes = new ASN1EncodableVector();

        logger.info(cadesMessagesBundle.getString("info.unsigned.attribute"));
        Collection<SignerInformation> vNewSigners = cmsSignedData.getSignerInfos().getSigners();

        Iterator<SignerInformation> it = vNewSigners.iterator();
        SignerInformation oSi = it.next();

        if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules()
                .getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr()
                .getObjectIdentifiers() != null) {
            for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo()
                    .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules()
                    .getMandatedUnsignedAttr().getObjectIdentifiers()) {
                SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory
                        .factory(objectIdentifier.getValue());
                if (signedOrUnsignedAttribute.getOID()
                        .equalsIgnoreCase(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())) {
                    signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(),
                            this.certificateChainTimeStamp, oSi.getSignature(), signaturePolicy, this.hash);
                }
                if (signedOrUnsignedAttribute.getOID().equalsIgnoreCase("1.2.840.113549.1.9.16.2.25")) //EscTimeStamp
                {

                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    outputStream.write(oSi.getSignature());
                    AttributeTable varUnsignedAttributes = oSi.getUnsignedAttributes();
                    Attribute varAttribute = varUnsignedAttributes.get(new ASN1ObjectIdentifier(
                            PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId()));
                    outputStream.write(varAttribute.getAttrType().getEncoded());
                    outputStream.write(varAttribute.getAttrValues().getEncoded());
                    varAttribute = varUnsignedAttributes.get(
                            new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_certificateRefs.getId()));
                    outputStream.write(varAttribute.getAttrType().getEncoded());
                    outputStream.write(varAttribute.getAttrValues().getEncoded());
                    varAttribute = varUnsignedAttributes.get(
                            new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_revocationRefs.getId()));
                    outputStream.write(varAttribute.getAttrType().getEncoded());
                    outputStream.write(varAttribute.getAttrValues().getEncoded());
                    escTimeStampContent = outputStream.toByteArray();
                    signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(),
                            this.certificateChainTimeStamp, escTimeStampContent, signaturePolicy, this.hash);
                }

                else {
                    signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), certificateChain,
                            oSi.getSignature(), signaturePolicy, this.hash);
                }
                unsignedAttributes.add(signedOrUnsignedAttribute.getValue());
                AttributeTable unsignedAttributesTable = new AttributeTable(unsignedAttributes);
                vNewSigners.remove(oSi);
                oSi = SignerInformation.replaceUnsignedAttributes(oSi, unsignedAttributesTable);
                vNewSigners.add(oSi);
            }
        }

        //TODO Estudar este mtodo de contra-assinatura posteriormente
        if (previewSignature != null && previewSignature.length > 0) {
            vNewSigners.addAll(cmsPreviewSignedData.getSignerInfos().getSigners());
        }
        SignerInformationStore oNewSignerInformationStore = new SignerInformationStore(vNewSigners);
        CMSSignedData oSignedData = cmsSignedData;
        cmsSignedData = CMSSignedData.replaceSigners(oSignedData, oNewSignerInformationStore);

        byte[] result = cmsSignedData.getEncoded();

        logger.info(cadesMessagesBundle.getString("info.signature.ok"));

        return result;

    } catch (CMSException | IOException | OperatorCreationException | CertificateEncodingException ex) {
        throw new SignerException(ex);
    }
}