Example usage for java.security KeyStoreException getMessage

List of usage examples for java.security KeyStoreException getMessage

Introduction

In this page you can find the example usage for java.security KeyStoreException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:it.danja.newsmonitor.utils.HttpServer.java

public void init() {

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();/* www.  j  a v a2  s .  c  o m*/

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpFileHandler(docRoot));

    // Set up the HTTP service
    httpService = new HttpService(httpproc, reqistry);

    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = HttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            log.info("HttpServer : Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = null;
        try {
            keystore = KeyStore.getInstance("jks");
        } catch (KeyStoreException e) {

            log.error(e.getMessage());
        }
        try {
            keystore.load(url.openStream(), "secret".toCharArray());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        } catch (CertificateException e) {

            log.error(e.getMessage());
        } catch (IOException e) {

            log.error(e.getMessage());
        }
        KeyManagerFactory kmfactory = null;
        try {
            kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        try {
            kmfactory.init(keystore, "secret".toCharArray());
        } catch (UnrecoverableKeyException e) {

            log.error(e.getMessage());
        } catch (KeyStoreException e) {

            log.error(e.getMessage());
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = null;
        try {
            sslcontext = SSLContext.getInstance("TLS");
        } catch (NoSuchAlgorithmException e) {

            log.error(e.getMessage());
        }
        try {
            sslcontext.init(keymanagers, null, null);
        } catch (KeyManagementException e) {

            log.error(e.getMessage());
        }
        this.sf = sslcontext.getServerSocketFactory();
    }
}

From source file:it.txt.access.capability.demo.soap.server.service.impl.CapabilityServiceHelper.java

@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
    try {/*from   w w w  .j  a  va 2 s .  c o m*/
        KeyStore keyStore = null;
        RESOURCE_LOADER = resourceLoader;
        String schemas = RESOURCE_LOADER.getResource("Capability_Schemas").getFile().getPath();
        CapabilitySchemaFactory.initCapabilityCreator(schemas);
        LOGGER.log(Level.INFO, "Capability Creator Initialized successfully.");
        File keystore = RESOURCE_LOADER.getResource("keystore/capability_keystore.jks").getFile();
        LOGGER.log(Level.INFO, "Set Resource Loader: {0}", keystore.getPath());
        KEYSTORE_DATA.setKeystorePath(keystore.getPath());
        KEYSTORE_DATA.setServerID("demoserver01@acme.com");
        KEYSTORE_DATA.setKeystorePsw("sysmgr".toCharArray());
        KEYSTORE_DATA.setPrivateKeyPsw("sysmgr".toCharArray());
        java.security.cert.X509Certificate x509Certificate = null;
        try {
            //Recover the Keystore.
            keyStore = KeystoreHelper.getKeyStore(KEYSTORE_DATA.getKeystorePath(),
                    KEYSTORE_DATA.getKeystorePsw());
            //Recover the certificate from the Keystore
            x509Certificate = KeystoreHelper.getX509CertificateByIssuer(keyStore, KEYSTORE_DATA.getServerID());
            //Check if we have found a certificate with the provided issuer.
            if (x509Certificate != null) {
                try {
                    //Recover the alias of the certificate
                    String SERVER_ALIAS = KeystoreHelper.getAlias(keyStore, x509Certificate);
                    //Recover the private key of the.
                    KEYSTORE_SIGN = new KeystoreSignature();
                    //Recover the server certificate key values
                    CERTIFICATE_KEY_VALUES = KEYSTORE_SIGN.getCertificateKeyValues(
                            KEYSTORE_DATA.getKeystorePath(), KEYSTORE_DATA.getPrivateKeyPsw(), SERVER_ALIAS,
                            KEYSTORE_DATA.getPrivateKeyPsw());
                } catch (KeyStoreException ex) {
                    LOGGER.log(Level.SEVERE, "Cannot recover the alias of the certificate: {0}",
                            ex.getMessage());
                } catch (KeystoreSecurityException ex) {
                    LOGGER.log(Level.SEVERE, "Error while recovering certificate private key: {0}",
                            ex.getMessage());
                }
            } else {
                LOGGER.log(Level.SEVERE, "Cannot find a certificate by using.");
            }
        } catch (KeystoreSecurityException ex) {
            LOGGER.log(Level.SEVERE, ex.getMessage());
        } catch (GeneralSecurityException ex) {
            LOGGER.log(Level.SEVERE, "Error while searching for certificate into keystore: {0}",
                    ex.getMessage());
        }
    } catch (CapabilitySchemaFactoryException ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, ex.getMessage(), ex);
    }
}

From source file:eu.europa.ec.markt.tlmanager.core.signature.SignatureManager.java

/**
 * Retrieves the certificate from the respective source.
 * /*from   ww w  . j a  v  a 2  s  .  c o m*/
 * @throws SignatureException
 */
public void retrieveCertificates() throws SignatureException {
    if (provider == null) {
        return;
    }
    if (signatureTokenConnection == null || !provider.equals(lastProvider)) { // provider was changed in ui
        initializeTokenCon(provider);
    }
    try {
        keys = signatureTokenConnection.getKeys();
    } catch (KeyStoreException kse) {
        signatureTokenConnection = null; // make sure that it is reinitialised next time!
        String msg = kse.getMessage();
        LOG.log(Level.SEVERE, ">>>Unable to get Keys: " + msg);
        throw new SignatureException(msg, kse);
    }
}

From source file:org.codice.ddf.admin.insecure.defaults.service.KeystoreValidator.java

private KeyStore loadKeystore() {
    KeyStore keystore = null;/*from   w w  w.  ja v a2s.  c om*/

    try {
        keystore = KeyStore.getInstance(System.getProperty(SecurityConstants.KEYSTORE_TYPE));
    } catch (KeyStoreException e) {
        LOGGER.warn(String.format(GENERIC_INSECURE_DEFAULTS_MSG, keystorePath.toString()), e);
        alerts.add(new Alert(Level.WARN,
                String.format(GENERIC_INSECURE_DEFAULTS_MSG, keystorePath) + e.getMessage() + "."));
        return null;
    }

    if (!new File(keystorePath.toString()).canRead()) {
        alerts.add(new Alert(Level.WARN, String.format(KEYSTORE_DOES_NOT_EXIST_MSG, keystorePath)));
        return null;
    }

    try (FileInputStream fis = new FileInputStream(keystorePath.toString())) {

        if (StringUtils.isNotBlank(keystorePassword)) {
            keystore.load(fis, keystorePassword.toCharArray());

            if (StringUtils.equals(keystorePassword, defaultKeystorePassword)) {
                alerts.add(new Alert(Level.WARN, String.format(DEFAULT_KEYSTORE_PASSWORD_USED_MSG,
                        keystorePath.toString(), defaultKeystorePassword)));
            }
        }
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        keystore = null;
        LOGGER.warn(String.format(GENERIC_INSECURE_DEFAULTS_MSG, keystorePath), e);
        alerts.add(new Alert(Level.WARN,
                String.format(GENERIC_INSECURE_DEFAULTS_MSG, keystorePath) + e.getMessage() + "."));
    }

    return keystore;
}

From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java

private SchemeSocketFactory getSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContextBuilder builder = SSLContexts.custom().useTLS();
    try {/* w  w w .  j a  va 2s.  com*/
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    } catch (KeyStoreException e) {
        log.error("Unable to set SSL trust manager: {}", e.getMessage(), e);
    }

    if (keyStore != null) {
        try {
            builder.loadKeyMaterial(keyStore, credentials.getPassword().toCharArray(),
                    new PrivateKeyStrategy() {
                        @Override
                        public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                            return credentials.getUserPrincipal().getName();
                        }
                    });
        } catch (KeyStoreException | UnrecoverableKeyException e) {
            log.error("Unable to set SSL key manager: {}", e.getMessage(), e);
        }
    }

    return new SSLSocketFactory(builder.build(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}

From source file:com.rockagen.commons.http.HttpConn.java

/**
 * Handler main//from   w  ww . ja  v  a 2 s  . c  o  m
 *
 * @param targetHost target {@link HttpHost}
 * @param proxyHost proxy {@link HttpHost}
 * @param httpRequestMethod HttpGet or HttpPost...
 * @param encoding encoding
 * @param upc {@link UsernamePasswordCredentials}
 * @param keystore keystore stream
 * @param password keystore password
 * @return result String
 * @throws IOException  if an I/O error occurs
 */
protected static String execute(HttpHost targetHost, HttpHost proxyHost, HttpRequest httpRequestMethod,
        String encoding, UsernamePasswordCredentials upc, InputStream keystore, char[] password)
        throws IOException {

    HttpClientBuilder hcb = HttpClients.custom();
    hcb.setDefaultRequestConfig(getRequestConfig());
    if (proxyHost != null) {
        hcb.setProxy(proxyHost);
    }
    if (keystore != null) {

        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(keystore, password);
            SSLContext sslcontext = SSLContexts.custom()
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslcontext);
            hcb.setSSLSocketFactory(ssf);
        } catch (KeyStoreException e) {
            log.error("{}", e.getMessage(), e);
        } catch (CertificateException e) {
            log.error("{}", e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            log.error("{}", e.getMessage(), e);
        } catch (KeyManagementException e) {
            log.error("{}", e.getMessage(), e);
        } finally {
            keystore.close();
        }

    }

    if (upc != null) {
        CredentialsProvider cp = new BasicCredentialsProvider();

        AuthScope as = new AuthScope(targetHost);

        cp.setCredentials(as, upc);
        hcb.setDefaultCredentialsProvider(cp);
    }

    CloseableHttpClient chc = hcb.build();
    try {
        CloseableHttpResponse response = chc.execute(targetHost, httpRequestMethod);
        return getResponse(response, encoding);
    } finally {
        chc.close();
    }

}

From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java

@Override
public KeyStore getKeyStore(InputStream keystoreIS, String password) throws CertException {
    KeyStore ks;//from www. ja va 2 s .c  o m
    try {
        ks = java.security.KeyStore.getInstance(KEYSTORE_TYPE);
        ks.load(keystoreIS, password.toCharArray());
    } catch (KeyStoreException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    } catch (CertificateException e) {
        throw new CertException(e);
    } catch (IOException e) {
        if (String.valueOf(e.getMessage()).contains("password was incorrect")) {
            // "Keystore was tampered with, or password was incorrect"
            // is not very useful to end-users
            throw new CertException("Incorrect password");
        }
        throw new CertException(e);
    }
    return ks;
}

From source file:com.vmware.identity.idm.server.clientcert.IdmClientCertificateValidator.java

/**
 *
 * @return keyStore representing that containing the trust CA certificates of the tenant
 * @throws InvalidArgumentException/* w  w w . ja  va2  s .co m*/
 */
private KeyStore getTrustedClientCaStore() throws InvalidArgumentException {
    KeyStore trustedClientCaStore;

    if (certPolicy == null || certPolicy.getTrustedCAs() == null) {
        throw new InvalidArgumentException("Null client certificate policy or trust ca certficagtes.");
    }
    try {
        trustedClientCaStore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e1) {
        throw new InvalidArgumentException("Failed in creating a keyStore instance: ", e1);
    }
    try {
        trustedClientCaStore.load(null, null);
    } catch (NoSuchAlgorithmException | CertificateException | IOException e1) {
        throw new InvalidArgumentException("Failed in initializing a keyStore instance: " + e1.getMessage(),
                e1);
    }
    for (Certificate trustCa : certPolicy.getTrustedCAs()) {
        X509Certificate x509Cert = (X509Certificate) trustCa;
        try {
            trustedClientCaStore.setCertificateEntry(x509Cert.getSubjectX500Principal().getName(), trustCa);
        } catch (KeyStoreException e) {
            throw new InvalidArgumentException("Failed in storing a ca cert to keyStore: " + e.getMessage(), e);
        }
    }
    return trustedClientCaStore;
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#applyCertificateRequest(String, File, File, String)
 *///from w  ww  .  ja  va  2s  .com
public synchronized boolean applyCertificateRequest(final String commonName, final File certificateFile,
        final File keystoreFile, final String storePassword) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#applyCertificateRequest(final String commonName, final File certificateFile, final File keystoreFile, final String storePassword) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", commonName);
        DEBUGGER.debug("Value: {}", certificateFile);
        DEBUGGER.debug("Value: {}", keystoreFile);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final File certificateDirectory = FileUtils
            .getFile(certConfig.getCertificateDirectory() + "/" + commonName);
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + commonName);

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("certificateDirectory: {}", certificateDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("certificateFile: {}", certificateFile);
        DEBUGGER.debug("keystoreFile: {}", keystoreFile);
    }

    boolean isComplete = false;
    FileInputStream certStream = null;
    FileOutputStream storeStream = null;
    FileInputStream keystoreInput = null;
    FileInputStream rootCertStream = null;
    FileInputStream intermediateCertStream = null;

    try {
        if (!(rootDirectory.exists())) {
            throw new CertificateManagementException(
                    "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(rootDirectory.canWrite())) {
            throw new CertificateManagementException(
                    "Root certificate directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(certConfig.getRootCertificateFile().exists())) {
            throw new CertificateManagementException("Root certificate file does not exist. Cannot continue.");
        }

        if (!(certConfig.getIntermediateCertificateFile().exists())) {
            throw new CertificateManagementException(
                    "Intermediate certificate file does not exist. Cannot continue.");
        }

        if (!(storeDirectory.canWrite())) {
            throw new CertificateManagementException(
                    "Keystore directory either does not exist or cannot be written to. Cannot continue.");
        }

        if (!(keystoreFile.canWrite())) {
            throw new CertificateManagementException(
                    "Unable to write to applicable keystore. Cannot continue.");
        }

        keystoreInput = FileUtils.openInputStream(keystoreFile);
        certStream = FileUtils.openInputStream(certificateFile);

        if (DEBUG) {
            DEBUGGER.debug("keystoreInput: {}", keystoreInput);
            DEBUGGER.debug("certStream: {}", certStream);
        }

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(keystoreInput, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        Key privateKey = keyStore.getKey(commonName, storePassword.toCharArray());
        CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

        if (DEBUG) {
            DEBUGGER.debug("CertificateFactory: {}", certFactory);
        }

        rootCertStream = FileUtils.openInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()));
        intermediateCertStream = FileUtils
                .openInputStream(FileUtils.getFile(certConfig.getIntermediateCertificateFile()));

        if (DEBUG) {
            DEBUGGER.debug("rootCertStream: {}", rootCertStream);
            DEBUGGER.debug("intermediateCertStream: {}", intermediateCertStream);
        }

        X509Certificate[] responseCert = new X509Certificate[] {
                (X509Certificate) certFactory.generateCertificate(rootCertStream),
                (X509Certificate) certFactory.generateCertificate(intermediateCertStream),
                (X509Certificate) certFactory.generateCertificate(certStream) };

        if (DEBUG) {
            DEBUGGER.debug("X509Certificate[]", (Object) responseCert);
        }

        storeStream = FileUtils.openOutputStream(keystoreFile);
        keyStore.setKeyEntry(commonName, privateKey, storePassword.toCharArray(), responseCert);
        keyStore.store(storeStream, storePassword.toCharArray());

        isComplete = true;
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } catch (UnrecoverableKeyException ukx) {
        throw new CertificateManagementException(ukx.getMessage(), ukx);
    } finally {
        if (storeStream != null) {
            IOUtils.closeQuietly(storeStream);
        }

        if (intermediateCertStream != null) {
            IOUtils.closeQuietly(intermediateCertStream);
        }

        if (rootCertStream != null) {
            IOUtils.closeQuietly(rootCertStream);
        }

        if (certStream != null) {
            IOUtils.closeQuietly(certStream);
        }

        if (keystoreInput != null) {
            IOUtils.closeQuietly(keystoreInput);
        }
    }

    return isComplete;
}