Example usage for org.bouncycastle.cms CMSSignedData getSignerInfos

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

Introduction

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

Prototype

public SignerInformationStore getSignerInfos() 

Source Link

Document

return the collection of signers that are associated with the signatures for the message.

Usage

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);
    }//  www  .  ja  v a 2  s  .c  o 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.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObject.java

License:BSD License

/**
 * This is used to check against replay attacks, see <a
 * href="http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.2"
 * >http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.2</a><br >
 *//* w  w  w  .j  a  va  2s .  c  om*/
public DateTime getSigningTime() {
    try {
        CMSSignedData cmsSignedData = new CMSSignedData(encodedContent);
        SignerInformationStore sis = cmsSignedData.getSignerInfos();

        @SuppressWarnings("unchecked")
        Collection<SignerInformation> signers = sis.getSigners();
        for (SignerInformation signerInformation : signers) {
            AttributeTable signedAttributes = signerInformation.getSignedAttributes();
            Attribute signingTime = signedAttributes.get(CMSAttributes.signingTime);

            @SuppressWarnings("unchecked")
            Enumeration<Object> en = signingTime.getAttrValues().getObjects();
            while (en.hasMoreElements()) {
                Object obj = en.nextElement();
                if (obj instanceof DERUTCTime) {
                    DERUTCTime derTime = (DERUTCTime) obj;
                    return new DateTime(derTime.getDate());
                }
            }
        }
        throw new IllegalArgumentException("Malformed encoded cms content");
    } catch (CMSException e) {
        throw new IllegalArgumentException("Malformed encoded cms content", e);
    } catch (ParseException e) {
        throw new IllegalArgumentException("Malformed encoded cms content", e);
    }
}

From source file:net.sf.assinafacil.AssinadorMSCAPI.java

License:Open Source License

@Override
/***// w  ww. j a v  a2s.c  om
 * Assina digitalmente o arquivo de entrada e gera o arquivo de sa\u00edda.
 * nesse caso a senha n\u00e3o \u00e9 utilizada pois o keystore \u00e9 um token suja senha 
 * ser\u00e1 requerida pelo MSCAPI.
 * 
 * @return Mensagem de status que ser\u00e1 exibida na interface.
 */
public String signFile(String fileInput, String signedFileName, String password, String certificateAlias)
        throws Exception {
    if (!isInitialized()) {
        throw new java.security.KeyException(
                "Chaveiro n\u00c3\u00a3o inicializado ou erro ao acess\u00c3\u00a1-lo.");
    }

    PrivateKey priv = null;
    Certificate storecert = null;
    Certificate[] certChain = null;
    ArrayList<Certificate> certList = new ArrayList<Certificate>();
    CertStore certs = null;
    CMSSignedData signedData = null;
    CMSProcessable content = null;
    byte[] signeddata = null;

    String retorno;

    if (signedFileName == null)
        signedFileName = fileInput;

    certChain = keyStore.getCertificateChain(certificateAlias);

    if (certChain == null) {
        throw new GeneralSecurityException(
                "Cadeia do certificado " + certificateAlias + " n\u00c3\u00a3o encontrada.");
    }
    certList.addAll(Arrays.asList(certChain));

    certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList));

    storecert = keyStore.getCertificate(certificateAlias);
    priv = (PrivateKey) (keyStore.getKey(certificateAlias, null));
    if (priv == null) {
        throw new java.security.AccessControlException(
                "Acesso \u00c3\u00a0 chave foi negado... senha inv\u00c3\u00a1lida?");
    }

    CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();
    signGen.addSigner(priv, (X509Certificate) storecert, CMSSignedDataGenerator.DIGEST_SHA1);
    signGen.addCertificatesAndCRLs(certs);

    try {
        signedData = new CMSSignedData(new FileInputStream(fileInput));
        content = signedData.getSignedContent();
        signGen.addSigners(signedData.getSignerInfos());
        signGen.addCertificatesAndCRLs(signedData.getCertificatesAndCRLs("Collection", "BC"));
        CMSSignedData signedData2 = signGen.generate(content, true, PROVIDER_STRING);
        signeddata = signedData2.getEncoded();

        retorno = "Arquivo " + signedFileName + " foi assinado novamente.";

    } catch (CMSException e) {
        content = new CMSProcessableFile(new File(fileInput));
        signedData = signGen.generate(content, true, PROVIDER_STRING);
        signeddata = signedData.getEncoded();

        retorno = "Arquivo " + signedFileName + " foi assinado.";
    }

    FileOutputStream fileOutput = new FileOutputStream(signedFileName);
    fileOutput.write(signeddata);
    fileOutput.close();

    Logger.getLogger(AssinadorMSCAPI.class.getName()).log(Level.INFO, retorno);

    return retorno;
}

From source file:net.sf.assinafacil.AssinaFacilApp.java

License:Open Source License

public SignerInformationStore getSignatures(File fileInput)
        throws java.security.SignatureException, FileNotFoundException {
    CMSSignedData signedData = null;

    SignerInformationStore signers = null;

    try {// ww w  . j  ava 2  s  .  c o  m
        signedData = new CMSSignedData(new FileInputStream(fileInput));
        signers = signedData.getSignerInfos();

        return signers;

    } catch (CMSException e) {
        throw new SignatureException("Arquivo no assinado ou formato invlido");
    }
}

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);//w ww  . jav a 2  s.com
    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:no.difi.oxalis.as2.util.SMimeBC.java

License:EUPL

/**
 * http://stackoverflow.com/a/31557473/135001
 *//* ww w  . j  a  va  2s.  co m*/
public static X509Certificate verifySignature(Map hashes, byte[] signature)
        throws OxalisSecurityException, OxalisAs2InboundException {
    try {
        CMSSignedData signedData = new CMSSignedData(hashes, signature);

        Store store = signedData.getCertificates();
        SignerInformationStore signerInformationStore = signedData.getSignerInfos();

        for (SignerInformation signerInformation : signerInformationStore.getSigners()) {
            Collection<X509CertificateHolder> certCollection = store.getMatches(signerInformation.getSID());

            Iterator<X509CertificateHolder> certificateIterator = certCollection.iterator();

            if (!certificateIterator.hasNext())
                throw new OxalisAs2InboundException(Disposition.AUTHENTICATION_FAILED,
                        "Unable to find certificate in signature.", null);

            X509CertificateHolder certificateHolder = certificateIterator.next();
            X509Certificate certificate = x509CertificateConverter.getCertificate(certificateHolder);

            SignerInformationVerifier verifier = getSignerInfoVerifierBuilder().build(certificate);

            if (signerInformation.verify(verifier))
                return certificate;
        }

        throw new OxalisSecurityException("Unable to verify signature.");
    } catch (CMSSignerDigestMismatchException e) {
        throw new OxalisSecurityException("Invalid message digest.", e);
    } catch (CMSException | CertificateException | OperatorCreationException e) {
        throw new OxalisSecurityException(e.getMessage(), e);
    }
}

From source file:org.apache.kerby.pkix.SignedDataEngine.java

License:Apache License

/**
 * Validates a CMS SignedData using the public key corresponding to the private
 * key used to sign the structure./*w  ww .ja v  a  2 s  .co m*/
 *
 * @param s
 * @return true if the signature is valid.
 * @throws Exception
 */
public static boolean validateSignedData(CMSSignedData s) throws Exception {

    Store certStore = s.getCertificates();
    Store crlStore = s.getCRLs();
    SignerInformationStore signers = s.getSignerInfos();

    Collection c = signers.getSigners();
    Iterator it = c.iterator();

    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certStore.getMatches(signer.getSID());

        Iterator certIt = certCollection.iterator();
        X509CertificateHolder cert = (X509CertificateHolder) certIt.next();

        if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
            return false;
        }
    }

    Collection certColl = certStore.getMatches(null);
    Collection crlColl = crlStore.getMatches(null);

    if (certColl.size() != s.getCertificates().getMatches(null).size()
            || crlColl.size() != s.getCRLs().getMatches(null).size()) {
        return false;
    }
    return true;
}

From source file:org.apache.pdfbox.examples.pdmodel.TestCreateSignature.java

License:Apache License

private void checkSignature(File file)
        throws IOException, CMSException, OperatorCreationException, GeneralSecurityException {
    PDDocument document = PDDocument.load(file);
    List<PDSignature> signatureDictionaries = document.getSignatureDictionaries();
    if (signatureDictionaries.isEmpty()) {
        Assert.fail("no signature found");
    }//  w w  w  .  j  a v  a  2s .c  om
    for (PDSignature sig : document.getSignatureDictionaries()) {
        COSString contents = (COSString) sig.getCOSObject().getDictionaryObject(COSName.CONTENTS);

        FileInputStream fis = new FileInputStream(file);
        byte[] buf = sig.getSignedContent(fis);
        fis.close();

        // inspiration:
        // http://stackoverflow.com/a/26702631/535646
        // http://stackoverflow.com/a/9261365/535646
        CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(buf), contents.getBytes());
        Store certificatesStore = signedData.getCertificates();
        Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
        SignerInformation signerInformation = signers.iterator().next();
        Collection matches = certificatesStore.getMatches(signerInformation.getSID());
        X509CertificateHolder certificateHolder = (X509CertificateHolder) matches.iterator().next();
        X509Certificate certFromSignedData = new JcaX509CertificateConverter()
                .getCertificate(certificateHolder);

        Assert.assertEquals(certificate, certFromSignedData);

        // CMSVerifierCertificateNotValidException means that the keystore wasn't valid at signing time
        if (!signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData))) {
            Assert.fail("Signature verification failed");
        }
        break;
    }
    document.close();
}

From source file:org.apache.pdfbox.examples.signature.CreateSignature.java

License:Apache License

/**
 * We just extend CMS signed Data/*ww  w.  j  av a 2s. c o  m*/
 *
 * @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 store?
    return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(newSigners));
}

From source file:org.apache.pdfbox.examples.signature.ShowSignature.java

License:Apache License

/**
 * Verify a PKCS7 signature./*from   w ww  .  j  av  a2 s.  c o  m*/
 *
 * @param byteArray the byte sequence that has been signed
 * @param contents the /Contents field as a COSString
 * @param sig the PDF signature (the /V dictionary)
 * @throws CertificateException
 * @throws CMSException
 * @throws StoreException
 * @throws OperatorCreationException
 */
private void verifyPKCS7(byte[] byteArray, COSString contents, PDSignature sig)
        throws CMSException, CertificateException, StoreException, OperatorCreationException {
    // inspiration:
    // http://stackoverflow.com/a/26702631/535646
    // http://stackoverflow.com/a/9261365/535646
    CMSProcessable signedContent = new CMSProcessableByteArray(byteArray);
    CMSSignedData signedData = new CMSSignedData(signedContent, contents.getBytes());
    Store certificatesStore = signedData.getCertificates();
    Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
    SignerInformation signerInformation = signers.iterator().next();
    Collection matches = certificatesStore.getMatches(signerInformation.getSID());
    X509CertificateHolder certificateHolder = (X509CertificateHolder) matches.iterator().next();
    X509Certificate certFromSignedData = new JcaX509CertificateConverter().getCertificate(certificateHolder);
    System.out.println("certFromSignedData: " + certFromSignedData);
    certFromSignedData.checkValidity(sig.getSignDate().getTime());

    if (signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData))) {
        System.out.println("Signature verified");
    } else {
        System.out.println("Signature verification failed");
    }
}