Example usage for javax.net.ssl KeyManagerFactory getInstance

List of usage examples for javax.net.ssl KeyManagerFactory getInstance

Introduction

In this page you can find the example usage for javax.net.ssl KeyManagerFactory getInstance.

Prototype

public static final KeyManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyManagerFactory object that acts as a factory for key managers.

Usage

From source file:com.amalto.workbench.utils.SSLContextProvider.java

private static KeyManager[] buildKeyManagers(String path, String storePass, String keytype)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        UnrecoverableKeyException {
    InputStream stream = null;//from   w  w  w. j a  va 2s.c o m
    try {
        if (StringUtils.isEmpty(path)) {
            return null;
        }
        if (!new File(path).exists()) {
            throw new KeyStoreException(Messages.bind(Messages.noKeystoreFile_error, path));
        }
        stream = new FileInputStream(path);

        KeyStore tks = KeyStore.getInstance(keytype);
        tks.load(stream, storePass.toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); //$NON-NLS-1$
        kmf.init(tks, storePass.toCharArray());

        return kmf.getKeyManagers();
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:test.integ.be.fedict.trust.SSLTrustValidatorTest.java

@Test
public void testTestEIDBelgiumBe() throws Exception {
    Security.addProvider(new BeIDProvider());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("BeID");

    keyManagerFactory.init(null);/*from w w  w .j av a 2 s.  c  o m*/
    SecureRandom secureRandom = new SecureRandom();
    sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { new ClientTestX509TrustManager() },
            secureRandom);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket("test.eid.belgium.be", 443);
    LOG.debug("socket created");
    SSLSession sslSession = sslSocket.getSession();
    Certificate[] peerCertificates = sslSession.getPeerCertificates();
    for (Certificate peerCertificate : peerCertificates) {
        LOG.debug("peer certificate: " + ((X509Certificate) peerCertificate).getSubjectX500Principal());
    }

    MemoryCertificateRepository repository = new MemoryCertificateRepository();
    repository.addTrustPoint((X509Certificate) peerCertificates[peerCertificates.length - 1]);

    TrustValidator trustValidator = new TrustValidator(repository);
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator();
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator);
    trustValidator.isTrusted(peerCertificates);
}

From source file:org.pepstock.jem.node.security.keystore.KeyStoreUtil.java

/**
 * Returns a SSL socket factory creating asymmetric keys at runtime.
 * /*from w w  w. j a  v  a  2s.c o m*/
 * @return a SSL socket factory for HTTPS listener 
 * @throws KeyStoreException if any errors occurs to get keys
 */
public static SSLServerSocketFactory getSSLServerSocketFactory() throws KeyStoreException {
    try {
        // gets a key stores created at runtime
        ByteArrayInputStream baos = SelfSignedCertificate.getCertificate();
        KeyStore keystore = KeyStore.getInstance("jks");
        // loads the keystore
        keystore.load(baos, SelfSignedCertificate.CERTIFICATE_PASSWORD.toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        // initialiazes the key manager
        kmfactory.init(keystore, SelfSignedCertificate.CERTIFICATE_PASSWORD.toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        // creates SSL socket factory
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        return sslcontext.getServerSocketFactory();
    } catch (UnrecoverableKeyException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (KeyManagementException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (CertificateException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (SecurityException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (IOException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (OperatorCreationException e) {
        throw new KeyStoreException(e.getMessage(), e);
    }
}

From source file:org.eclipse.mylyn.internal.commons.http.PollingSslProtocolSocketFactory.java

public PollingSslProtocolSocketFactory() {
    KeyManager[] keymanagers = null;
    if (System.getProperty(KEY_STORE) != null && System.getProperty(KEY_STORE_PASSWORD) != null) {
        try {//from  ww  w  . j a va  2s . co m
            String type = System.getProperty(KEY_STORE_TYPE, KeyStore.getDefaultType());
            KeyStore keyStore = KeyStore.getInstance(type);
            char[] password = System.getProperty(KEY_STORE_PASSWORD).toCharArray();
            keyStore.load(new FileInputStream(System.getProperty(KEY_STORE)), password);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, password);
            keymanagers = keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            CommonsHttpPlugin.log(IStatus.ERROR, "Could not initialize keystore", e); //$NON-NLS-1$
        }
    }

    hasKeyManager = keymanagers != null;

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL"); //$NON-NLS-1$
        sslContext.init(keymanagers, new TrustManager[] { new TrustAllTrustManager() }, null);
        this.socketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        CommonsHttpPlugin.log(IStatus.ERROR, "Could not initialize SSL context", e); //$NON-NLS-1$
    }
}

From source file:de.betterform.connector.http.ssl.BetterFORMKeyStoreManager.java

private X509KeyManager getCustomX509KeyManager(final URL url, final String password)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException,
        UnrecoverableKeyException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    if (url == null) {
        throw new IllegalArgumentException("BetterFORMKeyStoreManager: Keystore url may not be null");
    }/*from  ww  w .j  a  v a 2  s .c o m*/

    LOGGER.debug("BetterFORMKeyStoreManager: initializing custom key store");
    KeyStore customKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = null;
    try {
        is = url.openStream();
        customKeystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }

    if (LOGGER.isTraceEnabled()) {
        Enumeration aliases = customKeystore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            LOGGER.trace("Trusted certificate '" + alias + "':");
            Certificate trustedcert = customKeystore.getCertificate(alias);
            if (trustedcert != null && trustedcert instanceof X509Certificate) {
                X509Certificate cert = (X509Certificate) trustedcert;
                LOGGER.trace("  Subject DN: " + cert.getSubjectDN());
                LOGGER.trace("  Signature Algorithm: " + cert.getSigAlgName());
                LOGGER.trace("  Valid from: " + cert.getNotBefore());
                LOGGER.trace("  Valid until: " + cert.getNotAfter());
                LOGGER.trace("  Issuer: " + cert.getIssuerDN());
            }
        }
    }
    keyManagerFactory.init(customKeystore, password.toCharArray());

    KeyManager[] customX509KeyManagers = keyManagerFactory.getKeyManagers();
    if (customX509KeyManagers != null && customX509KeyManagers.length > 0) {
        for (int i = 0; i < customX509KeyManagers.length; i++) {
            if (customX509KeyManagers[i] instanceof X509KeyManager) {
                return (X509KeyManager) customX509KeyManagers[i];
            }
        }
    }

    return null;
}

From source file:org.jboss.as.test.syslogserver.TLSSyslogServer.java

/**
 * Creates custom sslContext from keystore and truststore configured in
 *
 * @see org.productivity.java.syslog4j.server.impl.net.tcp.TCPNetSyslogServer#initialize()
 *//*from www .j a v a 2  s .  c  o  m*/
@Override
public void initialize() throws SyslogRuntimeException {
    super.initialize();

    final SSLTCPNetSyslogServerConfigIF config = (SSLTCPNetSyslogServerConfigIF) this.tcpNetSyslogServerConfig;

    try {
        final char[] keystorePwd = config.getKeyStorePassword().toCharArray();
        final KeyStore keystore = loadKeyStore(config.getKeyStore(), keystorePwd);
        final char[] truststorePassword = config.getTrustStorePassword().toCharArray();
        final KeyStore truststore = loadKeyStore(config.getTrustStore(), truststorePassword);

        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, keystorePwd);

        final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(truststore);

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    } catch (Exception e) {
        LOGGER.error("Exception occurred during SSLContext for TLS syslog server initialization", e);
        throw new SyslogRuntimeException(e);
    }
}

From source file:org.hyperic.util.security.DefaultSSLProviderImpl.java

private KeyManagerFactory getKeyManagerFactory(final KeyStore keystore, final String password)
        throws KeyStoreException {
    try {//from w w  w.  ja  va2s  .com
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, password.toCharArray());
        return keyManagerFactory;
    } catch (NoSuchAlgorithmException e) {
        // no support for algorithm, if this happens we're kind of screwed
        // we're using the default so it should never happen
        throw new KeyStoreException("The algorithm is not supported: " + e, e);
    } catch (UnrecoverableKeyException e) {
        // invalid password, should never happen
        throw new KeyStoreException("Password for the keystore is invalid: " + e, e);
    }
}

From source file:net.di2e.ecdr.source.rest.TLSUtil.java

public static void setTLSOptions(WebClient client, boolean disableCNCheck) {
    ClientConfiguration clientConfiguration = WebClient.getConfig(client);

    HTTPConduit httpConduit = clientConfiguration.getHttpConduit();

    String keyStorePath = System.getProperty(SSL_KEYSTORE_JAVA_PROPERTY);
    String keyStorePassword = System.getProperty(SSL_KEYSTORE_PASSWORD_JAVA_PROPERTY);
    if (StringUtils.isNotBlank(keyStorePath) && StringUtils.isNotBlank(keyStorePassword)) {
        try {/*from  ww  w  .  ja  va 2 s .co m*/
            TLSClientParameters tlsParams = new TLSClientParameters();
            LOGGER.debug("Setting disable of CN check on client URL {} to [{}]", client.getCurrentURI(),
                    disableCNCheck);
            tlsParams.setDisableCNCheck(disableCNCheck);

            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

            // add the keystore if it exists
            File keystore = new File(keyStorePath);
            if (keystore.exists() && keyStorePassword != null) {
                FileInputStream fis = new FileInputStream(keystore);
                try {
                    LOGGER.debug("Loading keyStore {}", keystore);
                    keyStore.load(fis, keyStorePassword.toCharArray());
                } catch (IOException e) {
                    LOGGER.error("Unable to load keystore. {}", keystore, e);
                } catch (CertificateException e) {
                    LOGGER.error("Unable to load certificates from keystore. {}", keystore, e);
                } finally {
                    IOUtils.closeQuietly(fis);
                }
                KeyManagerFactory keyFactory = KeyManagerFactory
                        .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                keyFactory.init(keyStore, keyStorePassword.toCharArray());
                KeyManager[] km = keyFactory.getKeyManagers();
                tlsParams.setKeyManagers(km);
            }

            httpConduit.setTlsClientParameters(tlsParams);
        } catch (KeyStoreException e) {
            LOGGER.error("Unable to read keystore: ", e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("Problems creating SSL socket. Usually this is "
                    + "referring to the certificate sent by the server not being trusted by the client.", e);
        } catch (FileNotFoundException e) {
            LOGGER.error("Unable to locate one of the SSL stores: {} | {}", keyStorePath, e);
        } catch (UnrecoverableKeyException e) {
            LOGGER.error("Unable to read keystore: ", e);
        }
    }
}

From source file:net.sf.ufsc.ftp.FTPSClient.java

public FTPSClient() {
    super();/*from  w w w.  j a  v a 2s .  co m*/

    try {
        KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
        keyStore.load(null, PASSWORD.toCharArray());

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());

        keyManagerFactory.init(keyStore, PASSWORD.toCharArray());

        SSLContext context = SSLContext.getInstance(PROTOCOL);
        context.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { new SimpleTrustManager() }, null);

        this.socketFactory = new SecureSocketFactory(context);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.openhealthtools.openatna.net.ConnectionCertificateHandler.java

/**
 * Creates keymanagers from a keystore./*from  w  ww.java2 s  .  c om*/
 */
public static KeyManager[] createKeyManagers(final KeyStore keystore, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }
    log.debug("Initializing key manager");
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, password != null ? password.toCharArray() : null);
    return kmfactory.getKeyManagers();
}