Example usage for java.security KeyStore getCertificateChain

List of usage examples for java.security KeyStore getCertificateChain

Introduction

In this page you can find the example usage for java.security KeyStore getCertificateChain.

Prototype

public final Certificate[] getCertificateChain(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate chain associated with the given alias.

Usage

From source file:org.ejbca.extra.ra.ScepRAServlet.java

private void getCACertChain(String message, String remoteAddr, HttpServletResponse response, String alias,
        KeyStore raks, boolean getcaracertchain)
        throws KeyStoreException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchProviderException, CertStoreException, CMSException, IOException, Exception {
    Certificate[] chain = raks.getCertificateChain(alias);
    log.debug("CACertChain is of length: " + chain.length);
    if (chain != null) {
        X509Certificate cert = (X509Certificate) raks.getCertificateChain(alias)[0];
        log.debug("Found cert with DN '" + cert.getSubjectDN().toString() + "'");
        //            X509Certificate racert = (X509Certificate) raks.getCertificate(alias);
        //            PrivateKey rapriv = (PrivateKey) raks.getKey(alias, keystorepwd.toCharArray());
        byte[] pkcs7response = createPKCS7(chain, null, null);
        String ctype = "application/x-x509-ca-ra-cert";
        if (getcaracertchain) {
            ctype = "application/x-x509-ca-ra-cert-chain";
        }/*from   w  w w.j  a va2 s  .  c  om*/
        log.debug("Sent certificate(s) for CA/RA '" + message + "' to SCEP client with ip " + remoteAddr
                + ". Using content-type: " + ctype);
        sendBinaryBytes(pkcs7response, response, ctype, null);
    } else {
        log.error("No CA certificates found");
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "No CA certificates found.");
    }
}

From source file:org.ejbca.extra.ra.ScepRAServlet.java

private void service(String operation, String message, String remoteAddr, HttpServletResponse response)
        throws IOException {
    try {/*w w w .  j a v  a 2  s.  c o m*/
        if ((operation == null) || (message == null)) {
            log.error("Got request missing operation and/or message parameters.");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Parameters 'operation' and 'message' must be supplied!");
            return;
        }
        log.debug("Got request '" + operation + "'");
        log.debug("Message: " + message);
        log.debug("Operation is : " + operation);

        String alias = scepraks.getAlias();
        log.debug("SCEP RA Keystore alias : " + alias);
        KeyStore raks = scepraks.getKeyStore();
        Certificate[] chain = raks.getCertificateChain(alias);
        X509Certificate cacert = null;
        if (chain.length > 1) {
            // This should absolutely be more than one!
            cacert = (X509Certificate) chain[1];
        } else {
            log.error(
                    "Certificate chain in RA keystore is only 1 certificate long! This is en error, because there should also be CA certificates.");
        }
        X509Certificate racert = (X509Certificate) raks.getCertificate(alias);
        String kspwd = ExtraConfiguration.instance()
                .getString(ExtraConfiguration.SCEPKEYSTOREPWD + keyStoreNumber);
        PrivateKey rapriv = (PrivateKey) raks.getKey(alias, kspwd.toCharArray());

        if (operation.equals("PKIOperation")) {
            byte[] scepmsg = Base64.decode(message.getBytes());

            // Read the message end get the cert, this also checks authorization
            boolean includeCACert = true;
            if (StringUtils.equals("0", getInitParameter("includeCACert"))) {
                includeCACert = false;
            }

            byte[] reply = null;
            ScepRequestMessage reqmsg = new ScepRequestMessage(scepmsg, includeCACert);
            String transId = reqmsg.getTransactionId();
            log.debug("Received a message of type: " + reqmsg.getMessageType());
            if (reqmsg.getMessageType() == ScepRequestMessage.SCEP_TYPE_GETCERTINITIAL) {
                log.info("Received a GetCertInitial message from host: " + remoteAddr);
                Message msg = null;
                try {
                    msg = msgHome.findByMessageId(transId);
                } catch (Exception e) {
                    // TODO: internal resources
                    log.info("Error looking for message with transId " + transId + " :", e);
                }
                if (msg != null) {
                    if (msg.getStatus().equals(Message.STATUS_PROCESSED)) {
                        log.debug("Request is processed with status: " + msg.getStatus());
                        SubMessages submessagesresp = msg.getSubMessages(null, null, null);
                        Iterator<ISubMessage> iter = submessagesresp.getSubMessages().iterator();
                        PKCS10Response resp = (PKCS10Response) iter.next();
                        // create proper ScepResponseMessage
                        IResponseMessage ret = reqmsg.createResponseMessage(
                                org.ejbca.core.protocol.scep.ScepResponseMessage.class, reqmsg, racert, rapriv,
                                cryptProvider);
                        ret.setCACert(cacert);
                        X509Certificate respCert = resp.getCertificate();
                        if (resp.isSuccessful() && (respCert != null)) {
                            ret.setCertificate(respCert);
                        } else {
                            ret.setStatus(ResponseStatus.FAILURE);
                            ret.setFailInfo(FailInfo.BAD_REQUEST);
                            String failText = resp.getFailInfo();
                            ret.setFailText(failText);
                        }
                        ret.create();
                        reply = ret.getResponseMessage();
                    } else {
                        log.debug("Request is not yet processed, status: " + msg.getStatus());
                        reply = createPendingResponseMessage(reqmsg, racert, rapriv, cryptProvider)
                                .getResponseMessage();
                        log.debug("Responding with pending response, still pending.");
                    }
                } else {
                    // User doesn't exist
                }
            } else {
                if (reqmsg.getMessageType() == ScepRequestMessage.SCEP_TYPE_PKCSREQ) {
                    log.debug("Received a PKCSReq message from host: " + remoteAddr);
                    // Decrypt the Scep message and extract the pkcs10 request
                    if (reqmsg.requireKeyInfo()) {
                        // scep encrypts message with the RAs certificate
                        reqmsg.setKeyInfo(racert, rapriv, cryptProvider);
                    }
                    // Verify the request
                    if (reqmsg.verify() == false) {
                        String msg = "POPO verification failed.";
                        log.error(msg);
                        throw new SignRequestSignatureException(msg);
                    }
                    String username = reqmsg.getUsername();
                    if (username == null) {
                        String msg = "No username in request, request DN: " + reqmsg.getRequestDN();
                        log.error(msg);
                        throw new SignRequestException(msg);
                    }
                    log.info("Received a SCEP/PKCS10 request for user: " + username + ", from host: "
                            + remoteAddr);
                    String authPwd = ExtraConfiguration.instance().getString(ExtraConfiguration.SCEPAUTHPWD);
                    if (StringUtils.isNotEmpty(authPwd) && !StringUtils.equals(authPwd, "none")) {
                        log.debug("Requiring authPwd in order to precess SCEP requests");
                        String pwd = reqmsg.getPassword();
                        if (!StringUtils.equals(authPwd, pwd)) {
                            log.error("Wrong auth password received in SCEP request: " + pwd);
                            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Auth pwd missmatch");
                            return;
                        }
                        log.debug("Request passed authPwd test.");
                    } else {
                        log.debug("Not requiring authPwd in order to precess SCEP requests");
                    }
                    // Try to find the CA name from the issuerDN, if we can't find it (i.e. not defined in web.xml) we use the default
                    String issuerDN = CertTools.stringToBCDNString(reqmsg.getIssuerDN());
                    String caName = ExtraConfiguration.instance().getString(issuerDN);
                    if (StringUtils.isEmpty(caName)) {
                        caName = ExtraConfiguration.instance().getString(ExtraConfiguration.SCEPDEFAULTCA);
                        log.info("Did not find a CA name from issuerDN: " + issuerDN
                                + ", using the default CA '" + caName + "'");
                    } else {
                        log.debug("Found a CA name '" + caName + "' from issuerDN: " + issuerDN);
                    }
                    // Get altNames if we can find them
                    String altNames = reqmsg.getRequestAltNames();

                    byte[] encoded = reqmsg.getCertificationRequest().getEncoded();
                    String pkcs10 = new String(Base64.encode(encoded, false));

                    // Create a pkcs10 request
                    String certificateProfile = ExtraConfiguration.instance()
                            .getString(ExtraConfiguration.SCEPCERTPROFILEKEY);
                    String entityProfile = ExtraConfiguration.instance()
                            .getString(ExtraConfiguration.SCEPENTITYPROFILEKEY);
                    boolean createOrEditUser = ExtraConfiguration.instance()
                            .getBoolean(ExtraConfiguration.SCEPEDITUSER);
                    PKCS10Request req = new PKCS10Request(100, username, reqmsg.getRequestDN(), altNames, null,
                            null, entityProfile, certificateProfile, caName, pkcs10);
                    req.setCreateOrEditUser(createOrEditUser);
                    SubMessages submessages = new SubMessages();
                    submessages.addSubMessage(req);
                    msgHome.create(transId, submessages);
                    reply = createPendingResponseMessage(reqmsg, racert, rapriv, cryptProvider)
                            .getResponseMessage();
                }
            }

            if (reply == null) {
                // This is probably a getCert message?
                log.debug("Sending HttpServletResponse.SC_NOT_IMPLEMENTED (501) response");
                response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "Can not handle request");
                return;
            }
            // Send back SCEP response, PKCS#7 which contains the end entity's certificate, or pending, or failure
            sendBinaryBytes(reply, response, "application/x-pki-message", null);
        } else if (operation.equals("GetCACert")) {
            // The response has the content type tagged as application/x-x509-ca-cert. 
            // The body of the response is a DER encoded binary X.509 certificate. 
            // For example: "Content-Type:application/x-x509-ca-cert\n\n"<BER-encoded X509>
            // IF we are not an RA, which in case we should return the same thing as GetCACertChain
            log.info("Got SCEP cert request for CA '" + message + "'");
            if (chain != null) {
                if (chain.length > 1) {
                    // We are an RA, so return the same as GetCACertChain, but with other content type
                    getCACertChain(message, remoteAddr, response, alias, raks, false);
                } else {
                    // The CA certificate is no 0
                    X509Certificate cert = (X509Certificate) chain[0];
                    if (chain.length > 1) {
                        cert = (X509Certificate) chain[1];
                    }
                    log.debug("Found cert with DN '" + cert.getSubjectDN().toString() + "'");
                    log.info("Sent certificate for CA '" + message + "' to SCEP client with ip " + remoteAddr);
                    sendBinaryBytes(cert.getEncoded(), response, "application/x-x509-ca-cert", null);
                }
            } else {
                log.error("No CA certificates found");
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "No CA certificates found.");
            }
        } else if (operation.equals("GetCACertChain")) {
            // The response for GetCACertChain is a certificates-only PKCS#7 
            // SignedDatato carry the certificates to the end entity, with a 
            // Content-Type of application/x-x509-ca-ra-cert-chain.
            log.info("Got SCEP cert chain request for CA '" + message + "'");
            getCACertChain(message, remoteAddr, response, alias, raks, true);
        } else if (operation.equals("GetCACaps")) {
            // The response for GetCACaps is a <lf> separated list of capabilities

            /*
             "GetNextCACert"       CA Supports the GetNextCACert message.
             "POSTPKIOperation"    PKIOPeration messages may be sent via HTTP POST.
             "SHA-1"               CA Supports the SHA-1 hashing algorithm in 
                               signatures and fingerprints.  If present, the
                               client SHOULD use SHA-1.  If absent, the client
                               MUST use MD5 to maintain backward compatability.
             "Renewal"             Clients may use current certificate and key to
                               authenticate an enrollment request for a new
                               certificate.  
             */
            log.info("Got SCEP CACaps request for CA '" + message + "'");
            response.setContentType("text/plain");
            response.getOutputStream().print("POSTPKIOperation\nSHA-1");
        }
    } catch (java.lang.ArrayIndexOutOfBoundsException ae) {
        log.error("Empty or invalid request received.", ae);
        // TODO: Send back proper Failure Response
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, ae.getMessage());
    } catch (Exception e) {
        log.error("Error in ScepRAServlet:", e);
        // TODO: Send back proper Failure Response
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    }
}

From source file:org.ovirt.engine.core.utils.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/*  w w w. j  a  v  a 2  s.c o  m*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LOG.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LOG.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSLv3");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException(
                "I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:org.codice.ddf.security.validator.pki.PKITokenValidatorTest.java

@Before
public void setup() {
    pkiTokenValidator = new PKITokenValidator();
    pkiTokenValidator.setSignaturePropertiesPath(
            PKITokenValidatorTest.class.getResource("/signature.properties").getPath());
    pkiTokenValidator.setRealms(Arrays.asList("karaf"));
    pkiTokenValidator.init();//from www.  ja v a  2s .  co m

    try {
        KeyStore trustStore = KeyStore.getInstance(System.getProperty("javax.net.ssl.keyStoreType"));
        InputStream trustFIS = PKITokenValidatorTest.class.getResourceAsStream("/serverKeystore.jks");
        try {
            trustStore.load(trustFIS, "changeit".toCharArray());
        } catch (CertificateException e) {
            fail(e.getMessage());
        } finally {
            IOUtils.closeQuietly(trustFIS);
        }
        Certificate[] certs = trustStore.getCertificateChain("localhost");
        certificates = new X509Certificate[certs.length];
        for (int i = 0; i < certs.length; i++) {
            certificates[i] = (X509Certificate) certs[i];
        }

        trustStore = KeyStore.getInstance(System.getProperty(SecurityConstants.KEYSTORE_TYPE));
        trustFIS = PKITokenValidatorTest.class.getResourceAsStream("/badKeystore.jks");
        try {
            trustStore.load(trustFIS, "changeit".toCharArray());
        } catch (CertificateException e) {
            fail(e.getMessage());
        } finally {
            IOUtils.closeQuietly(trustFIS);
        }
        certs = trustStore.getCertificateChain("badhost");
        badCertificates = new X509Certificate[certs.length];
        for (int i = 0; i < certs.length; i++) {
            badCertificates[i] = (X509Certificate) certs[i];
        }
        merlin = new Merlin(
                PropertiesLoader.loadProperties(
                        PKITokenValidatorTest.class.getResource("/signature.properties").getPath()),
                PKITokenValidator.class.getClassLoader(), null);

        KeyStore keystore = KeyStore.getInstance(System.getProperty(SecurityConstants.KEYSTORE_TYPE));
        try (InputStream keystoreIS = PKITokenValidatorTest.class.getResourceAsStream("/test-user.jks")) {
            keystore.load(keystoreIS, "changeit".toCharArray());
        }
        Certificate cert = keystore.getCertificate("test");
        userCertificates = new X509Certificate[] { (X509Certificate) cert };

    } catch (Exception e) {
        fail(e.getMessage());
    }
}

From source file:davmail.util.ClientCertificateTest.java

public void testWindowsSmartCard() {
    try {//from  www .j av a2 s . c o  m
        KeyStore ks = KeyStore.getInstance("Windows-MY");
        ks.load(null, null);
        java.util.Enumeration en = ks.aliases();

        while (en.hasMoreElements()) {
            String aliasKey = (String) en.nextElement();
            X509Certificate c = (X509Certificate) ks.getCertificate(aliasKey);
            System.out.println("---> alias : " + aliasKey + " " + c.getSubjectDN());

            //PrivateKey key = (PrivateKey) ks.getKey(aliasKey, "Passw0rd".toCharArray());
            Certificate[] chain = ks.getCertificateChain(aliasKey);
        }

    } catch (Exception ioe) {
        System.err.println(ioe.getMessage());
    }
}

From source file:org.kuali.kra.s2s.service.impl.GrantsGovConnectorServiceImpl.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig/*from www. j a  va  2  s  .c o  m*/
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2SException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2SException {
    KeyStore keyStore = S2SCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(JKS_TYPE);
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(alias, key, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
        } else {
            keyManagerFactory.init(keyStore, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
        }
        KeyManager[] km = keyManagerFactory.getKeyManagers();
        tlsConfig.setKeyManagers(km);
        KeyStore trustStore = S2SCertificateReader.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();
        tlsConfig.setTrustManagers(tm);
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (UnrecoverableKeyException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (CertificateException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (IOException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:it.greenvulcano.gvesb.http.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/*from   w  ww. ja  va2s .  co  m*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreID != null) {
            KeyStore keystore = createKeyStore(this.keystoreID);
            if (logger.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        logger.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                logger.debug(" Certificate " + (c + 1) + ":");
                                logger.debug("  Subject DN: " + cert.getSubjectDN());
                                logger.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                logger.debug("  Valid from: " + cert.getNotBefore());
                                logger.debug("  Valid until: " + cert.getNotAfter());
                                logger.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keyPassword);
        }
        if (this.truststoreID != null) {
            KeyStore keystore = createKeyStore(this.truststoreID);
            if (logger.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    logger.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        logger.debug("  Subject DN: " + cert.getSubjectDN());
                        logger.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        logger.debug("  Valid from: " + cert.getNotBefore());
                        logger.debug("  Valid until: " + cert.getNotAfter());
                        logger.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslctx = SSLContext.getInstance("SSL");
        sslctx.init(keymanagers, trustmanagers, null);
        return sslctx;
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:org.wso2.carbon.security.util.ServerCrypto.java

@Override
/**//from  w  w  w. j  a va  2 s.c  o m
 * This first looks into the primary keystore and then looks at the other trust stores
 *
 * @see org.apache.ws.security.components.crypto.Crypto#getCertificates(String)
 */
public X509Certificate[] getCertificates(String alias) throws WSSecurityException {

    Certificate[] certs = new Certificate[0];
    Certificate cert = null;
    try {
        if (this.keystore != null) {
            // There's a chance that there can only be a set of trust stores
            certs = keystore.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a
                // result.
                cert = keystore.getCertificate(alias);
            }
        }

        if (certs == null && cert == null && this.trustStores != null) {
            // Now look into the trust stores
            Iterator trustStoreIter = this.trustStores.iterator();
            while (trustStoreIter.hasNext()) {
                KeyStore store = (KeyStore) trustStoreIter.next();
                certs = store.getCertificateChain(alias);
                if (certs != null) {
                    break; // found the certs
                } else {
                    cert = store.getCertificate(alias);
                }
            }
        }

        if (certs == null && cert == null && this.cacerts != null) {
            // There's a chance that there can only be a set of ca store
            certs = cacerts.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a
                // result.
                cert = cacerts.getCertificate(alias);
            }
        }

        if (cert != null) {
            certs = new Certificate[] { cert };
        } else if (certs == null) {

            // At this pont we don't have certs or a cert
            return new X509Certificate[0];
        }
    } catch (KeyStoreException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "keystore");
    }

    X509Certificate[] x509certs = new X509Certificate[0];
    if (certs != null) {
        x509certs = new X509Certificate[certs.length];
        for (int i = 0; i < certs.length; i++) {
            x509certs[i] = (X509Certificate) certs[i];
        }
    }
    return x509certs;
}

From source file:org.wso2.carbon.dataservices.core.auth.JWTAuthorizationProvider.java

/**
 * Get the alias for the X509 certificate thumb
 * @param thumb/*from   ww w  . j a  v a  2s  . c  om*/
 * @param keyStore
 * @return
 * @throws org.apache.axis2.AxisFault
 */
private String getAliasForX509CertThumb(byte[] thumb, KeyStore keyStore) throws AxisFault {
    Certificate cert = null;
    MessageDigest sha = null;

    try {
        sha = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e1) {
        log.error("noSHA1availabe");
        throw new AxisFault("noSHA1availabe");
    }
    try {
        for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) {
            String alias = (String) e.nextElement();
            Certificate[] certs = keyStore.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = keyStore.getCertificate(alias);
                if (cert == null) {
                    return null;
                }
            } else {
                cert = certs[0];
            }
            if (!(cert instanceof X509Certificate)) {
                continue;
            }
            sha.reset();
            try {
                sha.update(cert.getEncoded());
            } catch (CertificateEncodingException e1) {
                log.error("Error encoding certificate");
                throw new AxisFault("Error encoding certificate");
            }
            byte[] data = sha.digest();
            if (new String(thumb).equals(hexify(data))) {
                return alias;
            }
        }
    } catch (KeyStoreException e) {
        log.error("KeyStore exception while getting alias for X509CertThumb");
        throw new AxisFault("KeyStore exception while getting alias for X509CertThumb");
    }
    return null;
}

From source file:edu.vt.middleware.crypt.KeyStoreCli.java

/**
 * Lists keystore contents on STDOUT. Output is similar to keytool -list -v.
 *
 * @param  line  Parsed command line arguments container.
 *
 * @throws  Exception  On errors./*from   www .j ava  2  s . co  m*/
 */
protected void list(final CommandLine line) throws Exception {
    validateOptions(line);

    final KeyStore store = readKeyStore(line);
    final Enumeration<String> aliases = store.aliases();
    System.out.println("");
    while (aliases.hasMoreElements()) {
        final String alias = aliases.nextElement();
        System.out.println("Alias name: " + alias);
        System.out.println("Creation date: " + store.getCreationDate(alias));
        if (store.isKeyEntry(alias)) {
            System.out.println("Entry type: keyEntry");

            final Certificate[] chain = store.getCertificateChain(alias);
            System.out.println("Certificate chain length: " + chain.length);
            for (int i = 0; i < chain.length; i++) {
                System.out.println("===== Certificate [" + i + "] =====");
                printCertificate(chain[i]);
            }
        } else {
            System.out.println("Entry type: trustedCertEntry");
            System.out.println("Certificate details:");
            printCertificate(store.getCertificate(alias));
        }
        System.out.println("");
        System.out.println("");
    }
}