Example usage for org.bouncycastle.cms CMSSignedData CMSSignedData

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

Introduction

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

Prototype

public CMSSignedData(ContentInfo sigData) throws CMSException 

Source Link

Usage

From source file:org.glite.slcs.pki.bouncycastle.CMCPKIResponse.java

License:Apache License

/**
 * Constructor. Decode the CMS signed data in the BC CMSSignedData object.
 * //  w  w  w  . j av a  2 s .  c  om
 * @param signedData
 *            The byte array of of the CMS Signed Data
 * @throws GeneralSecurityException
 *             If an error occurs.
 */
public CMCPKIResponse(byte[] signedData) throws GeneralSecurityException {
    try {
        LOG.debug("decode CMSSignedData...");
        CMSSignedData cmsSignedData = new CMSSignedData(signedData);
        certificatesStore_ = cmsSignedData.getCertificatesAndCRLs("Collection",
                BouncyCastleProvider.PROVIDER_NAME);
    } catch (CMSException e) {
        throw new GeneralSecurityException("CMSException: " + e);
    }
}

From source file:org.jnotary.crypto.Verifier.java

License:Open Source License

@SuppressWarnings("rawtypes")
public VerifyResult verifySignature(byte[] signedData, TrustedStore trustedUserCertificateStore)
        throws Exception {
    CMSSignedData sdata = new CMSSignedData(signedData);
    Store certStore = sdata.getCertificates();
    SignerInformationStore signersStore = sdata.getSignerInfos();
    Collection signers = signersStore.getSigners();
    Iterator it = signers.iterator();

    final Map<SignerId, java.security.cert.X509Certificate> certificates = new HashMap<SignerId, java.security.cert.X509Certificate>();

    List<SignerInformation> signerInfoList = new ArrayList<SignerInformation>();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        signerInfoList.add(signer);//from w w  w . ja  va  2  s .  c  o  m
        X509CertificateHolder cert = getCertificateHolder(trustedUserCertificateStore, certStore, signer);
        ByteArrayInputStream certBais = new ByteArrayInputStream(cert.getEncoded());
        java.security.cert.X509Certificate x509cert = (java.security.cert.X509Certificate) CertificateFactory
                .getInstance("X.509").generateCertificate(certBais);
        certificates.put(signer.getSID(), x509cert);

        verifyDate(signer, x509cert);

        if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)))
            throw new Exception("Signature verification failed for " + cert.getSubject().toString());
    }
    CMSTypedData ctd = sdata.getSignedContent();
    if (ctd == null)
        throw new Exception("Data not exists");
    return new VerifyResult((byte[]) ctd.getContent(), signerInfoList, certificates);
}

From source file:org.jnotary.dvcs.SimpleRequestTest.java

License:Open Source License

@Test(expected = Exception.class)
public void parseCpkcRFCExample() throws IOException, CMSException {

    Reader reader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream("ccpdReqRfc.pem"));
    PEMParser pemParser = new PEMParser(reader);
    byte[] content = pemParser.readPemObject().getContent();
    CMSSignedData signedData = new CMSSignedData(content);
    CMSTypedData data = signedData.getSignedContent();

    DVCSRequest reqIn = DVCSRequest.getInstance(data.getContent());
    assertTrue("Service type is incorrect", reqIn.getRequestInformation().getService() == ServiceType.CCPD);
}

From source file:org.jruby.ext.openssl.x509store.PEMInputOutput.java

License:LGPL

/**
 * Reads in a PKCS7 object. This returns a ContentInfo object suitable for use with the CMS
 * API./*from   w  w  w. java 2s. co  m*/
 *
 * @return the X509Certificate
 * @throws IOException if an I/O error occured
 */
private static CMSSignedData readPKCS7(BufferedReader in, char[] p, String endMarker) throws IOException {
    String line;
    StringBuilder buf = new StringBuilder();
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    while ((line = in.readLine()) != null) {
        if (line.indexOf(endMarker) != -1) {
            break;
        }
        line = line.trim();
        buf.append(line.trim());
        Base64.decode(buf.substring(0, (buf.length() / 4) * 4), bOut);
        buf.delete(0, (buf.length() / 4) * 4);
    }
    if (buf.length() != 0) {
        throw new RuntimeException("base64 data appears to be truncated");
    }
    if (line == null) {
        throw new IOException(endMarker + " not found");
    }
    try {
        ASN1InputStream aIn = new ASN1InputStream(bOut.toByteArray());
        return new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));
    } catch (Exception e) {
        throw new IOException("problem parsing PKCS7 object: " + e.toString());
    }
}

From source file:org.jscep.content.CaCertificateContentHandler.java

License:Open Source License

/**
 * {@inheritDoc}/* ww w. j  a v a 2s  .co  m*/
 */
public List<X509Certificate> getContent(InputStream in, String mimeType) throws IOException {
    LOGGER.entering(getClass().getName(), "getContent", new Object[] { in, mimeType });

    final List<X509Certificate> certs = new ArrayList<X509Certificate>(2);
    final CertificateFactory cf;
    try {
        cf = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        IOException ioe = new IOException(e);

        LOGGER.throwing(getClass().getName(), "getContent", ioe);
        throw ioe;
    }

    if (mimeType.equals("application/x-x509-ca-cert")) {
        // http://tools.ietf.org/html/draft-nourse-scep-20#section-4.1.1.1
        try {

            X509Certificate ca = (X509Certificate) cf.generateCertificate(in);

            // There should only ever be one certificate in this response.
            certs.add(ca);
        } catch (CertificateException ce) {
            IOException ioe = new IOException(ce);

            LOGGER.throwing(getClass().getName(), "getContent", ioe);
            throw ioe;
        }
    } else if (mimeType.equals("application/x-x509-ca-ra-cert")) {
        // If an RA is in use, a certificates-only PKCS#7 SignedData
        // with a certificate chain consisting of both RA and CA certificates is
        // returned.
        // It should be in the order:
        // [0] RA
        // [1] CA
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int b;
        while ((b = in.read()) != -1) {
            baos.write(b);
        }

        // This area needs testing!

        CertStore store;
        try {
            byte[] bytes = baos.toByteArray();
            if (bytes.length == 0) {
                throw new IOException("Expected a SignedData object, but response was empty");
            }
            CMSSignedData sd = new CMSSignedData(bytes);

            store = sd.getCertificatesAndCRLs("Collection", (String) null);
        } catch (Exception e) {
            throw new IOException(e);
        }

        CertSelector selector = new X509CertSelector();
        try {
            @SuppressWarnings("unchecked")
            Collection<X509Certificate> certsCollection = (Collection<X509Certificate>) store
                    .getCertificates(selector);
            for (X509Certificate cert : certsCollection) {
                certs.add(cert);
            }
        } catch (CertStoreException e) {
            IOException ioe = new IOException(e);

            LOGGER.throwing(getClass().getName(), "getContent", ioe);
            throw ioe;
        }
    } else {
        IOException ioe = new IOException("Invalid Content Type");

        LOGGER.throwing(getClass().getName(), "getContent", ioe);
        throw ioe;
    }

    LOGGER.exiting(getClass().getName(), "getContent", certs);

    return certs;
}

From source file:org.jscep.content.CertRepContentHandler.java

License:Open Source License

/**
 * {@inheritDoc}/*from  www.ja v a  2  s  . c o  m*/
 * @throws IOException 
 */
public CMSSignedData getContent(InputStream in, String mimeType) throws IOException {
    LOGGER.entering(getClass().getName(), "getContent", new Object[] { in, mimeType });

    if (mimeType.equals("application/x-pki-message")) {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        int b;
        while ((b = in.read()) != -1) {
            baos.write(b);

        }
        baos.close();

        try {
            return new CMSSignedData(baos.toByteArray());
        } catch (CMSException e) {
            throw new IOException(e);
        }
    } else {
        IOException ioe = new IOException("Invalid Content Type");

        LOGGER.throwing(getClass().getName(), "getContent", ioe);
        throw ioe;
    }
}

From source file:org.jscep.content.NextCaCertificateContentHandler.java

License:Open Source License

/**
 * {@inheritDoc}/*from w  w  w  . ja v a2s.com*/
 */
public List<X509Certificate> getContent(InputStream in, String mimeType) throws IOException {
    LOGGER.entering(getClass().getName(), "getContent", new Object[] { in, mimeType });

    if (mimeType.equals("application/x-x509-next-ca-cert")) {
        // http://tools.ietf.org/html/draft-nourse-scep-20#section-4.6.1

        // The response consists of a SignedData PKCS#7 [RFC2315], 
        // signed by the current CA (or RA) signing key.
        final List<X509Certificate> certs = new ArrayList<X509Certificate>();

        Collection<? extends Certificate> collection;
        try {
            CMSSignedData cmsMessageData = new CMSSignedData(getBytes(in));
            ContentInfo cmsContentInfo = ContentInfo
                    .getInstance(ASN1Object.fromByteArray(cmsMessageData.getEncoded()));

            // TODO: This must be signed by the current CA.
            final SignedData sd = SignedData.getInstance(cmsContentInfo.getContent());
            if (SignedDataUtil.isSignedBy(sd, issuer) == false) {
                IOException ioe = new IOException("Invalid Signer");

                LOGGER.throwing(getClass().getName(), "getContent", ioe);
                throw ioe;
            }
            // The content of the SignedData PKCS#7 [RFC2315] is a degenerate
            // certificates-only Signed-data (Section 3.3) message containing the
            // new CA certificate and any new RA certificates, as defined in
            // Section 5.2.1.1.2, to be used when the current CA certificate
            // expires.
            CertStore store = SignedDataUtil.extractCertStore(sd);
            collection = store.getCertificates(new X509CertSelector());
        } catch (GeneralSecurityException e) {
            final IOException ioe = new IOException(e);

            LOGGER.throwing(getClass().getName(), "getContent", ioe);
            throw ioe;
        } catch (CMSException e) {
            final IOException ioe = new IOException(e);

            LOGGER.throwing(getClass().getName(), "getContent", ioe);
            throw ioe;
        }

        for (Certificate cert : collection) {
            certs.add((X509Certificate) cert);
        }

        LOGGER.exiting(getClass().getName(), "getContent", certs);
        return certs;
    } else {
        IOException ioe = new IOException("Invalid Content Type");

        LOGGER.throwing(getClass().getName(), "getContent", ioe);
        throw ioe;
    }
}

From source file:org.jscep.server.ScepServlet.java

License:Open Source License

/**
 * {@inheritDoc}//from ww  w .  j  ava2  s.c o  m
 */
@SuppressWarnings("unchecked")
@Override
public final void service(final HttpServletRequest req, final HttpServletResponse res)
        throws ServletException, IOException {
    byte[] body = getMessageBytes(req);

    final Operation op;
    try {
        op = getOperation(req);
        if (op == null) {
            // The operation parameter must be set.
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing \"operation\" parameter.");
            return;
        }
    } catch (IllegalArgumentException e) {
        // The operation was not recognised.
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid \"operation\" parameter.");
        return;
    }

    LOGGER.debug("Incoming Operation: " + op);

    final String reqMethod = req.getMethod();

    if (op == Operation.PKI_OPERATION) {
        if (!reqMethod.equals(POST) && !reqMethod.equals(GET)) {
            // PKIOperation must be sent using GET or POST

            res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            res.addHeader("Allow", GET + ", " + POST);

            return;
        }
    } else {
        if (!reqMethod.equals(GET)) {
            // Operations other than PKIOperation must be sent using GET

            res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            res.addHeader("Allow", GET);

            return;
        }
    }

    LOGGER.debug("Method " + reqMethod + " Allowed for Operation: " + op);

    if (op == Operation.GET_CA_CAPS) {
        try {
            LOGGER.debug("Invoking doGetCaCaps");
            doGetCaCaps(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.GET_CA_CERT) {
        try {
            LOGGER.debug("Invoking doGetCaCert");
            doGetCaCert(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.GET_NEXT_CA_CERT) {
        try {
            LOGGER.debug("Invoking doGetNextCaCert");
            doGetNextCaCert(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.PKI_OPERATION) {
        // PKIOperation

        res.setHeader("Content-Type", "application/x-pki-message");

        CMSSignedData sd;
        try {
            sd = new CMSSignedData(body);
        } catch (CMSException e) {
            throw new ServletException(e);
        }

        Store reqStore = sd.getCertificates();
        Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);

        CertificateFactory factory;
        try {
            factory = CertificateFactory.getInstance("X.509");
        } catch (CertificateException e) {
            throw new ServletException(e);
        }
        X509CertificateHolder holder = reqCerts.iterator().next();
        ByteArrayInputStream bais = new ByteArrayInputStream(holder.getEncoded());
        X509Certificate reqCert;
        try {
            reqCert = (X509Certificate) factory.generateCertificate(bais);
        } catch (CertificateException e) {
            throw new ServletException(e);
        }

        PkiMessage<?> msg;
        try {
            PkcsPkiEnvelopeDecoder envDecoder = new PkcsPkiEnvelopeDecoder(getRecipient(), getRecipientKey());
            PkiMessageDecoder decoder = new PkiMessageDecoder(reqCert, envDecoder);
            msg = decoder.decode(sd);
        } catch (MessageDecodingException e) {
            LOGGER.error("Error decoding request", e);
            throw new ServletException(e);
        }

        LOGGER.debug("Processing message {}", msg);

        MessageType msgType = msg.getMessageType();
        Object msgData = msg.getMessageData();

        Nonce senderNonce = Nonce.nextNonce();
        TransactionId transId = msg.getTransactionId();
        Nonce recipientNonce = msg.getSenderNonce();
        CertRep certRep;

        if (msgType == MessageType.GET_CERT) {
            final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
            final X500Name principal = iasn.getName();
            final BigInteger serial = iasn.getSerialNumber().getValue();

            try {
                List<X509Certificate> issued = doGetCert(principal, serial);
                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.GET_CERT_INITIAL) {
            final IssuerAndSubject ias = (IssuerAndSubject) msgData;
            final X500Name issuer = X500Name.getInstance(ias.getIssuer());
            final X500Name subject = X500Name.getInstance(ias.getSubject());

            try {
                List<X509Certificate> issued = doGetCertInitial(issuer, subject, transId);

                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.GET_CRL) {
            final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
            final X500Name issuer = iasn.getName();
            final BigInteger serialNumber = iasn.getSerialNumber().getValue();

            try {
                LOGGER.debug("Invoking doGetCrl");
                CMSSignedData messageData = getMessageData(doGetCrl(issuer, serialNumber));

                certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
            } catch (OperationFailureException e) {
                LOGGER.error("Error executing GetCRL request", e);
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                LOGGER.error("Error executing GetCRL request", e);
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.PKCS_REQ) {
            final PKCS10CertificationRequest certReq = (PKCS10CertificationRequest) msgData;

            try {
                LOGGER.debug("Invoking doEnrol");
                List<X509Certificate> issued = doEnrol(certReq, reqCert, transId);

                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else {
            throw new ServletException("Unknown Message for Operation");
        }

        PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, "DESede");
        PkiMessageEncoder encoder = new PkiMessageEncoder(getSignerKey(), getSigner(),
                getSignerCertificateChain(), envEncoder);
        CMSSignedData signedData;
        try {
            signedData = encoder.encode(certRep);
        } catch (MessageEncodingException e) {
            LOGGER.error("Error decoding response", e);
            throw new ServletException(e);
        }

        res.getOutputStream().write(signedData.getEncoded());
        res.getOutputStream().close();
    } else {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown Operation");
    }
}

From source file:org.jscep.transport.response.PkiOperationResponseHandler.java

License:Open Source License

/**
 * {@inheritDoc}//from  www.  j a v  a 2s .c  o  m
 */
@Override
public CMSSignedData getResponse(final byte[] content, final String mimeType) throws ContentException {
    if (mimeType.startsWith(PKI_MESSAGE)) {
        try {
            return new CMSSignedData(content);
        } catch (CMSException e) {
            throw new InvalidContentException(e);
        }
    } else {
        throw new InvalidContentTypeException(mimeType, PKI_MESSAGE);
    }
}

From source file:org.neociclo.odetteftp.util.EnvelopingUtil.java

License:Apache License

/**
 * Retrieve the signed content from a SignedData object. Signature MUST BE
 * VERIFIED apart since it's the original data without the signature
 * information./* ww  w .ja v a  2s  .c  o m*/
 * 
 * @param encoded
 *            the SignedData object
 * @return the original data from signed content
 * @throws CMSException
 */
public static byte[] parseSignedData(byte[] encoded) throws CMSException {

    installBouncyCastleProviderIfNecessary();

    CMSSignedData signed = new CMSSignedData(encoded);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {
        signed.getSignedContent().write(bout);
    } catch (IOException e) {
        // ignore in a hope it won't happen with ByteArrayOutputStream
        LOGGER.error("parseSignedData() - Failed to retrieve SignedData content.", e);
        return null;
    }
    byte[] content = bout.toByteArray();

    return content;
}