Example usage for org.bouncycastle.cms CMSSignedData replaceSigners

List of usage examples for org.bouncycastle.cms CMSSignedData replaceSigners

Introduction

In this page you can find the example usage for org.bouncycastle.cms CMSSignedData replaceSigners.

Prototype

public static CMSSignedData replaceSigners(CMSSignedData signedData,
        SignerInformationStore signerInformationStore) 

Source Link

Document

Replace the SignerInformation store associated with this CMSSignedData object with the new one passed in.

Usage

From source file:CreateSignature.java

License:Apache License

/**
 * We just extend CMS signed Data/*from w  w w  .j  a v a 2  s.c  om*/
 *
 * @param signedData -Generated CMS signed data
 * @return CMSSignedData - Extended CMS signed data
 */
@Override
protected CMSSignedData signTimeStamps(CMSSignedData signedData) throws IOException, TSPException {
    SignerInformationStore signerStore = signedData.getSignerInfos();
    List<SignerInformation> newSigners = new ArrayList<SignerInformation>();

    for (SignerInformation signer : signerStore.getSigners()) {
        newSigners.add(signTimeStamp(signer));
    }

    // TODO do we have to return a new stePrivateKeyPass -keystore samlKeystore.jks -keyalg RSA -sigalg SHA1WithRSAore?
    return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(newSigners));
}

From source file:br.gov.jfrj.siga.cd.TimeStamper.java

License:Open Source License

/**
 * Modyfy PKCS#7 data by adding timestamp
 * /* w w  w  .  j a v a 2 s.  c o  m*/
 * (at) param signedData (at) throws Exception
 */
public static CMSSignedData addTimestamp(CMSSignedData signedData) throws Exception {
    Collection ss = signedData.getSignerInfos().getSigners();
    SignerInformation si = (SignerInformation) ss.iterator().next();
    TimeStampToken tok = getTimeStampToken(si.getSignature());

    //      CertStore certs = tok.getCertificatesAndCRLs("Collection", "BC");
    Store certs = tok.getCertificates();
    Store certsAndCrls = AssinaturaDigital.buscarCrlParaCadaCertificado(certs);

    CMSSignedData cmssdcrl = CMSSignedData.replaceCertificatesAndCRLs(tok.toCMSSignedData(), certsAndCrls,
            certsAndCrls, certsAndCrls);

    tok = new TimeStampToken(cmssdcrl);

    ASN1InputStream asn1InputStream = new ASN1InputStream(tok.getEncoded());
    ASN1Primitive tstDER = asn1InputStream.readObject();
    DERSet ds = new DERSet(tstDER);
    Attribute a = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, ds);
    ASN1EncodableVector dv = new ASN1EncodableVector();
    dv.add(a);
    AttributeTable at = new AttributeTable(dv);
    si = SignerInformation.replaceUnsignedAttributes(si, at);
    ss.clear();
    ss.add(si);
    SignerInformationStore sis = new SignerInformationStore(ss);
    signedData = CMSSignedData.replaceSigners(signedData, sis);
    return signedData;
}

From source file:com.ackpdfbox.app.CreateSignatureBase.java

License:Apache License

/**
 * We just extend CMS signed Data/*  w ww.ja  va2s  . c o m*/
 *
 * @param signedData Generated CMS signed data
 * @return CMSSignedData Extended CMS signed data
 * @throws IOException
 * @throws org.bouncycastle.tsp.TSPException
 */
private CMSSignedData signTimeStamps(CMSSignedData signedData) throws IOException, TSPException {
    SignerInformationStore signerStore = signedData.getSignerInfos();
    List<SignerInformation> newSigners = new ArrayList<SignerInformation>();

    for (SignerInformation signer : signerStore.getSigners()) {
        newSigners.add(signTimeStamp(signer));
    }

    // TODO do we have to return a new store?
    return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(newSigners));
}

From source file:com.itdhq.poc.ocrsign.CreateSignature.java

License:Apache License

/**
 * We just extend CMS signed Data/*ww  w  . j  a v  a2  s .c  om*/
 *
 * @param signedData -Generated CMS signed data
 * @return CMSSignedData - Extended CMS signed data
 */
@Override
protected CMSSignedData signTimeStamps(CMSSignedData signedData) throws IOException, TSPException {
    SignerInformationStore signerStore = signedData.getSignerInfos();
    List<SignerInformation> newSigners = new ArrayList<SignerInformation>();

    // FIXME
    /*for (SignerInformation signer : signerStore.getSigners())
    {
    newSigners.add(signTimeStamp(signer));
    }*/

    // TODO do we have to return a new stePrivateKeyPass -keystore samlKeystore.jks -keyalg RSA -sigalg SHA1WithRSAore?
    return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(newSigners));
}

From source file:com.modemo.javase.signature.ValidationTimeStamp.java

License:Apache License

/**
 * Extend cms signed data with TimeStamp first or to all signers
 *
 * @param signedData Generated CMS signed data
 * @return CMSSignedData Extended CMS signed data
 * @throws IOException/*  w w w .ja v  a  2s  .com*/
 */
public CMSSignedData addSignedTimeStamp(CMSSignedData signedData) throws IOException {
    SignerInformationStore signerStore = signedData.getSignerInfos();
    List<SignerInformation> newSigners = new ArrayList<>();

    for (SignerInformation signer : signerStore.getSigners()) {
        // This adds a timestamp to every signer (into his unsigned attributes) in the signature.
        newSigners.add(signTimeStamp(signer));
    }

    // Because new SignerInformation is created, new SignerInfoStore has to be created 
    // and also be replaced in signedData. Which creates a new signedData object.
    return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(newSigners));
}

From source file:es.gob.afirma.signers.tsp.pkcs7.CMSTimestamper.java

License:Open Source License

/** A&ntilde;ade un sello de tiempo a las firmas encontradas dentro de una estructura PKCS#7.
 * @param pkcs7 Estructura que contiene las firmas a estampar un sello de tiempo
 * @param hashAlgorithm Algoritmo de huella digital a usar en los sellos de tiempo (si se indica <code>null</code> se usa SHA-1)
 * @param time Tiempo del sello/*  w  w  w .j  a  v  a 2s.  com*/
 * @return Nueva estructura PKCS#7 con los sellos de tiempo a&ntilde;adidos
 * @throws NoSuchAlgorithmException Si no se soporta el algoritmo de huella digital del sello de tiempo
 * @throws AOException Cuando ocurren errores gen&eacute;ricos
 * @throws IOException Si hay errores de entrada / salida */
public byte[] addTimestamp(final byte[] pkcs7, final String hashAlgorithm, final Calendar time)
        throws NoSuchAlgorithmException, AOException, IOException {

    final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(hashAlgorithm);

    final CMSSignedData signedData;
    try {
        signedData = new CMSSignedData(pkcs7);
    } catch (final Exception e) {
        throw new IllegalArgumentException("Los datos de entrada no son un SignedData de CMS: " + e); //$NON-NLS-1$
    }

    final SignerInformationStore origSignerInfoStore = signedData.getSignerInfos();

    // Insertamos un sello de tiempo en cada una de las firmas encontradas en el PKCS#7
    final List<SignerInformation> vNewSigners = new ArrayList<SignerInformation>();

    final Collection<?> ovSigners = origSignerInfoStore.getSigners();
    for (final Object name : ovSigners) {

        final SignerInformation si = (SignerInformation) name;

        final byte[] tsToken = getTimeStampToken(
                MessageDigest.getInstance(digestAlgorithm).digest(si.getSignature()), digestAlgorithm, time);

        final ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(tsToken));
        final ASN1Primitive derObj = is.readObject();
        is.close();
        final DERSet derSet = new DERSet(derObj);

        final Attribute unsignAtt = new Attribute(new ASN1ObjectIdentifier(SIGNATURE_TIMESTAMP_TOKEN_OID),
                derSet);

        final Hashtable<ASN1ObjectIdentifier, Attribute> ht = new Hashtable<ASN1ObjectIdentifier, Attribute>();
        ht.put(new ASN1ObjectIdentifier(SIGNATURE_TIMESTAMP_TOKEN_OID), unsignAtt);

        final AttributeTable unsignedAtts = new AttributeTable(ht);

        vNewSigners.add(SignerInformation.replaceUnsignedAttributes(si, unsignedAtts));
    }

    return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(vNewSigners)).getEncoded();

}

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

License:Open Source License

/**
 * Loops on each signerInformation of the cmsSignedData and extends the signature
 *
 * @param cmsSignedData//from   ww w .  java 2  s .  co m
 * @return
 */
private CMSSignedData extendAllCMSSignatures(CMSSignedData cmsSignedData, SignatureParameters parameters) {
    LOG.info("EXTEND ALL CMS SIGNATURES.");
    Collection<SignerInformation> signerInformationCollection = cmsSignedData.getSignerInfos().getSigners();
    for (SignerInformation signerInformation : signerInformationCollection) {
        cmsSignedData = preExtendCMSSignedData(cmsSignedData, parameters);
    }

    signerInformationCollection = cmsSignedData.getSignerInfos().getSigners();

    final List<SignerInformation> newSignerInformationList = new ArrayList<SignerInformation>();
    for (SignerInformation signerInformation : signerInformationCollection) {

        final CAdESSignature cadesSignature = new CAdESSignature(cmsSignedData, signerInformation);
        cadesSignature.setDetachedContents(parameters.getDetachedContent());
        assertSignatureValid(cadesSignature, parameters);
        final SignerInformation newSignerInformation = extendCMSSignature(cmsSignedData, signerInformation,
                parameters);
        newSignerInformationList.add(newSignerInformation);
    }

    final SignerInformationStore newSignerStore = new SignerInformationStore(newSignerInformationList);
    cmsSignedData = CMSSignedData.replaceSigners(cmsSignedData, newSignerStore);
    signerInformationCollection = cmsSignedData.getSignerInfos().getSigners();
    for (SignerInformation signerInformation : signerInformationCollection) {
        cmsSignedData = postExtendCMSSignedData(cmsSignedData, signerInformation, parameters);
    }
    return cmsSignedData;
}

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

License:Open Source License

/**
 * Take the last signerInformation of the cmsSignedData and extends the signature
 *
 * @param cmsSignedData//w w w  . ja v a2 s . c o m
 * @return
 */
private CMSSignedData extendLastCMSSignature(CMSSignedData cmsSignedData, SignatureParameters parameters) {

    LOG.info("EXTEND LAST CMS SIGNATURES.");
    cmsSignedData = preExtendCMSSignedData(cmsSignedData, parameters);

    Collection<SignerInformation> signerInformationCollection = cmsSignedData.getSignerInfos().getSigners();
    SignerInformation lastSignerInformation = getFirstSigner(cmsSignedData);
    final List<SignerInformation> newSignerInformationList = new ArrayList<SignerInformation>();
    for (SignerInformation signerInformation : signerInformationCollection) {

        if (lastSignerInformation == signerInformation) {

            final CAdESSignature cadesSignature = new CAdESSignature(cmsSignedData, signerInformation);
            cadesSignature.setDetachedContents(parameters.getDetachedContent());
            assertSignatureValid(cadesSignature, parameters);
            final SignerInformation newSignerInformation = extendCMSSignature(cmsSignedData, signerInformation,
                    parameters);
            newSignerInformationList.add(newSignerInformation);
        } else {
            newSignerInformationList.add(signerInformation);
        }
    }

    final SignerInformationStore newSignerStore = new SignerInformationStore(newSignerInformationList);
    cmsSignedData = CMSSignedData.replaceSigners(cmsSignedData, newSignerStore);

    lastSignerInformation = getFirstSigner(cmsSignedData);
    cmsSignedData = postExtendCMSSignedData(cmsSignedData, lastSignerInformation, parameters);
    return cmsSignedData;
}

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 {//from ww w . j a  v  a  2s .  c o  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.signature.cades.CounterSignatureBuilder.java

License:Open Source License

/**
 * This method applies a countersignature to an existing signature
 * @param signedData the countersignature
 * @return the updated signature, in which the countersignature has been embedded
 *///from  ww  w  .j a  va 2  s. co  m
public CMSSignedData signDocument(final CMSSignedData signedData) {

    final ASN1ObjectIdentifier csIdentifier = OID.id_countersignature;

    //Retrieve the SignerInformation from the countersigned signature
    final SignerInformationStore originalSignerInfos = cmsSignedData.getSignerInfos();
    //Retrieve the SignerInformation from the countersignature
    final SignerInformationStore signerInfos = signedData.getSignerInfos();

    //Add the countersignature
    SignerInformation updatedSI = cmsSignedData.getSignerInfos().get(selector)
            .addCounterSigners(originalSignerInfos.get(selector), signerInfos);

    //Create updated SignerInformationStore
    Collection<SignerInformation> counterSignatureInformationCollection = new ArrayList<SignerInformation>();
    counterSignatureInformationCollection.add(updatedSI);
    SignerInformationStore signerInformationStore = new SignerInformationStore(
            counterSignatureInformationCollection);

    //Return new, updated signature
    return CMSSignedData.replaceSigners(cmsSignedData, signerInformationStore);
}