Example usage for java.security.cert CertificateFactory generateCertificate

List of usage examples for java.security.cert CertificateFactory generateCertificate

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory generateCertificate.

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:org.wso2.carbon.mdm.mobileservices.windowspc.services.wstep.impl.CertificateEnrollmentServiceImpl.java

/**
 * Method for setting privateKey and rootCACertificate variables.
 *
 * @throws KeyStoreGenerationException//from   w ww . jav  a  2 s .c  o m
 * @throws org.wso2.carbon.mdm.mobileservices.windows.common.exceptions
 * .XMLFileOperationException
 * @throws CertificateGenerationException
 */
public void setRootCertAndKey(String storePassword, String keyPassword)
        throws KeyStoreGenerationException, XMLFileOperationException, CertificateGenerationException {

    File JKSFile = new File(getClass().getClassLoader()
            .getResource(Constants.CertificateEnrollment.WSO2_MDM_JKS_FILE).getFile());
    String JKSFilePath = JKSFile.getPath();
    KeyStore securityJKS;
    try {
        securityJKS = KeyStoreGenerator.getKeyStore();
    } catch (KeyStoreGenerationException e) {
        throw new KeyStoreGenerationException("Cannot retrieve the MDM key store.", e);
    }

    try {
        KeyStoreGenerator.loadToStore(securityJKS, storePassword.toCharArray(), JKSFilePath);
    } catch (KeyStoreGenerationException e) {
        throw new KeyStoreGenerationException("Cannot load the MDM key store.", e);
    }

    PrivateKey CAPrivateKey;
    try {
        CAPrivateKey = (PrivateKey) securityJKS.getKey(Constants.CertificateEnrollment.CA_CERT,
                keyPassword.toCharArray());
    } catch (KeyStoreException e) {
        throw new CertificateGenerationException("Cannot generate private key due to Key store error.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateGenerationException(
                "Requested cryptographic algorithm is not available in the environment.", e);
    } catch (UnrecoverableKeyException e) {
        throw new CertificateGenerationException("Cannot recover private key.", e);
    }

    privateKey = CAPrivateKey;
    Certificate CACertificate;
    try {
        CACertificate = securityJKS.getCertificate(Constants.CertificateEnrollment.CA_CERT);
    } catch (KeyStoreException e) {
        throw new KeyStoreGenerationException("Keystore cannot be accessed.", e);
    }
    CertificateFactory certificateFactory;

    try {
        certificateFactory = CertificateFactory.getInstance(Constants.CertificateEnrollment.X_509);
    } catch (CertificateException e) {
        throw new CertificateGenerationException("Cannot initiate certificate factory.", e);
    }

    ByteArrayInputStream byteArrayInputStream;
    try {
        byteArrayInputStream = new ByteArrayInputStream(CACertificate.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new CertificateGenerationException("CA certificate cannot be encoded.", e);
    }

    X509Certificate X509CACertificate;
    try {
        X509CACertificate = (X509Certificate) certificateFactory.generateCertificate(byteArrayInputStream);
    } catch (CertificateException e) {
        throw new CertificateGenerationException("X509 CA certificate cannot be generated.", e);
    }
    rootCACertificate = X509CACertificate;
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException {

    if (headerSignature == null || headerSignature.isEmpty()) {
        return null;
    }/*  w w  w .  j  a  va 2s .c  o m*/

    try {
        KeyStoreReader keyStoreReader = new KeyStoreReader();
        CMSSignedData signedData = new CMSSignedData(Base64.decodeBase64(headerSignature.getBytes()));
        Store reqStore = signedData.getCertificates();
        @SuppressWarnings("unchecked")
        Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);

        if (reqCerts != null && reqCerts.size() > 0) {
            CertificateFactory certificateFactory = CertificateFactory
                    .getInstance(CertificateManagementConstants.X_509);
            X509CertificateHolder holder = reqCerts.iterator().next();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(holder.getEncoded());
            X509Certificate reqCert = (X509Certificate) certificateFactory
                    .generateCertificate(byteArrayInputStream);

            if (reqCert != null && reqCert.getSerialNumber() != null) {
                Certificate lookUpCertificate = keyStoreReader
                        .getCertificateByAlias(reqCert.getSerialNumber().toString());

                if (lookUpCertificate instanceof X509Certificate) {
                    return (X509Certificate) lookUpCertificate;
                }
            }

        }
    } catch (CMSException e) {
        String errorMsg = "CMSException when decoding certificate signature";
        throw new KeystoreException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "IOException when decoding certificate signature";
        throw new KeystoreException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "CertificateException when decoding certificate signature";
        throw new KeystoreException(errorMsg, e);
    }

    return null;
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

public byte[] getPKIMessage(InputStream inputStream) throws KeystoreException {

    try {/*from w  ww  .ja  v a  2 s . c om*/
        CMSSignedData signedData = new CMSSignedData(inputStream);
        Store reqStore = signedData.getCertificates();
        @SuppressWarnings("unchecked")
        Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);

        KeyStoreReader keyStoreReader = new KeyStoreReader();
        PrivateKey privateKeyRA = keyStoreReader.getRAPrivateKey();
        PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
        X509Certificate certRA = (X509Certificate) keyStoreReader.getRACertificate();
        X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();

        CertificateFactory certificateFactory = CertificateFactory
                .getInstance(CertificateManagementConstants.X_509);
        X509CertificateHolder holder = reqCerts.iterator().next();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(holder.getEncoded());
        X509Certificate reqCert = (X509Certificate) certificateFactory
                .generateCertificate(byteArrayInputStream);

        PkcsPkiEnvelopeDecoder envelopeDecoder = new PkcsPkiEnvelopeDecoder(certRA, privateKeyRA);
        PkiMessageDecoder messageDecoder = new PkiMessageDecoder(reqCert, envelopeDecoder);
        PkiMessage<?> pkiMessage = messageDecoder.decode(signedData);
        Object msgData = pkiMessage.getMessageData();

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

        PKCS10CertificationRequest certRequest = (PKCS10CertificationRequest) msgData;
        X509Certificate generatedCert = generateCertificateFromCSR(privateKeyCA, certRequest,
                certCA.getIssuerX500Principal().getName());

        List<X509Certificate> issued = new ArrayList<X509Certificate>();
        issued.add(generatedCert);

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

        PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert,
                CertificateManagementConstants.DES_EDE);
        PkiMessageEncoder encoder = new PkiMessageEncoder(privateKeyRA, certRA, envEncoder);
        CMSSignedData cmsSignedData = encoder.encode(certRep);

        return cmsSignedData.getEncoded();

    } catch (CertificateException e) {
        String errorMsg = "Certificate issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    } catch (MessageEncodingException e) {
        String errorMsg = "Message encoding issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "Input output issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    } catch (MessageDecodingException e) {
        String errorMsg = "Message decoding issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    } catch (CMSException e) {
        String errorMsg = "CMS issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    }
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

private X509Certificate loadCerToX509Certificate(CertificateBundle certificateBundle)
        throws CertificateException, IOException {
    Assert.assertNotNull(certificateBundle.cer());
    ByteArrayInputStream cerStream = new ByteArrayInputStream(certificateBundle.cer());
    CertificateFactory certificateFactory = CertificateFactory.getInstance(X509);
    X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(cerStream);
    cerStream.close();/*w  ww  . j  av a2  s  .  c o  m*/
    return x509Certificate;
}

From source file:org.jenkins_ci.update_center.Main.java

/**
 * Loads a certificate chain and makes sure it's valid.
 *//* w ww.j a  va 2  s  . c o m*/
protected List<X509Certificate> getCertificateChain() throws IOException, GeneralSecurityException {
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    for (File f : certificates) {
        certs.add(loadCertificate(cf, f));
    }

    Set<TrustAnchor> rootCAs = CertificateUtil.getDefaultRootCAs();
    InputStream stream = getClass().getResourceAsStream("/hudson-community.cert");
    try {
        rootCAs.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null));
    } finally {
        IOUtils.closeQuietly(stream);
    }
    for (File f : rootCA) {
        rootCAs.add(new TrustAnchor(loadCertificate(cf, f), null));
    }

    try {
        CertificateUtil.validatePath(certs, rootCAs);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }
    return certs;
}

From source file:com.xwiki.authentication.saml.XWikiSAMLAuthenticator.java

/**
 * {@inheritDoc}//from w  w  w .ja  va 2 s . c om
 *
 * @see com.xpn.xwiki.user.impl.xwiki.AppServerTrustedAuthServiceImpl#checkSAMLResponse(com.xpn.xwiki.XWikiContext)
 */
public boolean checkSAMLResponse(XWikiContext context) throws XWikiException {
    // read from SAMLResponse
    XWikiRequest request = context.getRequest();
    Map attributes = new HashMap();

    String samlResponse = request.getParameter("SAMLResponse");
    if (samlResponse == null)
        return false;

    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Reading SAML Response");
        }
        samlResponse = new String(Base64.decode(samlResponse), "UTF-8");

        if (LOG.isDebugEnabled()) {
            LOG.debug("SAML Response is " + samlResponse);
        }

        // Get parser pool manager
        BasicParserPool ppMgr = new BasicParserPool();
        ppMgr.setNamespaceAware(true);
        Document inCommonMDDoc;

        inCommonMDDoc = ppMgr.parse(new StringReader(samlResponse));
        Element ResponseRoot = inCommonMDDoc.getDocumentElement();
        // Get apropriate unmarshaller
        UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
        Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(ResponseRoot);
        // Unmarshall using the document root element, an EntitiesDescriptor
        Response response = (Response) unmarshaller.unmarshall(ResponseRoot);

        // reading cert
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        String cert = getSAMLCertificate(context);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Verification signature using certificate " + cert);
        }
        InputStream sis = context.getEngineContext().getResourceAsStream(cert);
        X509Certificate certificate = (X509Certificate) cf.generateCertificate(sis);
        sis.close();

        response.validate(true);
        Signature signature = response.getSignature();
        SAMLSignatureProfileValidator pv = new SAMLSignatureProfileValidator();
        pv.validate(signature);
        BasicX509Credential credential = new BasicX509Credential();
        credential.setEntityCertificate(certificate);
        SignatureValidator sigValidator = new SignatureValidator(credential);
        sigValidator.validate(signature);

        Assertion subjectAssertion = null;
        boolean isValidDate = true;

        if (LOG.isDebugEnabled()) {
            LOG.debug("Reading SAML User data");
        }

        // Verify assertions
        for (Assertion a : response.getAssertions()) {
            // Find subject assertions
            if (a.getAuthnStatements().size() > 0) {
                if (a.getConditions().getNotOnOrAfter().isBeforeNow())
                    isValidDate = false;
            }

            // Process all attributes
            for (AttributeStatement attStatement : a.getAttributeStatements()) {
                for (Attribute att : attStatement.getAttributes()) {
                    for (XMLObject val : att.getAttributeValues()) {
                        attributes.put(att.getName(), ((XSStringImpl) val).getValue());
                    }
                }
                for (EncryptedAttribute att : attStatement.getEncryptedAttributes()) {
                    for (XMLObject val : ((Attribute) att).getAttributeValues()) {
                        attributes.put(((Attribute) att).getName(), ((XSStringImpl) val).getValue());
                    }
                }
            }
        }

        String samlid1 = response.getInResponseTo();
        String samlid2 = (String) request.getSession().getAttribute("saml_id");
        if (isValidDate == false) {
            // invalid ID
            if (LOG.isErrorEnabled()) {
                LOG.error("SAML Dates are invalid");
            }
            return false;
        }
        if (!samlid1.equals(samlid2)) {
            // invalid ID
            if (LOG.isErrorEnabled()) {
                LOG.error("SAML ID do not match " + samlid1 + " " + samlid2);
            }
            return false;
        }
    } catch (Exception e1) {
        // failed to read SAMLResponse
        if (LOG.isErrorEnabled()) {
            LOG.error("Failed Reading SAML Response", e1);
        }
        return false;
    }

    // let's map the data
    Map<String, String> userData = getExtendedInformations(attributes, context);

    String nameID = (String) attributes.get(getIdFieldName(context));
    if (LOG.isDebugEnabled()) {
        LOG.debug("SAML ID is " + nameID);
        LOG.debug("SAML attributes are " + attributes);
        LOG.debug("SAML user data are " + userData);
    }

    String sql = "select distinct doc.fullName from XWikiDocument as doc, BaseObject as obj, StringProperty as nameidprop where doc.fullName=obj.name and obj.className='XWiki.SAMLAuthClass' and obj.id=nameidprop.id.id and nameidprop.id.name='nameid' and nameidprop.value='"
            + nameID + "'";
    List list = context.getWiki().search(sql, context);
    String validFullUserName = null;
    String validUserName = null;

    if (list.size() == 0) {
        // User does not exist. Let's generate a unique page name      
        if (LOG.isDebugEnabled()) {
            LOG.debug("Did not find XWiki User. Generating it.");
        }
        String userName = generateXWikiUsername(userData, context);
        if (userName.equals(""))
            userName = "user";
        validUserName = context.getWiki().getUniquePageName("XWiki", userName, context);
        validFullUserName = "XWiki." + validUserName;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Generated XWiki User Name " + validFullUserName);
        }
    } else {
        validFullUserName = (String) list.get(0);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Found XWiki User " + validFullUserName);
        }
    }

    // we found a user or generated a unique user name       
    if (validFullUserName != null) {
        // check if we need to create/update a user page
        String database = context.getDatabase();
        try {
            // Switch to main wiki to force users to be global users
            context.setDatabase(context.getMainXWiki());

            // test if user already exists
            if (!context.getWiki().exists(validFullUserName, context)) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Need to create user " + validFullUserName);
                }

                // create user
                userData.put("active", "1");

                int result = context.getWiki().createUser(validUserName, userData, "XWiki.XWikiUsers",
                        "#includeForm(\"XWiki.XWikiUserSheet\")", "edit", context);
                if (result < 0) {
                    if (LOG.isErrorEnabled()) {
                        LOG.error("Failed to create user " + validFullUserName + " with code " + result);
                    }
                    return false;
                }
                XWikiDocument userDoc = context.getWiki().getDocument(validFullUserName, context);
                BaseObject obj = userDoc.newObject("XWiki.SAMLAuthClass", context);
                obj.set("nameid", nameID, context);
                context.getWiki().saveDocument(userDoc, context);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("User " + validFullUserName + " has been successfully created");
                }
            } else {
                XWikiDocument userDoc = context.getWiki().getDocument(validFullUserName, context);
                BaseObject userObj = userDoc.getObject("XWiki.XWikiUsers");
                boolean updated = false;

                for (Map.Entry<String, String> entry : userData.entrySet()) {
                    String field = entry.getKey();
                    String value = entry.getValue();
                    BaseProperty prop = (BaseProperty) userObj.get(field);
                    String currentValue = (prop == null || prop.getValue() == null) ? null
                            : prop.getValue().toString();
                    if (value != null && !value.equals(currentValue)) {
                        userObj.set(field, value, context);
                        updated = true;
                    }
                }

                if (updated == true) {
                    context.getWiki().saveDocument(userDoc, context);

                    if (LOG.isDebugEnabled()) {
                        LOG.debug("User " + validFullUserName + " has been successfully updated");
                    }
                }

            }
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Failed to create user " + validFullUserName, e);
            }
            return false;
        } finally {
            context.setDatabase(database);
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Setting authentication in session for user " + validFullUserName);
    }

    // mark that we have authenticated the user in the session
    context.getRequest().getSession().setAttribute(getAuthFieldName(context), validFullUserName);

    // need to redirect now
    try {
        String sourceurl = (String) request.getSession().getAttribute("saml_url");
        if (LOG.isDebugEnabled()) {
            LOG.debug("Redirecting after valid authentication to " + sourceurl);
        }
        context.getResponse().sendRedirect(sourceurl);
        context.setFinished(true);
        return true;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

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

/**
 * {@inheritDoc}//from  ww w . j  a v  a2  s .com
 */
@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.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Writer writer = res.getWriter();
            writer.write("Missing \"operation\" parameter.");
            writer.flush();

            return;
        }
    } catch (IllegalArgumentException e) {
        // The operation was not recognised.

        res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        Writer writer = res.getWriter();
        writer.write("Invalid \"operation\" parameter.");
        writer.flush();

        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, 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.hyperledger.fabric.sdk.security.CryptoPrimitives.java

/**
 * Return X509Certificate  from pem bytes.
 * So you may ask why this ?  Well some providers (BC) seems to have problems with creating the
 * X509 cert from bytes so here we go through all available providers till one can convert. :)
 *
 * @param pemCertificate//w w w.j av  a  2 s.  co m
 * @return
 */

private X509Certificate getX509Certificate(byte[] pemCertificate) throws CryptoException {
    X509Certificate ret = null;
    CryptoException rete = null;

    List<Provider> providerList = new LinkedList<>(Arrays.asList(Security.getProviders()));
    if (SECURITY_PROVIDER != null) { //Add if overridden
        providerList.add(SECURITY_PROVIDER);
    }
    try {
        providerList.add(BouncyCastleProvider.class.newInstance()); // bouncy castle is there always.
    } catch (Exception e) {
        logger.warn(e);

    }
    for (Provider provider : providerList) {
        try {
            if (null == provider) {
                continue;
            }
            CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT, provider);
            if (null != certFactory) {
                try (ByteArrayInputStream bis = new ByteArrayInputStream(pemCertificate)) {
                    Certificate certificate = certFactory.generateCertificate(bis);

                    if (certificate instanceof X509Certificate) {
                        ret = (X509Certificate) certificate;
                        rete = null;
                        break;
                    }
                }

            }
        } catch (Exception e) {

            rete = new CryptoException(e.getMessage(), e);

        }

    }

    if (null != rete) {

        throw rete;

    }

    if (ret == null) {

        logger.error("Could not convert pem bytes");

    }

    return ret;

}

From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java

synchronized private void readSiteCertificates(ServletContext servletContext) {
    if (trustedCerts != null)
        return;//  w  ww . ja  v a  2s .co m

    trustedCerts = new ArrayList<>();

    // Now to add the other certificates added to the site
    File certsDirectory = new File(servletContext.getRealPath("/WEB-INF/classes/certificates"));
    try {
        if (certsDirectory.exists()) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            String[] certs = certsDirectory.list(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String fileName) {
                    return fileName.endsWith(".crt") || fileName.endsWith(".cer") || fileName.endsWith(".pem");
                }

            });
            if (certs != null) {
                X509Certificate x509Cert;
                for (String cert : certs) {
                    try (FileInputStream fis = new FileInputStream(new File(certsDirectory, cert))) {
                        x509Cert = (X509Certificate) cf.generateCertificate(fis);
                    }
                    if (x509Cert != null && !trustedCerts.contains(x509Cert)) {
                        trustedCerts.add(x509Cert);
                    }
                }
            }
        }
    } catch (Throwable e1) {
        LOG.log(Level.INFO, "Failed to load certificates from diretory " + certsDirectory.getAbsolutePath(),
                e1);
    }
}