Java Code Examples for javax.net.ssl.KeyManagerFactory

The following are top voted examples for showing how to use javax.net.ssl.KeyManagerFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: iotgateway   File: CertPemClientCredentials.java   Source Code and License 11 votes vote down vote up
private SSLSocketFactory getSocketFactory() {
  try {
    Security.addProvider(new BouncyCastleProvider());

    TrustManagerFactory trustManagerFactory = createAndInitTrustManagerFactory();
    KeyManagerFactory keyManagerFactory = createAndInitKeyManagerFactory();

    SSLContext context = SSLContext.getInstance(TLS_VERSION);
    context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    return context.getSocketFactory();
  } catch (Exception e) {
    log.error("[{}:{}:{}:{}] Creating TLS factory failed!", caCert, cert, privateKey, password, e);
    throw new RuntimeException("Creating TLS factory failed!", e);
  }
}
 
Example 2
Project: push-network-proxies   File: SSLHelper.java   Source Code and License 10 votes vote down vote up
public static SSLContext newSSLContext(final KeyStore ks, final String password,
    final String ksAlgorithm) throws InvalidSSLConfig {
    try {
        // Get a KeyManager and initialize it
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(ksAlgorithm);
        kmf.init(ks, password.toCharArray());

        // Get a TrustManagerFactory with the DEFAULT KEYSTORE, so we have all the certificates in cacerts trusted
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance(ksAlgorithm);
        tmf.init((KeyStore) null);

        // Get the SSLContext to help create SSLSocketFactory
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        return sslContext;
    } catch (final GeneralSecurityException e) {
        throw new InvalidSSLConfig(e);
    }
}
 
Example 3
Project: q-mail   File: MockSmtpServer.java   Source Code and License 7 votes vote down vote up
private void upgradeToTls(Socket socket) throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException {

    KeyStore keyStore = keyStoreProvider.getKeyStore();

    String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(defaultAlgorithm);
    keyManagerFactory.init(keyStore, keyStoreProvider.getPassword());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
            socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
    sslSocket.setUseClientMode(false);
    sslSocket.startHandshake();

    input = Okio.buffer(Okio.source(sslSocket.getInputStream()));
    output = Okio.buffer(Okio.sink(sslSocket.getOutputStream()));
}
 
Example 4
Project: iBase4J-Common   File: HTTPSCoder.java   Source Code and License 7 votes vote down vote up
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 实例化密钥库
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 获得密钥库
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密钥工厂
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 实例化信任库
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 获得信任库
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任库
	trustManagerFactory.init(trustStore);
	// 实例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 获得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
Example 5
Project: message-broker   File: SslHandlerFactory.java   Source Code and License 7 votes vote down vote up
public SslHandlerFactory(AmqpServerConfiguration configuration) throws KeyStoreException, IOException,
        CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    KeyStore keyStore = getKeyStore(configuration.getSsl().getKeyStore().getType(),
                                    configuration.getSsl().getKeyStore().getLocation(),
                                    configuration.getSsl().getKeyStore().getPassword());
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(configuration.getSsl()
                                                                                     .getKeyStore()
                                                                                     .getCertType());
    keyManagerFactory.init(keyStore, configuration.getSsl().getKeyStore().getPassword().toCharArray());

    KeyStore trustStore = getKeyStore(configuration.getSsl().getTrustStore().getType(),
                                      configuration.getSsl().getTrustStore().getLocation(),
                                      configuration.getSsl().getTrustStore().getPassword());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(configuration.getSsl()
                                                                           .getTrustStore()
                                                                           .getCertType());
    trustManagerFactory.init(trustStore);

    sslContext = SSLContext.getInstance(configuration.getSsl().getProtocol());
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
}
 
Example 6
Project: MQTT-Essentials-A-Lightweight-IoT-Protocol   File: SecurityHelper.java   Source Code and License 7 votes vote down vote up
private static KeyManagerFactory createKeyManagerFactory(
	final String clientCertificateFileName, final String clientKeyFileName, final String clientKeyPassword) 
	throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException
{
	// Creates a key manager factory
	// Load and create the client certificate
	final X509Certificate clientCertificate = createX509CertificateFromFile(clientCertificateFileName);	
	// Load the private client key
	final PrivateKey privateKey = createPrivateKeyFromPemFile(clientKeyFileName);
	// Client key and certificate are sent to server
	final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
	keyStore.load(null, null);
	keyStore.setCertificateEntry("certificate", clientCertificate);
	keyStore.setKeyEntry("private-key", privateKey, 
		clientKeyPassword.toCharArray(),
		new Certificate[] { clientCertificate });
	final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	keyManagerFactory.init(keyStore, clientKeyPassword.toCharArray());
	
	return keyManagerFactory;
}
 
Example 7
Project: CryptoVoice   File: Main.java   Source Code and License 7 votes vote down vote up
@Override
public Pair<TrustManagerFactory, KeyManagerFactory> getTrustManagerFactory() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null);
        InputStream stream = this.getAssets().open("server.crt");
        BufferedInputStream bis = new BufferedInputStream(stream);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        while (bis.available() > 0) {
            Certificate cert = cf.generateCertificate(bis);
            trustStore.setCertificateEntry("cert" + bis.available(), cert);
        }
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(trustStore, "1234".toCharArray());
        TrustManagerFactory tmf=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        return new Pair<>(tmf, kmfactory);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 8
Project: iot-edge-greengrass   File: CertPemClientCredentials.java   Source Code and License 6 votes vote down vote up
private SSLSocketFactory getSocketFactory() {
  try {
    Security.addProvider(new BouncyCastleProvider());

    TrustManagerFactory trustManagerFactory = createAndInitTrustManagerFactory();
    KeyManagerFactory keyManagerFactory = createAndInitKeyManagerFactory();

    SSLContext context = SSLContext.getInstance(TLS_VERSION);
    context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    return context.getSocketFactory();
  } catch (Exception e) {
    log.error("[{}:{}:{}:{}] Creating TLS factory failed!", caCert, cert, privateKey, password, e);
    throw new RuntimeException("Creating TLS factory failed!", e);
  }
}
 
Example 9
Project: q-mail   File: MockImapServer.java   Source Code and License 6 votes vote down vote up
private void upgradeToTls(Socket socket) throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException {

    KeyStore keyStore = keyStoreProvider.getKeyStore();

    String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(defaultAlgorithm);
    keyManagerFactory.init(keyStore, keyStoreProvider.getPassword());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
            socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
    sslSocket.setUseClientMode(false);
    sslSocket.startHandshake();

    input = Okio.buffer(Okio.source(sslSocket.getInputStream()));
    output = Okio.buffer(Okio.sink(sslSocket.getOutputStream()));
}
 
Example 10
Project: JAVA-   File: HTTPSPKCSCoder.java   Source Code and License 6 votes vote down vote up
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 实例化密钥库
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 获得密钥库
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密钥工厂
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 实例化信任库
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 获得信任库
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任库
	trustManagerFactory.init(trustStore);
	// 实例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 获得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
Example 11
Project: thingsboard-gateway   File: CertPemClientCredentials.java   Source Code and License 6 votes vote down vote up
private SSLSocketFactory getSocketFactory() {
    try {
        Security.addProvider(new BouncyCastleProvider());

        TrustManagerFactory trustManagerFactory = createAndInitTrustManagerFactory();
        KeyManagerFactory keyManagerFactory = createAndInitKeyManagerFactory();

        SSLContext context = SSLContext.getInstance(TLS_VERSION);
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        return context.getSocketFactory();
    } catch (Exception e) {
        log.error("[{}:{}:{}:{}] Creating TLS factory failed!", caCert, cert, privateKey, password, e);
        throw new RuntimeException("Creating TLS factory failed!", e);
    }
}
 
Example 12
Project: incubator-servicecomb-java-chassis   File: KeyStoreUtil.java   Source Code and License 6 votes vote down vote up
public static KeyManager[] createKeyManagers(final KeyStore keystore,
    char[] keyvalue) {
  try {
    KeyManagerFactory kmfactory =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, keyvalue);
    return kmfactory.getKeyManagers();
  } catch (Exception e) {
    throw new IllegalArgumentException("Bad key store."
        + e.getMessage());
  }
}
 
Example 13
Project: VBrowser-Android   File: NanoHTTPD.java   Source Code and License 6 votes vote down vote up
/**
 * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
 * certificate and passphrase
 */
public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException {
    try {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath);

        if (keystoreStream == null) {
            throw new IOException("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath);
        }

        keystore.load(keystoreStream, passphrase);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, passphrase);
        return makeSSLSocketFactory(keystore, keyManagerFactory);
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 14
Project: mobile-store   File: LocalRepoKeyStore.java   Source Code and License 6 votes vote down vote up
private void addToStore(String alias, KeyPair kp, Certificate cert) throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException {
    Certificate[] chain = {
        cert,
    };
    keyStore.setKeyEntry(alias, kp.getPrivate(),
            "".toCharArray(), chain);

    keyStore.store(new FileOutputStream(keyStoreFile), "".toCharArray());

    /*
     * After adding an entry to the keystore we need to create a fresh
     * KeyManager by reinitializing the KeyManagerFactory with the new key
     * store content and then rewrapping the default KeyManager with our own
     */
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    keyManagerFactory.init(keyStore, "".toCharArray());
    KeyManager defaultKeyManager = keyManagerFactory.getKeyManagers()[0];
    KeyManager wrappedKeyManager = new KerplappKeyManager((X509KeyManager) defaultKeyManager);
    keyManagers = new KeyManager[] {
        wrappedKeyManager,
    };
}
 
Example 15
Project: iBase4J-Common   File: HTTPSPKCSCoder.java   Source Code and License 6 votes vote down vote up
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 实例化密钥库
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 获得密钥库
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密钥工厂
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 实例化信任库
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 获得信任库
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任库
	trustManagerFactory.init(trustStore);
	// 实例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 获得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
Example 16
Project: drift   File: ApacheThriftMethodInvokerFactory.java   Source Code and License 6 votes vote down vote up
private static SSLContext createSslContext(ApacheThriftClientConfig config)
{
    try {
        KeyStore trustStore = loadTrustStore(config.getTrustCertificate());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        KeyManager[] keyManagers = null;
        if (config.getKey() != null) {
            Optional<String> keyPassword = Optional.ofNullable(config.getKeyPassword());
            KeyStore keyStore = loadKeyStore(config.getTrustCertificate(), config.getKey(), keyPassword);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, new char[0]);
            keyManagers = keyManagerFactory.getKeyManagers();
        }

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
        return sslContext;
    }
    catch (IOException | GeneralSecurityException e) {
        throw new IllegalArgumentException("Unable to load SSL keys", e);
    }
}
 
Example 17
Project: rxjava2_retrofit2   File: CustomHttpsTrust.java   Source Code and License 6 votes vote down vote up
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {

        if (bksFile == null || password == null) {
            return null;
        }

        KeyStore clientKeyStore;
        try {
            clientKeyStore = KeyStore.getInstance("BKS");
            clientKeyStore.load(bksFile, password.toCharArray());
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(clientKeyStore, password.toCharArray());
            return keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
Example 18
Project: RoughWorld   File: WebInterfaceSSL.java   Source Code and License 6 votes vote down vote up
/**
     * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
     * certificate and passphrase
     */
    public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase)
    {
        try {
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            File keystrorefile = new File(keyAndTrustStoreClasspathPath);
            System.out.println(keystrorefile.getAbsolutePath());
            InputStream keystoreStream = new FileInputStream(keystrorefile);//NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath);

//            if (keystoreStream == null) 
//            {
//            	System.out.println("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath);
//                //throw new IOException("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath);
//            	return null;
//            }

            keystore.load(keystoreStream, passphrase);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keystore, passphrase);
            return makeSSLSocketFactory(keystore, keyManagerFactory);
        } catch (Exception e) {
        	System.out.println(e.toString());
            //throw new IOException(e.getMessage());
        }
        return null;
    }
 
Example 19
Project: automat   File: HTTPSPKCSCoder.java   Source Code and License 6 votes vote down vote up
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 实例化密钥库
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 获得密钥库
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密钥工厂
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 实例化信任库
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 获得信任库
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任库
	trustManagerFactory.init(trustStore);
	// 实例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 获得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
Example 20
Project: JAVA-   File: HTTPSCoder.java   Source Code and License 6 votes vote down vote up
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 实例化密钥库
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 获得密钥库
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密钥工厂
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 实例化信任库
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 获得信任库
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任库
	trustManagerFactory.init(trustStore);
	// 实例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 获得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
Example 21
Project: dropwizard-dsegraph   File: DseGraphFactory.java   Source Code and License 6 votes vote down vote up
private DseCluster.Builder withSSL(DseCluster.Builder builder) throws KeyStoreException, NoSuchAlgorithmException, IOException, CertificateException, KeyManagementException, UnrecoverableKeyException {

        // JKS Truststore
        KeyStore truststore = KeyStore.getInstance("JKS");
        truststore.load(new FileInputStream(sslTruststoreFile), sslTruststorePassword.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(truststore);

        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");

        // Keystore details means supporting client authentication
        if (null != sslKeystoreFile && sslKeystoreFile.length() > 0 && null != sslKeystorePassword && sslKeystorePassword.length() > 0) {
            KeyStore keystore = KeyStore.getInstance("JKS");
            keystore.load(new FileInputStream(sslKeystoreFile), sslKeystorePassword.toCharArray());
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keystore, sslKeystorePassword.toCharArray());

            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new java.security.SecureRandom());
        } else {
            sslContext.init(null, tmf.getTrustManagers(), new java.security.SecureRandom());
        }

        return builder.withSSL(RemoteEndpointAwareJdkSSLOptions.builder().withSSLContext(sslContext).build());
    }
 
Example 22
Project: MQTT-Essentials-A-Lightweight-IoT-Protocol   File: SecurityHelper.java   Source Code and License 6 votes vote down vote up
private static KeyManagerFactory createKeyManagerFactory(
	final String clientCertificateFileName, final String clientKeyFileName, final String clientKeyPassword) 
	throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException
{
	// Creates a key manager factory
	// Load and create the client certificate
	final X509Certificate clientCertificate = createX509CertificateFromFile(clientCertificateFileName);	
	// Load the private client key
	final PrivateKey privateKey = createPrivateKeyFromPemFile(clientKeyFileName);
	// Client key and certificate are sent to server
	final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
	keyStore.load(null, null);
	keyStore.setCertificateEntry("certificate", clientCertificate);
	keyStore.setKeyEntry("private-key", privateKey, 
		clientKeyPassword.toCharArray(),
		new Certificate[] { clientCertificate });
	final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	keyManagerFactory.init(keyStore, clientKeyPassword.toCharArray());
	
	return keyManagerFactory;
}
 
Example 23
Project: hekate   File: NettySslUtils.java   Source Code and License 6 votes vote down vote up
private static KeyManagerFactory keyManager(NetworkSslConfig cfg, ResourceService res) throws GeneralSecurityException, IOException,
    ResourceLoadingException {
    KeyManagerFactory factory;

    if (cfg.getKeyStoreAlgorithm() == null || cfg.getKeyStoreAlgorithm().isEmpty()) {
        factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    } else {
        factory = KeyManagerFactory.getInstance(cfg.getKeyStoreAlgorithm());
    }

    KeyStore store = keyStore(cfg.getKeyStorePath(), cfg.getKeyStorePassword(), cfg.getKeyStoreType(), res);

    factory.init(store, cfg.getKeyStorePassword().toCharArray());

    return factory;
}
 
Example 24
Project: flume-release-1.7.0   File: AvroSource.java   Source Code and License 6 votes vote down vote up
private SSLContext createServerSSLContext() {
  try {
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(new FileInputStream(keystore), keystorePassword.toCharArray());

    // Set up key manager factory to use our key store
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(getAlgorithm());
    kmf.init(ks, keystorePassword.toCharArray());

    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(kmf.getKeyManagers(), null, null);
    return serverContext;
  } catch (Exception e) {
    throw new Error("Failed to initialize the server-side SSLContext", e);
  }
}
 
Example 25
Project: flume-release-1.7.0   File: TestAvroSink.java   Source Code and License 6 votes vote down vote up
private SSLContext createServerSSLContext() {
  try {
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(new FileInputStream(keystore), keystorePassword.toCharArray());

    // Set up key manager factory to use our key store
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(getAlgorithm());
    kmf.init(ks, keystorePassword.toCharArray());

    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(kmf.getKeyManagers(), null, null);
    return serverContext;
  } catch (Exception e) {
    throw new Error("Failed to initialize the server-side SSLContext", e);
  }
}
 
Example 26
Project: iBase4J   File: HTTPSPKCSCoder.java   Source Code and License 6 votes vote down vote up
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 实例化密钥库
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 获得密钥库
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密钥工厂
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 实例化信任库
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 获得信任库
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任库
	trustManagerFactory.init(trustStore);
	// 实例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 获得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
Example 27
Project: iBase4J   File: HTTPSCoder.java   Source Code and License 6 votes vote down vote up
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 实例化密钥库
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 获得密钥库
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密钥工厂
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 实例化信任库
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 获得信任库
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任库
	trustManagerFactory.init(trustStore);
	// 实例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 获得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
Example 28
Project: wx-idk   File: HttpsRequestTools.java   Source Code and License 6 votes vote down vote up
/**
   * 创建Http/Https请求对象
   * @author Rocye
   * @param url 请求地址
   * @param method 请求方式:GET/POST
   * @param certPath 证书路径
   * @param certPass 证书密码
* @param useCert 是否需要证书
   * @return Https连接
   * @throws Exception 任何异常
   * @version 2017.11.14
   */
  private HttpsURLConnection createRequest(String url, String method, String certPath, String certPass, boolean useCert) throws Exception{
      URL realUrl = new URL(url);
      HttpsURLConnection connection = (HttpsURLConnection)realUrl.openConnection();

      //设置证书
if(useCert){
	KeyStore clientStore = KeyStore.getInstance("PKCS12");
	InputStream inputStream = new FileInputStream(certPath);
	clientStore.load(inputStream, certPass.toCharArray());
	KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	kmf.init(clientStore, certPass.toCharArray());
	KeyManager[] kms = kmf.getKeyManagers();
	SSLContext sslContext = SSLContext.getInstance("TLSv1");
	sslContext.init(kms, null, new SecureRandom());
	connection.setSSLSocketFactory(sslContext.getSocketFactory());
}

      // 设置通用的请求属性
      connection.setRequestProperty("Accept", "*/*");
      connection.setRequestProperty("Connection", "Keep-Alive");
      connection.setConnectTimeout(this.connectTimeout);
      connection.setReadTimeout(this.readTimeout);
      if("POST".equals(method)){
          // 发送POST请求必须设置如下两行
          connection.setDoOutput(true);
          connection.setDoInput(true);
          connection.setUseCaches(false);   // 忽略缓存
          connection.setRequestMethod("POST");
      }
      return connection;
  }
 
Example 29
Project: quorrabot   File: EventWebSocketSecureServer.java   Source Code and License 6 votes vote down vote up
public EventWebSocketSecureServer(int port, String keystorepath, String keystorepassword, InetAddress ip) {
    super(port, ip);

    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        char ksPassword[] = keystorepassword.toCharArray();
        if (!keystorepath.equals("")) {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream(new File(keystorepath)), ksPassword);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, ksPassword);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(ks);

            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        } else {
            sslContext.init(null, null, null);
        }
        this.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext));
    } catch (Exception e) {
        com.gmt2001.Console.out.println("Secure EventSocketServer failed: " + e);
        e.printStackTrace();
    }
}
 
Example 30
Project: quorrabot   File: MusicWebSocketSecureServer.java   Source Code and License 6 votes vote down vote up
public MusicWebSocketSecureServer(int port, String keystorepath, String keystorepassword, InetAddress ip) {
    super(port, ip);

    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        char ksPassword[] = keystorepassword.toCharArray();
        if (!keystorepath.equals("")) {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream(new File(keystorepath)), ksPassword);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, ksPassword);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(ks);

            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        } else {
            sslContext.init(null, null, null);
        }
        this.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext));
    } catch (Exception e) {
        com.gmt2001.Console.out.println("Secure EventSocketServer failed: " + e);
        e.printStackTrace();
    }
}
 
Example 31
Project: TrackMeIfYouCanChat   File: Registrar.java   Source Code and License 6 votes vote down vote up
public static SSLContext createSSLContext()
{
    try
    {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream("A2KeyStore.jks"), "1234567890".toCharArray());

        // Create key manager
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        keyManagerFactory.init(keyStore, "1234567890".toCharArray());
        KeyManager[] km = keyManagerFactory.getKeyManagers();

        // Create trust manager
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        trustManagerFactory.init(keyStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();

        // Initialize SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(km, tm, null);

        return sslContext;
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }

    return null;
}
 
Example 32
Project: Sense-Hub-Android-Things   File: WebService.java   Source Code and License 6 votes vote down vote up
/**
 * Creates an SSLSocketFactory for HTTPS.
 *
 * Pass a KeyStore resource with your certificate and passphrase
 */
public static void configureSSL(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException {

    try {
        // Android does not have the default jks but uses bks
        KeyStore keystore = KeyStore.getInstance("BKS");
        InputStream keystoreStream = WebService.class.getResourceAsStream(keyAndTrustStoreClasspathPath);
        keystore.load(keystoreStream, passphrase);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keystore);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, passphrase);
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        sslServerSocketFactory = sslContext.getServerSocketFactory();

    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 33
Project: iot-edge-greengrass   File: CertPemClientCredentials.java   Source Code and License 5 votes vote down vote up
private KeyManagerFactory createAndInitKeyManagerFactory() throws Exception {
  X509Certificate certHolder = certificateConverter.getCertificate((X509CertificateHolder) readPEMFile(cert));

  Object keyObject = readPEMFile(privateKey);

  char[] passwordCharArray = "".toCharArray();
  if (!StringUtils.isEmpty(password)) {
    passwordCharArray = password.toCharArray();
  }

  JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC");

  KeyPair key;
  if (keyObject instanceof PEMEncryptedKeyPair) {
    PEMDecryptorProvider provider = new JcePEMDecryptorProviderBuilder().build(passwordCharArray);
    key = keyConverter.getKeyPair(((PEMEncryptedKeyPair) keyObject).decryptKeyPair(provider));
  } else {
    key = keyConverter.getKeyPair((PEMKeyPair) keyObject);
  }

  KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
  clientKeyStore.load(null, null);
  clientKeyStore.setCertificateEntry("cert", certHolder);
  clientKeyStore.setKeyEntry("private-key", key.getPrivate(), passwordCharArray, new Certificate[] { certHolder });

  KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  keyManagerFactory.init(clientKeyStore, passwordCharArray);
  return keyManagerFactory;
}
 
Example 34
Project: TrackMeIfYouCanChat   File: Client.java   Source Code and License 5 votes vote down vote up
public static SSLContext createSSLContext()
{
    try
    {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream("A2KeyStore.jks"), "1234567890".toCharArray());

        // Create key manager
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        keyManagerFactory.init(keyStore, "1234567890".toCharArray());
        KeyManager[] km = keyManagerFactory.getKeyManagers();

        // Create trust manager
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        trustManagerFactory.init(keyStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();

        // Initialize SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(km, tm, null);

        return sslContext;
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }

    return null;
}
 
Example 35
Project: openjdk-jdk10   File: SSLEngineTestCase.java   Source Code and License 5 votes vote down vote up
/**
 * Returns SSLContext with TESTED_SECURITY_PROTOCOL protocol and
 * sets up keys.
 *
 * @return - SSLContext with a protocol specified by
 *           TESTED_SECURITY_PROTOCOL.
 */
public static SSLContext getContext() {
    try {
        java.security.Security.setProperty(
                "jdk.tls.disabledAlgorithms", "");
        java.security.Security.setProperty(
                "jdk.certpath.disabledAlgorithms", "");
        KeyStore ks = KeyStore.getInstance("JKS");
        KeyStore ts = KeyStore.getInstance("JKS");
        char[] passphrase = PASSWD.toCharArray();
        try (FileInputStream keyFileStream =
                new FileInputStream(KEY_FILE_NAME)) {
            ks.load(keyFileStream, passphrase);
        }
        try (FileInputStream trustFileStream =
                new FileInputStream(TRUST_FILE_NAME)) {
            ts.load(trustFileStream, passphrase);
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);
        TrustManagerFactory tmf =
                TrustManagerFactory.getInstance("SunX509");
        tmf.init(ts);
        SSLContext sslCtx =
                SSLContext.getInstance(TESTED_SECURITY_PROTOCOL);
        sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        return sslCtx;
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException |
            CertificateException | UnrecoverableKeyException |
            KeyManagementException ex) {
        throw new Error("Unexpected exception", ex);
    }
}
 
Example 36
Project: GitHub   File: CustomTrust.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose
 * certificates have not been signed by these certificates will fail with a {@code
 * SSLHandshakeException}.
 *
 * <p>This can be used to replace the host platform's built-in trusted certificates with a custom
 * set. This is useful in development where certificate authority-trusted certificates aren't
 * available. Or in production, to avoid reliance on third-party certificate authorities.
 *
 * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using
 * the host platform's built-in trust store.
 *
 * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>
 *
 * <p>Relying on your own trusted certificates limits your server team's ability to update their
 * TLS certificates. By installing a specific set of trusted certificates, you take on additional
 * operational complexity and limit your ability to migrate between certificate authorities. Do
 * not use custom trusted certificates in production without the blessing of your server's TLS
 * administrator.
 */
private X509TrustManager trustManagerForCertificates(InputStream in)
    throws GeneralSecurityException {
  CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
  Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
  if (certificates.isEmpty()) {
    throw new IllegalArgumentException("expected non-empty set of trusted certificates");
  }

  // Put the certificates a key store.
  char[] password = "password".toCharArray(); // Any password will work.
  KeyStore keyStore = newEmptyKeyStore(password);
  int index = 0;
  for (Certificate certificate : certificates) {
    String certificateAlias = Integer.toString(index++);
    keyStore.setCertificateEntry(certificateAlias, certificate);
  }

  // Use it to build an X509 trust manager.
  KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
      KeyManagerFactory.getDefaultAlgorithm());
  keyManagerFactory.init(keyStore, password);
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
      TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(keyStore);
  TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    throw new IllegalStateException("Unexpected default trust managers:"
        + Arrays.toString(trustManagers));
  }
  return (X509TrustManager) trustManagers[0];
}
 
Example 37
Project: GitHub   File: SslClient.java   Source Code and License 5 votes vote down vote up
public SslClient build() {
  try {
    // Put the certificate in a key store.
    char[] password = "password".toCharArray();
    KeyStore keyStore = newEmptyKeyStore(password);

    if (keyPair != null) {
      Certificate[] certificates = chainCertificates.toArray(
          new Certificate[chainCertificates.size()]);
      keyStore.setKeyEntry("private", keyPair.getPrivate(), password, certificates);
    }

    for (int i = 0; i < certificates.size(); i++) {
      keyStore.setCertificateEntry("cert_" + i, certificates.get(i));
    }

    // Wrap it up in an SSL context.
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
        KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
      throw new IllegalStateException("Unexpected default trust managers:"
          + Arrays.toString(trustManagers));
    }

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagers, new SecureRandom());

    return new SslClient(sslContext, (X509TrustManager) trustManagers[0]);
  } catch (GeneralSecurityException gse) {
    throw new AssertionError(gse);
  }
}
 
Example 38
Project: GitHub   File: HttpsUtils.java   Source Code and License 5 votes vote down vote up
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {
        if (bksFile == null || password == null) return null;
        KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        clientKeyStore.load(bksFile, password.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientKeyStore, password.toCharArray());
        return kmf.getKeyManagers();
    } catch (Exception e) {
        OkLogger.printStackTrace(e);
    }
    return null;
}
 
Example 39
Project: TPlayer   File: HttpsUtils.java   Source Code and License 5 votes vote down vote up
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {
        if (bksFile == null || password == null) {
            return null;
        }
        KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        clientKeyStore.load(bksFile, password.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientKeyStore, password.toCharArray());
        return kmf.getKeyManagers();
    } catch (Exception e) {
        OkLogger.printStackTrace(e);
    }
    return null;
}
 
Example 40
Project: VBrowser-Android   File: NanoHTTPD.java   Source Code and License 5 votes vote down vote up
/**
 * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a
 * loaded KeyManagerFactory. These objects must properly loaded/initialized
 * by the caller.
 */
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException {
    try {
        return makeSSLSocketFactory(loadedKeyStore, loadedKeyFactory.getKeyManagers());
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 41
Project: an2linuxclient   File: TlsHelper.java   Source Code and License 5 votes vote down vote up
public static SSLContext getNotificationTlsContext(Context c, Certificate serverCert){
    try {
        SSLContext tlsContext = SSLContext.getInstance(TLS_VERSIONS[0]);

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setKeyEntry("key", RsaHelper.getPrivateKey(c), "".toCharArray(),
                new Certificate[]{TlsHelper.getCertificate(c)});
        keyStore.setCertificateEntry("serverCert", serverCert);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "".toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        tlsContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);
        return tlsContext;
    } catch (Exception e){
        Log.e("TlsHelper", "getNotificationTlsContext");
        Log.e("StackTrace", Log.getStackTraceString(e));
        return null;
    }
}
 
Example 42
Project: webtrekk-android-sdk   File: NanoHTTPD.java   Source Code and License 5 votes vote down vote up
/**
 * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a
 * loaded KeyManagerFactory. These objects must properly loaded/initialized
 * by the caller.
 */
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException {
    try {
        return makeSSLSocketFactory(loadedKeyStore, loadedKeyFactory.getKeyManagers());
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 43
Project: springboot-shiro-cas-mybatis   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the trusted ssl context.
 *
 * @param trustStoreFile the trust store file
 * @param trustStorePassword the trust store password
 * @param trustStoreType the trust store type
 * @return the trusted ssl context
 */
private static SSLContext getTrustedSslContext(final File trustStoreFile, final String trustStorePassword,
                                        final String trustStoreType) {
    try {

        if (!trustStoreFile.exists() || !trustStoreFile.canRead()) {
            throw new FileNotFoundException("Truststore file cannot be located at " + trustStoreFile.getCanonicalPath());
        }

        final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
        final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();

        try (final FileInputStream casStream = new FileInputStream(trustStoreFile)) {
            casTrustStore.load(casStream, trustStorePasswordCharArray);
        }

        final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        final X509KeyManager customKeyManager = getKeyManager("PKIX", casTrustStore, trustStorePasswordCharArray);
        final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
        final X509TrustManager customTrustManager = getTrustManager("PKIX", casTrustStore);
        final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);

        final KeyManager[] keyManagers = {
                new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
        };
        final TrustManager[] trustManagers = {
                new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
        };

        final SSLContext context = SSLContexts.custom().useSSL().build();
        context.init(keyManagers, trustManagers, null);
        return context;

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
 
Example 44
Project: ultrasonic   File: SSLSocketFactory.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 45
Project: cas-5.1.0   File: FileTrustStoreSslSocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the trusted ssl context.
 *
 * @param trustStoreFile     the trust store file
 * @param trustStorePassword the trust store password
 * @param trustStoreType     the trust store type
 * @return the trusted ssl context
 */
private static SSLContext getTrustedSslContext(final Resource trustStoreFile, final String trustStorePassword,
                                               final String trustStoreType) {
    try {

        final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
        final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();

        try (InputStream casStream = trustStoreFile.getInputStream()) {
            casTrustStore.load(casStream, trustStorePasswordCharArray);
        }

        final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        final X509KeyManager customKeyManager = getKeyManager(ALG_NAME_PKIX, casTrustStore, trustStorePasswordCharArray);
        final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
        final X509TrustManager customTrustManager = getTrustManager(ALG_NAME_PKIX, casTrustStore);
        final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);

        final KeyManager[] keyManagers = {
                new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
        };
        final TrustManager[] trustManagers = {
                new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
        };

        final SSLContext context = SSLContexts.custom().useProtocol("SSL").build();
        context.init(keyManagers, trustManagers, null);
        return context;

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw Throwables.propagate(e);
    }
}
 
Example 46
Project: EvolvingNetLib   File: HttpsUtil.java   Source Code and License 5 votes vote down vote up
private static KeyManager[] prepareKeyManager(InputStream bksFile, String password) {
    try {
        if (bksFile == null || password == null) return null;
        KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        clientKeyStore.load(bksFile, password.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientKeyStore, password.toCharArray());
        return kmf.getKeyManagers();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 47
Project: Book-Shelf   File: CustomTrust.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose
 * certificates have not been signed by these certificates will fail with a {@code
 * SSLHandshakeException}.
 *
 * <p>This can be used to replace the host platform's built-in trusted certificates with a custom
 * set. This is useful in development where certificate authority-trusted certificates aren't
 * available. Or in production, to avoid reliance on third-party certificate authorities.
 *
 * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using
 * the host platform's built-in trust store.
 *
 * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>
 *
 * <p>Relying on your own trusted certificates limits your server team's ability to update their
 * TLS certificates. By installing a specific set of trusted certificates, you take on additional
 * operational complexity and limit your ability to migrate between certificate authorities. Do
 * not use custom trusted certificates in production without the blessing of your server's TLS
 * administrator.
 */
private X509TrustManager trustManagerForCertificates(InputStream in)
        throws GeneralSecurityException {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
    if (certificates.isEmpty()) {
        throw new IllegalArgumentException("expected non-empty set of trusted certificates");
    }

    // Put the certificates a key store.
    char[] password = "password".toCharArray(); // Any password will work.
    KeyStore keyStore = newEmptyKeyStore(password);
    int index = 0;
    for (Certificate certificate : certificates) {
        String certificateAlias = Integer.toString(index++);
        keyStore.setCertificateEntry(certificateAlias, certificate);
    }

    // Use it to build an X509 trust manager.
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
            TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
        throw new IllegalStateException("Unexpected default trust managers:"
                + Arrays.toString(trustManagers));
    }
    return (X509TrustManager) trustManagers[0];
}
 
Example 48
Project: fresco_floodlight   File: OFChannelInitializer.java   Source Code and License 5 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception {
	ChannelPipeline pipeline = ch.pipeline();
	OFChannelHandler handler = new OFChannelHandler(
			switchManager,
			connectionListener,
			pipeline,
			debugCounters,
			timer,
			ofBitmaps,
			defaultFactory);

	if (keyStore != null && keyStorePassword != null) {
		try {
			/* Set up factories and stores. */
			TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
			KeyStore tmpKS = null;
			tmFactory.init(tmpKS);

			/* Use keystore/pass defined in properties file. */
			KeyStore ks = KeyStore.getInstance("JKS");
			ks.load(new FileInputStream(keyStore), keyStorePassword.toCharArray());

			KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			kmf.init(ks, keyStorePassword.toCharArray());

			KeyManager[] km = kmf.getKeyManagers();
			TrustManager[] tm = tmFactory.getTrustManagers();

			/* Set up SSL prereqs for Netty. */
			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(km, tm, null);
			SSLEngine sslEngine = sslContext.createSSLEngine();

			/* We are the server and we will create secure sessions. */
			sslEngine.setUseClientMode(false);
			sslEngine.setEnableSessionCreation(true);

			/* These are redundant (default), but for clarity... */
			sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols()); 
			sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
			
			/* First, decrypt w/handler+engine; then, proceed with rest of handlers. */
			pipeline.addLast(PipelineHandler.SSL_TLS_ENCODER_DECODER, new SslHandler(sslEngine));
			log.info("SSL OpenFlow socket initialized and handler ready for switch.");
		} catch (Exception e) { /* There are lots of possible exceptions to catch, so this should get them all. */
			log.error("Exception initializing SSL OpenFlow socket: {}", e.getMessage());
			throw e; /* If we wanted secure but didn't get it, we should bail. */
		}
	}
	
	pipeline.addLast(PipelineHandler.OF_MESSAGE_DECODER,
			new OFMessageDecoder());
	pipeline.addLast(PipelineHandler.OF_MESSAGE_ENCODER,
			new OFMessageEncoder());
	pipeline.addLast(PipelineHandler.MAIN_IDLE,
			new IdleStateHandler(PipelineIdleReadTimeout.MAIN,
					PipelineIdleWriteTimeout.MAIN,
					0));
	pipeline.addLast(PipelineHandler.READ_TIMEOUT, new ReadTimeoutHandler(30));
	pipeline.addLast(PipelineHandler.CHANNEL_HANDSHAKE_TIMEOUT,
			new HandshakeTimeoutHandler(
					handler,
					timer,
					PipelineHandshakeTimeout.CHANNEL));

	pipeline.addLast(PipelineHandler.CHANNEL_HANDLER, handler);
}
 
Example 49
Project: athena   File: NettyMessagingManager.java   Source Code and License 5 votes vote down vote up
@Override
protected void initChannel(SocketChannel channel) throws Exception {
    TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore ts = KeyStore.getInstance("JKS");
    ts.load(new FileInputStream(tsLocation), tsPwd);
    tmFactory.init(ts);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(ksLocation), ksPwd);
    kmf.init(ks, ksPwd);

    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null);

    SSLEngine serverSslEngine = serverContext.createSSLEngine();

    serverSslEngine.setNeedClientAuth(true);
    serverSslEngine.setUseClientMode(false);
    serverSslEngine.setEnabledProtocols(serverSslEngine.getSupportedProtocols());
    serverSslEngine.setEnabledCipherSuites(serverSslEngine.getSupportedCipherSuites());
    serverSslEngine.setEnableSessionCreation(true);

    channel.pipeline().addLast("ssl", new io.netty.handler.ssl.SslHandler(serverSslEngine))
            .addLast("encoder", encoder)
            .addLast("decoder", new MessageDecoder())
            .addLast("handler", dispatcher);
}
 
Example 50
Project: RoughWorld   File: WebInterfaceSSL.java   Source Code and License 5 votes vote down vote up
/**
 * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a
 * loaded KeyManagerFactory. These objects must properly loaded/initialized
 * by the caller.
 */
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException {
    try {
        return makeSSLSocketFactory(loadedKeyStore, loadedKeyFactory.getKeyManagers());
    } catch (Exception e) {
    	System.out.println(e.toString());
        //throw new IOException(e.getMessage());
    }
    return null;
}
 
Example 51
Project: alfresco-core   File: AlfrescoKeyStoreImpl.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public KeyManager[] createKeyManagers()
{
    KeyInfoManager keyInfoManager = null;

    try
    {
        keyInfoManager = getKeyInfoManager(getKeyMetaDataFileLocation());
        KeyStore ks = loadKeyStore(keyStoreParameters, keyInfoManager);

        logger.debug("Initializing key managers");
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        
        String keyStorePassword = keyInfoManager.getKeyStorePassword();
        kmfactory.init(ks, keyStorePassword != null ? keyStorePassword.toCharArray(): null);
        return kmfactory.getKeyManagers(); 
    }
    catch(Throwable e)
    {
        throw new AlfrescoRuntimeException("Unable to create key manager", e);
    }
    finally
    {
        if(keyInfoManager != null)
        {
            keyInfoManager.clear();
        }
    }
}
 
Example 52
Project: tomcat7   File: JSSESocketFactory.java   Source Code and License 5 votes vote down vote up
@Override
public KeyManager[] getKeyManagers() throws Exception {
    String keystoreType = endpoint.getKeystoreType();
    if (keystoreType == null) {
        keystoreType = defaultKeystoreType;
    }

    String algorithm = endpoint.getAlgorithm();
    if (algorithm == null) {
        algorithm = KeyManagerFactory.getDefaultAlgorithm();
    }

    return getKeyManagers(keystoreType, endpoint.getKeystoreProvider(),
            algorithm, endpoint.getKeyAlias());
}
 
Example 53
Project: tomcat7   File: JSSESocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the initialized key managers.
 */
protected KeyManager[] getKeyManagers(String keystoreType,
                                      String keystoreProvider,
                                      String algorithm,
                                      String keyAlias)
            throws Exception {

    KeyManager[] kms = null;

    String keystorePass = getKeystorePassword();

    KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass);
    if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
        throw new IOException(
                sm.getString("jsse.alias_no_key_entry", keyAlias));
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    String keyPass = endpoint.getKeyPass();
    if (keyPass == null) {
        keyPass = keystorePass;
    }
    kmf.init(ks, keyPass.toCharArray());

    kms = kmf.getKeyManagers();
    if (keyAlias != null) {
        String alias = keyAlias;
        if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
            alias = alias.toLowerCase(Locale.ENGLISH);
        }
        for(int i=0; i<kms.length; i++) {
            kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias);
        }
    }

    return kms;
}
 
Example 54
Project: tomcat7   File: TesterSupport.java   Source Code and License 5 votes vote down vote up
protected static KeyManager[] getUser1KeyManagers() throws Exception {
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(getKeyStore("org/apache/tomcat/util/net/user1.jks"),
            "changeit".toCharArray());
    return kmf.getKeyManagers();
}
 
Example 55
Project: ats-framework   File: SslUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Trust-all SSL context.
 * Optionally specify certificate file to create the keystore from.
 *
 * @param certFileName
 * @param certPassword
 * @param protocol e.g. TLS, TLSv1.2
 * @return
 */
public static SSLContext getSSLContext( String certFileName, String certPassword, String protocol ) {

    SSLContext sslContext = null;
    char[] passphrase = null;
    if (certPassword != null) {
        passphrase = certPassword.toCharArray();
    }

    try {
        // First initialize the key and trust material.
        KeyStore ksKeys = KeyStore.getInstance("PKCS12");
        ksKeys.load(null);
        if (certFileName != null && certPassword != null) {
            createKeyStoreFromPemKey(certFileName, certPassword, ksKeys);
        }

        // KeyManagers decide which key material to use.
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ksKeys, passphrase);

        // TrustManagers decide whether to allow connections.
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");

        // Create a trust-all trust manager
        TrustManager[] trustManagers = new TrustManager[]{ new SslUtils.DefaultTrustManager() };
        tmf.init(ksKeys);

        sslContext = SSLContext.getInstance(protocol);
        sslContext.init(kmf.getKeyManagers(), trustManagers, null);
    } catch (Exception e) {
        throw new RuntimeException("Error initializing ssl context", e);
    }

    return sslContext;
}
 
Example 56
Project: mtls-sample   File: SerialNumberExtractor.java   Source Code and License 5 votes vote down vote up
SerialNumberExtractor() throws GeneralSecurityException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(null, null);
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
    KeyManager keyManager = keyManagers[0];
    this.keyManager = (X509ExtendedKeyManager) keyManager;
}
 
Example 57
Project: syndesis   File: ActiveMQUtil.java   Source Code and License 5 votes vote down vote up
public static KeyManager[] createKeyManagers(String clientCertificate) throws GeneralSecurityException, IOException {
    final KeyStore clientKs = createKeyStore("amq-client", clientCertificate);

    // create Key Manager
    KeyManagerFactory kmFactory = KeyManagerFactory.getInstance("PKIX");
    kmFactory.init(clientKs, null);
    return kmFactory.getKeyManagers();
}
 
Example 58
Project: tasfe-framework   File: HttpChannelInitializer.java   Source Code and License 5 votes vote down vote up
@Override
 protected void initChannel(SocketChannel ch) throws Exception {
     ChannelPipeline pipeline = ch.pipeline();

     // SSL的安全链接
     if (ServerConfig.isSsl()) {
         SSLContext sslcontext = SSLContext.getInstance("TLS");
         KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
         KeyStore ks = KeyStore.getInstance("JKS");
         String keyStorePath = ServerConfig.getKeyStorePath();
         String keyStorePassword = ServerConfig.getKeyStorePassword();
         ks.load(new FileInputStream(keyStorePath), keyStorePassword.toCharArray());
         String keyPassword = ServerConfig.getKeyPassword();
         kmf.init(ks, keyPassword.toCharArray());
         sslcontext.init(kmf.getKeyManagers(), null, null);
         SSLEngine sslEngine = sslcontext.createSSLEngine();
         sslEngine.setUseClientMode(false);
         sslEngine.setNeedClientAuth(false);
         /**
          * 务必放在第一位
          */
         pipeline.addLast(new SslHandler(sslEngine));
         logger.info("initChannel: addLast SslHandler");
         /**
          * Generates a temporary self-signed certificate for testing purposes.
          */
/*SelfSignedCertificate ssc = new SelfSignedCertificate();
SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
//SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
if (sslCtx != null) {
	pipeline.addLast(sslCtx.newHandler(ch.alloc()));
}*/
     }
     // Register HTTP handler chain.
     this.appendHttpPipeline(pipeline);
 }
 
Example 59
Project: iothub   File: MqttSslHandlerProvider.java   Source Code and License 5 votes vote down vote up
public SslHandler getSslHandler() {
    try {
        URL ksUrl = Resources.getResource(keyStoreFile);
        File ksFile = new File(ksUrl.toURI());
        URL tsUrl = Resources.getResource(keyStoreFile);
        File tsFile = new File(tsUrl.toURI());

        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance(keyStoreType);
        trustStore.load(new FileInputStream(tsFile), keyStorePassword.toCharArray());
        tmFactory.init(trustStore);

        KeyStore ks = KeyStore.getInstance(keyStoreType);

        ks.load(new FileInputStream(ksFile), keyStorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keyPassword.toCharArray());

        KeyManager[] km = kmf.getKeyManagers();
        TrustManager x509wrapped = getX509TrustManager(tmFactory);
        TrustManager[] tm = {x509wrapped};
        SSLContext sslContext = SSLContext.getInstance(TLS);
        sslContext.init(km, tm, null);
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.setNeedClientAuth(false);
        sslEngine.setWantClientAuth(true);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);
        return new SslHandler(sslEngine);
    } catch (Exception e) {
        log.error("Unable to set up SSL context. Reason: " + e.getMessage(), e);
        throw new RuntimeException("Failed to get SSL handler", e);
    }
}
 
Example 60
Project: pyplyn   File: AbstractRemoteClient.java   Source Code and License 5 votes vote down vote up
/**
 * Configures an {@link SSLContext} on the specified {@link OkHttpClient.Builder}, taking into account
 *   the trust store specified by {@link EndpointConnector#keystorePath()} and {@link EndpointConnector#keystorePassword()}}
 */
private static void initSSLSocketFactory(EndpointConnector connector, OkHttpClient.Builder builder) {
    char[] keystorePassword = byteToCharArray(connector.keystorePassword());
    try {
        // initialize keystore
        //   the default type is 'jks';  however, this can be changed by updating the `keystore.type` property
        //   in `$JAVA_HOME/lib/security/java.security`
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(new FileInputStream(connector.keystorePath()), keystorePassword);


        // setup trust manager factory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keystore);
        X509TrustManager trustManager = (X509TrustManager)trustManagerFactory.getTrustManagers()[0];

        // setup key manager factory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, keystorePassword);

        // initialize an SSL context using the same protocol as the default and init
        SSLContext sslContext = SSLContext.getInstance(connector.sslContextAlgorithm());
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        // set socket factory
        builder.sslSocketFactory(sslContext.getSocketFactory(), trustManager);

    } catch (IOException |CertificateException |UnrecoverableKeyException |NoSuchAlgorithmException |KeyStoreException |KeyManagementException e) {
        // rethrow as RTE, since we cannot continue if mutual auth was expected but could not be initialized
        throw new RuntimeException("Unexpected exception configuring mutual authentication for " + connector.id(), e);

    } finally {
        // clear password after using it
        Arrays.fill(keystorePassword, (char)0);
    }
}