Example usage for org.bouncycastle.cms SignerInformation replaceUnsignedAttributes

List of usage examples for org.bouncycastle.cms SignerInformation replaceUnsignedAttributes

Introduction

In this page you can find the example usage for org.bouncycastle.cms SignerInformation replaceUnsignedAttributes.

Prototype

public static SignerInformation replaceUnsignedAttributes(SignerInformation signerInformation,
        AttributeTable unsignedAttributes) 

Source Link

Document

Return a signer information object with the passed in unsigned attributes replacing the ones that are current associated with the object passed in.

Usage

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from w  w  w.ja  v  a 2s .  c om
protected SignerInformation extendCMSSignature(CMSSignedData signedData, SignerInformation si,
        SignatureParameters parameters, Document originalData) throws IOException {
    si = super.extendCMSSignature(signedData, si, parameters, originalData);
    Hashtable<ASN1ObjectIdentifier, ASN1Encodable> unsignedAttrs = si.getUnsignedAttributes().toHashtable();

    /* Extends unsigned attributes */
    CAdESSignature signature = new CAdESSignature(signedData, si.getSID());
    Date signingTime = signature.getSigningTime();
    if (signingTime == null) {
        signingTime = parameters.getSigningDate();
    }
    if (signingTime == null) {
        signingTime = new Date();
    }
    unsignedAttrs = extendUnsignedAttributes(unsignedAttrs, signature.getSigningCertificate(), signingTime,
            signature.getCertificateSource());

    SignerInformation newsi = SignerInformation.replaceUnsignedAttributes(si,
            new AttributeTable(unsignedAttrs));
    return newsi;
}

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

License:Open Source License

public static ASN1Object getTimeStampAttributeValue(final TSPSource tspSource, final byte[] messageToTimestamp,
        final DigestAlgorithm timestampDigestAlgorithm, final Attribute... attributesForTimestampToken) {
    try {//  www  . ja va  2s . co m

        if (LOG.isDebugEnabled()) {
            LOG.debug("Message to timestamp is: " + DSSUtils.encodeHexString(messageToTimestamp));
        }
        byte[] timestampDigest = DSSUtils.digest(timestampDigestAlgorithm, messageToTimestamp);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Digested ({}) message to timestamp is {}",
                    new Object[] { timestampDigestAlgorithm, DSSUtils.encodeHexString(timestampDigest) });
        }

        final TimeStampToken timeStampToken = tspSource.getTimeStampResponse(timestampDigestAlgorithm,
                timestampDigest);

        if (timeStampToken == null) {
            throw new DSSNullReturnedException(TimeStampToken.class);
        }

        if (LOG.isDebugEnabled()) {
            final byte[] messageImprintDigest = timeStampToken.getTimeStampInfo().getMessageImprintDigest();
            LOG.debug("Digested ({}) message in timestamp is {}",
                    new Object[] { timestampDigestAlgorithm, DSSUtils.encodeHexString(messageImprintDigest) });
        }

        CMSSignedData cmsSignedDataTimeStampToken = new CMSSignedData(timeStampToken.getEncoded());

        // TODO (27/08/2014): attributesForTimestampToken cannot be null: to be modified
        if (attributesForTimestampToken != null) {
            // timeStampToken contains one and only one signer
            final SignerInformation signerInformation = (SignerInformation) cmsSignedDataTimeStampToken
                    .getSignerInfos().getSigners().iterator().next();
            AttributeTable unsignedAttributes = CAdESSignature.getUnsignedAttributes(signerInformation);
            for (final Attribute attributeToAdd : attributesForTimestampToken) {
                final ASN1ObjectIdentifier attrType = attributeToAdd.getAttrType();
                final ASN1Encodable objectAt = attributeToAdd.getAttrValues().getObjectAt(0);
                unsignedAttributes = unsignedAttributes.add(attrType, objectAt);
            }
            final SignerInformation newSignerInformation = SignerInformation
                    .replaceUnsignedAttributes(signerInformation, unsignedAttributes);
            final List<SignerInformation> signerInformationList = new ArrayList<SignerInformation>();
            signerInformationList.add(newSignerInformation);
            final SignerInformationStore newSignerStore = new SignerInformationStore(signerInformationList);
            cmsSignedDataTimeStampToken = CMSSignedData.replaceSigners(cmsSignedDataTimeStampToken,
                    newSignerStore);
        }
        final byte[] newTimeStampTokenBytes = cmsSignedDataTimeStampToken.getEncoded();
        return DSSASN1Utils.toASN1Primitive(newTimeStampTokenBytes);
    } catch (IOException e) {
        throw new DSSException(e);
    } catch (CMSException e) {
        throw new DSSException(e);
    }

}

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

License:Open Source License

@Override
public byte[] getArchiveTimestampData(int index, Document originalDocument) throws IOException {

    ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream();

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

    /* The encapContentInfo should always be present according to the standard, but sometimes it's omitted */
    // 5.4.1/* ww w  . j  a v  a2s  .  c  om*/
    if (signedData.getEncapContentInfo() == null || signedData.getEncapContentInfo().getContent() == null) {
        /* Detached signatures have either no encapContentInfo in signedData, or it exists but has no eContent */
        if (originalDocument != null) {
            toTimestamp.write(originalDocument.openStream());
        } else {
            throw new RuntimeException("Signature is detached and no original data provided.");
        }
    } else {

        ContentInfo content = signedData.getEncapContentInfo();
        DEROctetString octet = (DEROctetString) content.getContent();

        ContentInfo info2 = new ContentInfo(new ASN1ObjectIdentifier("1.2.840.113549.1.7.1"),
                new BERConstructedOctetString(octet.getOctets()));
        toTimestamp.write(info2.getEncoded());
    }

    if (signedData.getCertificates() != null) {
        DEROutputStream output = new DEROutputStream(toTimestamp);
        output.writeObject(signedData.getCertificates());
        output.close();
    }

    if (signedData.getCRLs() != null) {
        toTimestamp.write(signedData.getCRLs().getEncoded());
    }

    if (signerInformation.getUnsignedAttributes() != null) {
        ASN1EncodableVector original = signerInformation.getUnsignedAttributes().toASN1EncodableVector();
        List<Attribute> timeStampToRemove = getTimeStampToRemove(index);
        ASN1EncodableVector filtered = new ASN1EncodableVector();
        for (int i = 0; i < original.size(); i++) {
            DEREncodable enc = original.get(i);
            if (!timeStampToRemove.contains(enc)) {
                filtered.add(original.get(i));
            }
        }
        SignerInformation filteredInfo = SignerInformation.replaceUnsignedAttributes(signerInformation,
                new AttributeTable(filtered));

        toTimestamp.write(filteredInfo.toASN1Structure().getEncoded());
    }

    return toTimestamp.toByteArray();
}

From source file:eu.europa.esig.dss.cades.signature.CAdESLevelBaselineLTA.java

License:Open Source License

@Override
protected SignerInformation extendCMSSignature(final CMSSignedData cmsSignedData,
        SignerInformation signerInformation, final CAdESSignatureParameters parameters) throws DSSException {

    CAdESSignature cadesSignature = new CAdESSignature(cmsSignedData, signerInformation);
    cadesSignature.setDetachedContents(parameters.getDetachedContent());
    AttributeTable unsignedAttributes = CMSUtils.getUnsignedAttributes(signerInformation);
    unsignedAttributes = addArchiveTimestampV3Attribute(cadesSignature, cmsSignedData, signerInformation,
            parameters, unsignedAttributes);
    SignerInformation newSignerInformation = SignerInformation.replaceUnsignedAttributes(signerInformation,
            unsignedAttributes);//from   w ww  .j  a va 2s  .c  om
    return newSignerInformation;
}

From source file:eu.europa.esig.dss.cades.signature.CAdESLevelBaselineT.java

License:Open Source License

@Override
protected SignerInformation extendCMSSignature(CMSSignedData signedData, SignerInformation signerInformation,
        CAdESSignatureParameters parameters) throws DSSException {
    final CAdESSignature cadesSignature = new CAdESSignature(signedData, signerInformation);
    cadesSignature.setDetachedContents(parameters.getDetachedContent());
    assertExtendSignaturePossible(cadesSignature);

    AttributeTable unsignedAttributes = CMSUtils.getUnsignedAttributes(signerInformation);
    unsignedAttributes = addSignatureTimestampAttribute(signerInformation, unsignedAttributes, parameters);

    return SignerInformation.replaceUnsignedAttributes(signerInformation, unsignedAttributes);
}

From source file:eu.europa.esig.dss.cades.signature.CAdESSignatureExtension.java

License:Open Source License

public static ASN1Object getTimeStampAttributeValue(final TSPSource tspSource, final byte[] messageToTimestamp,
        final DigestAlgorithm timestampDigestAlgorithm, final Attribute... attributesForTimestampToken) {
    try {//from w  ww .j  a  v  a  2  s .  c  om

        if (LOG.isDebugEnabled()) {
            LOG.debug("Message to timestamp is: " + Hex.encodeHexString(messageToTimestamp));
        }
        byte[] timestampDigest = DSSUtils.digest(timestampDigestAlgorithm, messageToTimestamp);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Digested ({}) message to timestamp is {}",
                    new Object[] { timestampDigestAlgorithm, Hex.encodeHexString(timestampDigest) });
        }

        final TimeStampToken timeStampToken = tspSource.getTimeStampResponse(timestampDigestAlgorithm,
                timestampDigest);

        if (timeStampToken == null) {
            throw new NullPointerException();
        }

        if (LOG.isDebugEnabled()) {
            final byte[] messageImprintDigest = timeStampToken.getTimeStampInfo().getMessageImprintDigest();
            LOG.debug("Digested ({}) message in timestamp is {}",
                    new Object[] { timestampDigestAlgorithm, Hex.encodeHexString(messageImprintDigest) });
        }

        CMSSignedData cmsSignedDataTimeStampToken = new CMSSignedData(timeStampToken.getEncoded());

        // TODO (27/08/2014): attributesForTimestampToken cannot be null: to be modified
        if (attributesForTimestampToken != null) {
            // timeStampToken contains one and only one signer
            final SignerInformation signerInformation = cmsSignedDataTimeStampToken.getSignerInfos()
                    .getSigners().iterator().next();
            AttributeTable unsignedAttributes = CMSUtils.getUnsignedAttributes(signerInformation);
            for (final Attribute attributeToAdd : attributesForTimestampToken) {
                final ASN1ObjectIdentifier attrType = attributeToAdd.getAttrType();
                final ASN1Encodable objectAt = attributeToAdd.getAttrValues().getObjectAt(0);
                unsignedAttributes = unsignedAttributes.add(attrType, objectAt);
            }
            final SignerInformation newSignerInformation = SignerInformation
                    .replaceUnsignedAttributes(signerInformation, unsignedAttributes);
            final List<SignerInformation> signerInformationList = new ArrayList<SignerInformation>();
            signerInformationList.add(newSignerInformation);
            final SignerInformationStore newSignerStore = new SignerInformationStore(signerInformationList);
            cmsSignedDataTimeStampToken = CMSSignedData.replaceSigners(cmsSignedDataTimeStampToken,
                    newSignerStore);
        }
        final byte[] newTimeStampTokenBytes = cmsSignedDataTimeStampToken.getEncoded();
        return DSSASN1Utils.toASN1Primitive(newTimeStampTokenBytes);
    } catch (IOException e) {
        throw new DSSException(e);
    } catch (CMSException e) {
        throw new DSSException(e);
    }

}

From source file:net.jsign.timestamp.Timestamper.java

License:Apache License

protected CMSSignedData modifySignedData(CMSSignedData sigData, AttributeTable unsignedAttributes,
        Collection<X509CertificateHolder> extraCertificates) throws IOException, CMSException {
    SignerInformation signerInformation = sigData.getSignerInfos().getSigners().iterator().next();
    signerInformation = SignerInformation.replaceUnsignedAttributes(signerInformation, unsignedAttributes);

    Collection<X509CertificateHolder> certificates = new ArrayList<X509CertificateHolder>();
    certificates.addAll(sigData.getCertificates().getMatches(null));
    if (extraCertificates != null) {
        certificates.addAll(extraCertificates);
    }/*  ww w . j  a  v a 2  s  .co m*/
    Store<X509CertificateHolder> certificateStore = new CollectionStore<X509CertificateHolder>(certificates);

    AuthenticodeSignedDataGenerator generator = new AuthenticodeSignedDataGenerator();
    generator.addCertificates(certificateStore);
    generator.addSigners(new SignerInformationStore(signerInformation));

    ASN1ObjectIdentifier contentType = new ASN1ObjectIdentifier(sigData.getSignedContentTypeOID());
    ASN1Encodable content = ASN1Sequence.getInstance(sigData.getSignedContent().getContent());

    return generator.generate(contentType, content);
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

License:Open Source License

private static CMSSignedData addTimestamp(String tsaUrl, CMSSignedData signedData) throws IOException {

    Collection<SignerInformation> signerInfos = signedData.getSignerInfos().getSigners();

    // get signature of first signer (should be the only one)
    SignerInformation si = signerInfos.iterator().next();
    byte[] signature = si.getSignature();

    // send request to TSA
    byte[] token = TimeStampingClient.getTimeStampToken(tsaUrl, signature, DigestType.SHA1);

    // create new SignerInformation with TS attribute
    Attribute tokenAttr = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
            new DERSet(ASN1Primitive.fromByteArray(token)));
    ASN1EncodableVector timestampVector = new ASN1EncodableVector();
    timestampVector.add(tokenAttr);//ww  w .j a v a  2 s  .  c o m
    AttributeTable at = new AttributeTable(timestampVector);
    si = SignerInformation.replaceUnsignedAttributes(si, at);
    signerInfos.clear();
    signerInfos.add(si);
    SignerInformationStore newSignerStore = new SignerInformationStore(signerInfos);

    // create new signed data
    CMSSignedData newSignedData = CMSSignedData.replaceSigners(signedData, newSignerStore);
    return newSignedData;
}

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  w w .  ja v  a2s. c  o  m*/
        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);
    }
}

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

License:Open Source License

@Override
public byte[] doTimeStampForSignature(byte[] signature) throws SignerException {
    try {/*  ww  w  . j  a  v  a2 s  . c  o m*/
        Security.addProvider(new BouncyCastleProvider());
        CMSSignedData cmsSignedData = new CMSSignedData(signature);
        SignerInformationStore signers = cmsSignedData.getSignerInfos();
        Iterator<?> it = signers.getSigners().iterator();
        SignerInformation signer = (SignerInformation) it.next();
        AttributeFactory attributeFactory = AttributeFactory.getInstance();
        ASN1EncodableVector unsignedAttributes = new ASN1EncodableVector();
        SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory
                .factory(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId());
        signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.getCertificateChain(),
                signer.getSignature(), signaturePolicy, null);
        unsignedAttributes.add(signedOrUnsignedAttribute.getValue());
        AttributeTable unsignedAttributesTable = new AttributeTable(unsignedAttributes);
        List<SignerInformation> vNewSigners = new ArrayList<SignerInformation>();
        vNewSigners.add(SignerInformation.replaceUnsignedAttributes(signer, unsignedAttributesTable));
        SignerInformationStore oNewSignerInformationStore = new SignerInformationStore(vNewSigners);
        CMSSignedData oSignedData = cmsSignedData;
        cmsSignedData = CMSSignedData.replaceSigners(oSignedData, oNewSignerInformationStore);
        byte[] result = cmsSignedData.getEncoded();
        return result;
    } catch (CMSException ex) {
        throw new SignerException(ex.getMessage());
    } catch (IOException ex) {
        throw new SignerException(ex.getMessage());
    }

}