Search in sources :

Example 86 with KeyManagerFactory

use of javax.net.ssl.KeyManagerFactory in project ecf by eclipse.

the class XMPPConnection method proceedTLSReceived.

/**
 * The server has indicated that TLS negotiation can start. We now need to secure the
 * existing plain connection and perform a handshake. This method won't return until the
 * connection has finished the handshake or an error occured while securing the connection.
 *
 * @throws Exception if an exception occurs.
 */
void proceedTLSReceived() throws Exception {
    SSLContext context = this.config.getCustomSSLContext();
    KeyStore ks = null;
    KeyManager[] kms = null;
    PasswordCallback pcb = null;
    if (config.getCallbackHandler() == null) {
        ks = null;
    } else if (context == null) {
        // System.out.println("Keystore type: "+configuration.getKeystoreType());
        if (config.getKeystoreType().equals("NONE")) {
            ks = null;
            pcb = null;
        } else if (config.getKeystoreType().equals("PKCS11")) {
            try {
                Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class);
                String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library();
                ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes());
                Provider p = (Provider) c.newInstance(config);
                Security.addProvider(p);
                ks = KeyStore.getInstance("PKCS11", p);
                pcb = new PasswordCallback("PKCS11 Password: ", false);
                this.config.getCallbackHandler().handle(new Callback[] { pcb });
                ks.load(null, pcb.getPassword());
            } catch (Exception e) {
                ks = null;
                pcb = null;
            }
        } else if (config.getKeystoreType().equals("Apple")) {
            ks = KeyStore.getInstance("KeychainStore", "Apple");
            ks.load(null, null);
        // pcb = new PasswordCallback("Apple Keychain",false);
        // pcb.setPassword(null);
        } else {
            ks = KeyStore.getInstance(config.getKeystoreType());
            try {
                pcb = new PasswordCallback("Keystore Password: ", false);
                config.getCallbackHandler().handle(new Callback[] { pcb });
                ks.load(new FileInputStream(config.getKeystorePath()), pcb.getPassword());
            } catch (Exception e) {
                ks = null;
                pcb = null;
            }
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        try {
            if (pcb == null) {
                kmf.init(ks, null);
            } else {
                kmf.init(ks, pcb.getPassword());
                pcb.clearPassword();
            }
            kms = kmf.getKeyManagers();
        } catch (NullPointerException npe) {
            kms = null;
        }
    }
    // Verify certificate presented by the server
    if (context == null) {
        context = SSLContext.getInstance("TLS");
        context.init(kms, new javax.net.ssl.TrustManager[] { new ServerTrustManager(getServiceName(), config) }, new java.security.SecureRandom());
    }
    Socket plain = socket;
    // Secure the plain connection
    socket = context.getSocketFactory().createSocket(plain, plain.getInetAddress().getHostAddress(), plain.getPort(), true);
    socket.setSoTimeout(0);
    socket.setKeepAlive(true);
    // Initialize the reader and writer with the new secured version
    initReaderAndWriter();
    // Proceed to do the handshake
    ((SSLSocket) socket).startHandshake();
    // if (((SSLSocket) socket).getWantClientAuth()) {
    // System.err.println("Connection wants client auth");
    // }
    // else if (((SSLSocket) socket).getNeedClientAuth()) {
    // System.err.println("Connection needs client auth");
    // }
    // else {
    // System.err.println("Connection does not require client auth");
    // }
    // Set that TLS was successful
    usingTLS = true;
    // Set the new  writer to use
    packetWriter.setWriter(writer);
    // Send a new opening stream to the server
    packetWriter.openStream();
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) FileInputStream(java.io.FileInputStream) Provider(java.security.Provider) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) PasswordCallback(javax.security.auth.callback.PasswordCallback) Callback(javax.security.auth.callback.Callback) ByteArrayInputStream(java.io.ByteArrayInputStream) PasswordCallback(javax.security.auth.callback.PasswordCallback) KeyManager(javax.net.ssl.KeyManager) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket)

Example 87 with KeyManagerFactory

use of javax.net.ssl.KeyManagerFactory in project ultrasonic by ultrasonic.

the class SSLSocketFactory method createSSLContext.

private static SSLContext createSSLContext(String algorithm, final KeyStore keystore, final String keyStorePassword, final SecureRandom random, final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (algorithm == null) {
        algorithm = TLS;
    }
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keystore, keyStorePassword != null ? keyStorePassword.toCharArray() : null);
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keystore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    if (trustManagers != null && trustStrategy != null) {
        for (int i = 0; i < trustManagers.length; i++) {
            TrustManager tm = trustManagers[i];
            if (tm instanceof X509TrustManager) {
                trustManagers[i] = new TrustManagerDecorator((X509TrustManager) tm, trustStrategy);
            }
        }
    }
    SSLContext sslcontext = SSLContext.getInstance(algorithm);
    sslcontext.init(keyManagers, trustManagers, random);
    return sslcontext;
}
Also used : X509TrustManager(javax.net.ssl.X509TrustManager) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SSLContext(javax.net.ssl.SSLContext) KeyManager(javax.net.ssl.KeyManager) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 88 with KeyManagerFactory

use of javax.net.ssl.KeyManagerFactory in project nimbus by nimbus-org.

the class SSLServerSocketFactory method getKeyManagers.

protected KeyManager[] getKeyManagers() throws Exception {
    KeyManager[] keyManager = null;
    KeyStore store = getKeyStore();
    if (keyAlias != null && !store.isKeyEntry(keyAlias)) {
        throw new IOException("KeyAlias is not entried. " + keyAlias);
    }
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyStoreAlgorithm);
    keyManagerFactory.init(store, keyPassword.toCharArray());
    keyManager = keyManagerFactory.getKeyManagers();
    if (keyAlias != null) {
        if (DEFAULT_KEYSTORE_TYPE.equals(keyStoreType)) {
            keyAlias = keyAlias.toLowerCase();
        }
        for (int i = 0; i < keyManager.length; i++) {
            keyManager[i] = new X509KeyManagerWrapper((X509KeyManager) keyManager[i], keyAlias);
        }
    }
    return keyManager;
}
Also used : X509KeyManager(javax.net.ssl.X509KeyManager) IOException(java.io.IOException) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager) KeyStore(java.security.KeyStore) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 89 with KeyManagerFactory

use of javax.net.ssl.KeyManagerFactory in project i2p.i2p by i2p.

the class SSLUtil method initializeFactory.

/**
 *  Sets up the SSLContext and sets the socket factory.
 *  No option prefix allowed.
 *
 * @throws IOException GeneralSecurityExceptions are wrapped in IOE for convenience
 * @return factory, throws on all errors
 */
public static SSLServerSocketFactory initializeFactory(Properties opts) throws IOException {
    String ksPass = opts.getProperty(PROP_KEYSTORE_PASSWORD, KeyStoreUtil.DEFAULT_KEYSTORE_PASSWORD);
    String keyPass = opts.getProperty(PROP_KEY_PASSWORD);
    if (keyPass == null) {
        throw new IOException("No key password, set " + PROP_KEY_PASSWORD + " in " + (new File(I2PAppContext.getGlobalContext().getConfigDir(), DEFAULT_SAMCLIENT_CONFIGFILE)).getAbsolutePath());
    }
    String ksname = opts.getProperty(PROP_KS_NAME);
    if (ksname == null) {
        throw new IOException("No keystore, set " + PROP_KS_NAME + " in " + (new File(I2PAppContext.getGlobalContext().getConfigDir(), DEFAULT_SAMCLIENT_CONFIGFILE)).getAbsolutePath());
    }
    File ks = new File(ksname);
    if (!ks.isAbsolute()) {
        ks = new File(I2PAppContext.getGlobalContext().getConfigDir(), KS_DIR);
        ks = new File(ks, ksname);
    }
    InputStream fis = null;
    try {
        SSLContext sslc = SSLContext.getInstance("TLS");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        fis = new FileInputStream(ks);
        keyStore.load(fis, ksPass.toCharArray());
        KeyStoreUtil.logCertExpiration(keyStore, ks.getAbsolutePath(), 180 * 24 * 60 * 60 * 1000L);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, keyPass.toCharArray());
        sslc.init(kmf.getKeyManagers(), null, I2PAppContext.getGlobalContext().random());
        return sslc.getServerSocketFactory();
    } catch (GeneralSecurityException gse) {
        IOException ioe = new IOException("keystore error");
        ioe.initCause(gse);
        throw ioe;
    } finally {
        if (fis != null)
            try {
                fis.close();
            } catch (IOException ioe) {
            }
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) SSLContext(javax.net.ssl.SSLContext) File(java.io.File) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Example 90 with KeyManagerFactory

use of javax.net.ssl.KeyManagerFactory in project java-driver by datastax.

the class SSLTestBase method getSSLOptions.

/**
 * @param sslImplementation the SSL implementation to use
 * @param clientAuth        whether the client should authenticate
 * @param trustingServer    whether the client should trust the server's certificate
 * @return {@link com.datastax.driver.core.SSLOptions} with the given configuration for
 * server certificate validation and client certificate authentication.
 */
public SSLOptions getSSLOptions(SslImplementation sslImplementation, boolean clientAuth, boolean trustingServer) throws Exception {
    TrustManagerFactory tmf = null;
    if (trustingServer) {
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(this.getClass().getResourceAsStream(CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PATH), CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD.toCharArray());
        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
    }
    switch(sslImplementation) {
        case JDK:
            KeyManagerFactory kmf = null;
            if (clientAuth) {
                KeyStore ks = KeyStore.getInstance("JKS");
                ks.load(this.getClass().getResourceAsStream(CCMBridge.DEFAULT_CLIENT_KEYSTORE_PATH), CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
                kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                kmf.init(ks, CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD.toCharArray());
            }
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null, new SecureRandom());
            return RemoteEndpointAwareJdkSSLOptions.builder().withSSLContext(sslContext).build();
        case NETTY_OPENSSL:
            SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(OPENSSL).trustManager(tmf);
            if (clientAuth) {
                builder.keyManager(CCMBridge.DEFAULT_CLIENT_CERT_CHAIN_FILE, CCMBridge.DEFAULT_CLIENT_PRIVATE_KEY_FILE);
            }
            return new RemoteEndpointAwareNettySSLOptions(builder.build());
        default:
            fail("Unsupported SSL implementation: " + sslImplementation);
            return null;
    }
}
Also used : SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) KeyManagerFactory(javax.net.ssl.KeyManagerFactory)

Aggregations

KeyManagerFactory (javax.net.ssl.KeyManagerFactory)439 KeyStore (java.security.KeyStore)322 SSLContext (javax.net.ssl.SSLContext)218 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)203 FileInputStream (java.io.FileInputStream)135 IOException (java.io.IOException)122 InputStream (java.io.InputStream)106 KeyManager (javax.net.ssl.KeyManager)104 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)79 TrustManager (javax.net.ssl.TrustManager)76 KeyStoreException (java.security.KeyStoreException)62 SecureRandom (java.security.SecureRandom)58 CertificateException (java.security.cert.CertificateException)57 UnrecoverableKeyException (java.security.UnrecoverableKeyException)54 KeyManagementException (java.security.KeyManagementException)51 File (java.io.File)37 X509Certificate (java.security.cert.X509Certificate)33 GeneralSecurityException (java.security.GeneralSecurityException)31 X509TrustManager (javax.net.ssl.X509TrustManager)29 Certificate (java.security.cert.Certificate)28