Example usage for org.bouncycastle.cms SignerInformation getSignature

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

Introduction

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

Prototype

public byte[] getSignature() 

Source Link

Document

return the encoded signature

Usage

From source file:CreateSignature.java

License:Apache License

/**
 * We are extending CMS Signature/*w ww .j ava 2 s  . co m*/
 *
 * @param signer information about signer
 * @return information about SignerInformation
 */
private SignerInformation signTimeStamp(SignerInformation signer) throws IOException, TSPException {
    AttributeTable unsignedAttributes = signer.getUnsignedAttributes();

    ASN1EncodableVector vector = new ASN1EncodableVector();
    if (unsignedAttributes != null) {
        vector = unsignedAttributes.toASN1EncodableVector();
    }

    byte[] token = getTsaClient().getTimeStampToken(signer.getSignature());
    ASN1ObjectIdentifier oid = PKCSObjectIdentifiers.id_aa_signatureTimeStampToken;
    ASN1Encodable signatureTimeStamp = new Attribute(oid, new DERSet(ASN1Primitive.fromByteArray(token)));

    vector.add(signatureTimeStamp);
    Attributes signedAttributes = new Attributes(vector);

    SignerInformation newSigner = SignerInformation.replaceUnsignedAttributes(signer,
            new AttributeTable(signedAttributes));

    // TODO can this actually happen?
    if (newSigner == null) {
        return signer;
    }

    return newSigner;
}

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

License:Open Source License

@SuppressWarnings("unchecked")
protected static String validarAssinaturaCMS(byte[] digest, String digestAlgorithm, byte[] assinatura,
        Date dtAssinatura) throws InvalidKeyException, SecurityException, CRLException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException,
        ChainValidationException, IOException, Exception {

    final CMSSignedData s;
    if (digest != null) {
        Map<String, byte[]> map = new HashMap<String, byte[]>();
        map.put(digestAlgorithm, digest);
        s = new CMSSignedData(map, assinatura);
    } else {//from w ww.  j  a v a  2  s  . c  o  m
        s = new CMSSignedData(assinatura);
    }

    Store certs = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();
    Collection<SignerInformation> c = signers.getSigners();
    Iterator<SignerInformation> it = c.iterator();
    X509CertificateHolder firstSignerCert = null;

    while (it.hasNext()) {
        SignerInformation signer = it.next();
        Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID());

        Iterator<X509CertificateHolder> certIt = certCollection.iterator();
        X509CertificateHolder cert = certIt.next();
        if (firstSignerCert == null)
            firstSignerCert = cert;

        if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)))
            throw new Exception("Assinatura invlida!");

        System.out.println("\nSigner Info: \n");
        System.out.println("Is Signature Valid? true");
        System.out.println("Digest: " + asHex(signer.getContentDigest()));
        System.out.println("Enc Alg Oid: " + signer.getEncryptionAlgOID());
        System.out.println("Digest Alg Oid: " + signer.getDigestAlgOID());
        System.out.println("Signature: " + asHex(signer.getSignature()));

    }

    //      X509Certificate[] cadeiaTotal = montarCadeiaOrdenadaECompleta((Collection<X509Certificate>) (certs.getCertificates(null)));
    X509Certificate[] cadeiaTotal = montarCadeiaOrdenadaECompleta(certs.getMatches(null));

    List<X509CRLObject> crls = new ArrayList<>();
    if (certs.getMatches(null) != null) {
        Enumeration ec = ASN1Set.getInstance(certs.getMatches(null)).getObjects();

        while (ec.hasMoreElements()) {
            crls.add(new X509CRLObject(CertificateList.getInstance(ec.nextElement())));
        }
    }

    final X509ChainValidator cadeia = new X509ChainValidator(cadeiaTotal,
            /* trustedAnchors */new HashSet(FachadaDeCertificadosAC.getTrustAnchors()),
            crls.toArray(new X509CRLObject[0]));

    cadeia.checkCRL(true);

    try {
        cadeia.validateChain(dtAssinatura);
    } catch (Exception e1) {
        if (e1.getMessage().endsWith("Validation time is in future.")) {
            String s1 = e1.getMessage() + " Current date: [" + new Date().toString() + "]. Record date: ["
                    + dtAssinatura + "]. LCRs' dates [";
            for (X509CRLObject crl : (Collection<X509CRLObject>) certs.getMatches(null)) {
                String s2 = crl.getIssuerX500Principal().getName();
                s2 = s2.split(",")[0];

                s1 += s2 + " (" + crl.getThisUpdate() + " - " + crl.getNextUpdate() + ") ";
            }
            s1 += "]";
            throw new AplicacaoException(s1, 0, e1);
        } else
            throw e1;
    }

    //      String s1 = firstSignerCert.getSubjectDN().getName();
    String s1 = firstSignerCert.getSubject().toString();
    s1 = obterNomeExibicao(s1);

    return s1;
}

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

License:Open Source License

@SuppressWarnings("unchecked")
protected static String validarAssinaturaCMSeCarimboDeTempo(final byte[] digest, final String digestAlgorithm,
        final byte[] assinatura, Date dtAssinatura) throws InvalidKeyException, SecurityException, CRLException,
        CertificateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException,
        AplicacaoException, ChainValidationException, IOException, Exception {

    String nome = validarAssinaturaCMS(digest, digestAlgorithm, assinatura, dtAssinatura);

    Map<String, byte[]> map = new HashMap<String, byte[]>();
    map.put(digestAlgorithm, digest);//from  w  w  w .  j ava  2 s  . com
    final CMSSignedData s = new CMSSignedData(map, assinatura);

    Collection ss = s.getSignerInfos().getSigners();
    SignerInformation si = (SignerInformation) ss.iterator().next();

    Attribute attr = si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken);
    CMSSignedData cmsTS = new CMSSignedData(attr.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded());

    TimeStampToken tok = new TimeStampToken(cmsTS);
    Store cs = tok.getCertificates();

    SignerId signer_id = tok.getSID();
    BigInteger cert_serial_number = signer_id.getSerialNumber();
    Collection certs = cs.getMatches(null);
    Iterator iter = certs.iterator();
    X509Certificate certificate = null;
    while (iter.hasNext()) {
        X509Certificate cert = (X509Certificate) iter.next();
        if (cert_serial_number != null) {
            if (cert.getSerialNumber().equals(cert_serial_number)) {
                certificate = cert;
            }
        } else {
            if (certificate == null) {
                certificate = cert;
            }
        }
    }

    tok.validate(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificate));
    // Nato: falta validar as CRLs do carimbo de tempo

    if (!Arrays.equals(tok.getTimeStampInfo().getMessageImprintDigest(),
            MessageDigest.getInstance("SHA1").digest(si.getSignature()))) {
        throw new Exception("Carimbo de tempo no confere com o resumo do documento");
    }

    try {
        validarAssinaturaCMS(null, null, cmsTS.getEncoded(), tok.getTimeStampInfo().getGenTime());
    } catch (Exception e) {
        throw new Exception("Carimbo de tempo invlido!", e);
    }

    return nome;
}

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

License:Open Source License

/**
 * Modyfy PKCS#7 data by adding timestamp
 * //w ww  . java  2s .co 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.itdhq.poc.ocrsign.CreateSignature.java

License:Apache License

/**
 * We are extending CMS Signature//from  w ww  .j  a v a 2s.c  o  m
 *
 * @param signer information about signer
 * @return information about SignerInformation
 */
private SignerInformation signTimeStamp(SignerInformation signer) throws IOException, TSPException {
    AttributeTable unsignedAttributes = signer.getUnsignedAttributes();

    ASN1EncodableVector vector = new ASN1EncodableVector();
    if (unsignedAttributes != null) {
        vector = unsignedAttributes.toASN1EncodableVector();
    }

    byte[] token = getTsaClient().getTimeStampToken(signer.getSignature());
    // FIXME
    /*ASN1ObjectIdentifier oid = PKCSObjectIdentifiers.id_aa_signatureTimeStampToken;
    ASN1Encodable signatureTimeStamp = new Attribute(oid, new DERSet(ASN1Primitive.fromByteArray(token)));
            
    vector.add(signatureTimeStamp);
    Attributes signedAttributes = new Attributes(vector);
            
    SignerInformation newSigner = SignerInformation.replaceUnsignedAttributes(
        signer, new AttributeTable(signedAttributes));
                
            
    // TODO can this actually happen?
    if (newSigner == null)
    {
    return signer;
    }
            
    return newSigner;*/
    return signer;
}

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

License:Apache License

/**
 * Extend CMS Signer Information with the TimeStampToken into the unsigned Attributes.
 *
 * @param signer information about signer
 * @return information about SignerInformation
 * @throws IOException//from w w  w .j  a v a2 s . c  om
 */
private SignerInformation signTimeStamp(SignerInformation signer) throws IOException {
    AttributeTable unsignedAttributes = signer.getUnsignedAttributes();

    ASN1EncodableVector vector = new ASN1EncodableVector();
    if (unsignedAttributes != null) {
        vector = unsignedAttributes.toASN1EncodableVector();
    }

    byte[] token = tsaClient.getTimeStampToken(signer.getSignature());
    ASN1ObjectIdentifier oid = PKCSObjectIdentifiers.id_aa_signatureTimeStampToken;
    ASN1Encodable signatureTimeStamp = new Attribute(oid, new DERSet(ASN1Primitive.fromByteArray(token)));

    vector.add(signatureTimeStamp);
    Attributes signedAttributes = new Attributes(vector);

    // There is no other way changing the unsigned attributes of the signer information.
    // result is never null, new SignerInformation always returned, 
    // see source code of replaceUnsignedAttributes
    return SignerInformation.replaceUnsignedAttributes(signer, new AttributeTable(signedAttributes));
}

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/*ww  w .  j  av  a  2s . c  o  m*/
 * @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.CAdESLevelBaselineT.java

License:Open Source License

private AttributeTable addSignatureTimestampAttribute(SignerInformation signerInformation,
        AttributeTable unsignedAttributes, SignatureParameters parameters) {

    ASN1Object signatureTimeStamp = getTimeStampAttributeValue(signatureTsa, signerInformation.getSignature(),
            parameters);//www .j a v  a  2 s. co  m
    return unsignedAttributes.add(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, signatureTimeStamp);
}

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

License:Open Source License

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

    if (this.signatureTsa == null) {
        throw new ConfigurationException(MSG.CONFIGURE_TSP_SERVER);
    }//from   w  ww. j  av  a  2 s.  c o  m

    LOG.info("Extend signature with id " + si.getSID());
    AttributeTable unsigned = si.getUnsignedAttributes();
    Hashtable<ASN1ObjectIdentifier, Attribute> unsignedAttrHash = null;
    if (unsigned == null) {
        unsignedAttrHash = new Hashtable<ASN1ObjectIdentifier, Attribute>();
    } else {
        unsignedAttrHash = si.getUnsignedAttributes().toHashtable();
    }

    Attribute signatureTimeStamp = getTimeStampAttribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
            this.signatureTsa, digestAlgorithm, si.getSignature());
    unsignedAttrHash.put(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, signatureTimeStamp);

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

    // Attribute signatureTimeStamp = getTimeStampAttribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
    // this.signatureTsa, digestAlgorithm, si.getSignature());
    //
    // AttributeTable table2 = si.getUnsignedAttributes().add(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
    // signatureTimeStamp);
    // /* If we add a timestamp, then we must remove every reference to timestamp -X and archive timestamp */
    // table2 = table2.remove(CAdESProfileA.id_aa_ets_archiveTimestampV2);
    // table2 = table2.remove(PKCSObjectIdentifiers.id_aa_ets_escTimeStamp);
    //
    // SignerInformation newsi = SignerInformation.replaceUnsignedAttributes(si, table2);
    // return newsi;
    //
}

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   w ww .  j av a2 s.  com*/
        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));

}