Java Code Examples for javax.net.ssl.KeyManagerFactory#getInstance()

The following examples show how to use javax.net.ssl.KeyManagerFactory#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ArangoSslTest.java    From arangodb-java-driver with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void connect() throws Exception {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(this.getClass().getResourceAsStream(SSL_TRUSTSTORE), SSL_TRUSTSTORE_PASSWORD.toCharArray());

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

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);

    final SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    final ArangoDB arangoDB = new ArangoDB.Builder()
            .loadProperties(ArangoSslTest.class.getResourceAsStream("/arangodb-ssl.properties")).useSsl(true)
            .sslContext(sc).build();
    final ArangoDBVersion version = arangoDB.getVersion();
    assertThat(version, is(notNullValue()));
}
 
Example 2
Source File: MqttConnection.java    From bce-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * get SSLSocketFactory
 * @param caKeystore
 * @param clientKeystore
 * @param keystorePassword
 *
 * @return
 */
public static SSLSocketFactory getFactory(KeyStore caKeystore, KeyStore clientKeystore, String keystorePassword) {
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(caKeystore);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientKeystore, keystorePassword.toCharArray());
        SSLContext context = SSLContext.getInstance(TLS_V_1_2);
        KeyManager[] kms = kmf.getKeyManagers();
        context.init(kms, tmf.getTrustManagers(), null);
        return context.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 3
Source File: KeyStoreUtil.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the array of key managers for a given info store+info.
 *
 * @param pathInfo
 * @throws Exception
 */
public static KeyManager[] getKeyManagers(Info pathInfo) throws Exception {
    if (pathInfo.store == null) {
        return null;
    }
    File clientKeyStoreFile = new File(pathInfo.store);
    if (!clientKeyStoreFile.isFile()) {
        throw new Exception("No KeyManager: " + pathInfo.store + " does not exist or is not a file.");
    }
    String clientKeyStorePassword = pathInfo.password;
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    KeyStore keyStore = KeyStore.getInstance("JKS");

    FileInputStream clientFis = new FileInputStream(pathInfo.store);
    keyStore.load(clientFis, clientKeyStorePassword.toCharArray());
    clientFis.close();
    kmf.init(keyStore, clientKeyStorePassword.toCharArray());
    return kmf.getKeyManagers();
}
 
Example 4
Source File: MqttConnectionFactory.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
protected SSLSocketFactory getSocketFactory(String keyStoreLocation, String keyStoreType, String keyStorePassword,
                                            String trustStoreLocation, String trustStoreType,
                                            String trustStorePassword, String sslVersion) throws Exception {

    char[] keyPassphrase = keyStorePassword.toCharArray();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(new FileInputStream(keyStoreLocation), keyPassphrase);

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

    char[] trustPassphrase = trustStorePassword.toCharArray();
    KeyStore trustStore = KeyStore.getInstance(trustStoreType);
    trustStore.load(new FileInputStream(trustStoreLocation), trustPassphrase);

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    SSLContext sslContext = SSLContext.getInstance(sslVersion);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    return sslContext.getSocketFactory();
}
 
Example 5
Source File: SSLContextBuilder.java    From core-ng-project with Apache License 2.0 6 votes vote down vote up
public SSLContext build() {
    try {
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(PEM.decode(KEY)));
        Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(PEM.decode(CERT)));

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setKeyEntry("default", privateKey, new char[0], new Certificate[]{certificate});

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, new char[0]);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), null, null);
        return context;
    } catch (KeyStoreException | IOException | CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyManagementException | InvalidKeySpecException e) {
        throw new Error(e);
    }
}
 
Example 6
Source File: TrustUtils.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get a custom SSL context for secure server connections. The key store of
 * the context contains the private key and bridge certificate. The trust
 * manager contains system and own certificates or blindly accepts every
 * server certificate.
 */
public static SSLContext getCustomSSLContext(
        PrivateKey privateKey,
        X509Certificate bridgeCert,
        boolean validateCertificate)
        throws KeyStoreException,
        IOException,
        NoSuchAlgorithmException,
        CertificateException,
        UnrecoverableKeyException,
        KeyManagementException {
    // in-memory keystore
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(null, null);
    keystore.setKeyEntry("private",
            privateKey,
            new char[0],
            new Certificate[] { bridgeCert });

    // key managers
    KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmFactory.init(keystore, new char[0]);

    KeyManager[] km = kmFactory.getKeyManagers();
    return getCustomSSLContext(km, validateCertificate);
}
 
Example 7
Source File: CertificateContextBuilder.java    From sissi with Apache License 2.0 5 votes vote down vote up
private KeyManager[] getKeyManagers(Certificate key) throws Exception {
	KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	InputStream certificate = key.getFile().openStream();
	try {
		KeyStore ks = KeyStore.getInstance(this.keystore);
		ks.load(certificate, key.getPassword());
		factory.init(ks, key.getPassword());
	} finally {
		IOUtil.closeQuietly(certificate);
	}
	return factory.getKeyManagers();
}
 
Example 8
Source File: HttpsUtils.java    From BaseProject with Apache License 2.0 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 9
Source File: SSLKeyManager.java    From PADListener with GNU General Public License v2.0 5 votes vote down vote up
public synchronized void addKeyStore(String description, KeyStore ks, char[] password) throws KeyStoreException, UnrecoverableKeyException {
    try {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, password);
        KeyManager km = kmf.getKeyManagers()[0];
        if (!(km instanceof X509KeyManager))
            throw new KeyStoreException("KeyManager for " + description + "is not X509!");
        _stores.put(description, ks);
        _managers.put(description, (X509KeyManager) km);
    } catch (NoSuchAlgorithmException nsae) {
        _logger.severe("This should never happen! SunX509 algorithm not found: " + nsae.getMessage());
    }
    _changeSupport.firePropertyChange(KEY_PROPERTY, null, null);
}
 
Example 10
Source File: EciesEncryptionClient.java    From protect with MIT License 5 votes vote down vote up
private void configureHttps(final HttpsURLConnection httpsConnection, final int remoteServerId)
		throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
		UnrecoverableKeyException, KeyManagementException {

	// Configure SSL context
	final SSLContext sslContext = SSLContext.getInstance(CommonConfiguration.TLS_VERSION);

	// Create in-memory key store
	final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
	final char[] password = "password".toCharArray();
	keyStore.load(null, password);

	// Add the CA certificate for the server
	keyStore.setCertificateEntry("ca-" + remoteServerId, this.caCertificates.get(remoteServerId - 1));

	// Add certificate and private key for the server
	// Note: Client CA cert is last after all the servers
	final X509Certificate ourCaCert = this.caCertificates.get(this.serverConfiguration.getNumServers());
	keyStore.setKeyEntry("host", this.clientTlsKey, password,
			new X509Certificate[] { clientCertificate, ourCaCert });

	// Make Key Manager Factory
	final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
	kmf.init(keyStore, password);

	// Setup the trust manager factory
	final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
	tmf.init(keyStore);

	// Initialize the context
	sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());

	// Get the socket factory from the context
	httpsConnection.setSSLSocketFactory(sslContext.getSocketFactory());
}
 
Example 11
Source File: SSLHelper.java    From HaoReader with GNU General Public License v3.0 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 12
Source File: AlfrescoKeyStoreImpl.java    From alfresco-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public KeyManager[] createKeyManagers()
{
    KeyInfoManager keyInfoManager = null;

    try
    {
        keyInfoManager = getKeyInfoManager(getKeyStoreParameters());
        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 13
Source File: ClientSslContextFactory.java    From game-server with MIT License 5 votes vote down vote up
/**
 * 服务器 SSLContext
 * 
 * @author JiangZhiYong
 * @QQ 359135103 2017年9月5日 下午2:19:01
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
 */
private static SSLContext createServerSslContext() throws GeneralSecurityException, IOException {
	// Create keystore
	KeyStore ks = KeyStore.getInstance("JKS");
	InputStream in = null;
	try {
		in = ClientSslContextFactory.class.getResourceAsStream(GATE_KEYSTORE);
		if(in==null) {
			in=FileUtil.getFileInputStream(PressureClientTool.configPath+java.io.File.separatorChar+GATE_KEYSTORE);
		}
		ks.load(in, GATE_PW);
	} finally {
		if (in != null) {
			try {
				in.close();
			} catch (IOException ignored) {
			}
		}
	}

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

	// Initialize the SSLContext to work with our key managers.
	SSLContext sslContext = SSLContext.getInstance(PROTOCOL);
	sslContext.init(kmf.getKeyManagers(), ClientTrustManagerFactory.X509_MANAGERS, null);
	return sslContext;
}
 
Example 14
Source File: CertificateHelper.java    From CapturePacket with MIT License 5 votes vote down vote up
public static KeyManager[] getKeyManagers(KeyStore keyStore,
        Authority authority) throws NoSuchAlgorithmException,
        NoSuchProviderException, UnrecoverableKeyException,
        KeyStoreException {
    String keyManAlg = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManAlg
    /* , PROVIDER_NAME */);
    kmf.init(keyStore, authority.password());
    return kmf.getKeyManagers();
}
 
Example 15
Source File: HttpClientUtil.java    From jframe with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param trustFile
 * @param trustPasswd
 * @param keyFile
 * @param keyPasswd
 * @return
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws UnrecoverableKeyException
 * @throws KeyManagementException
 */
public static SSLContext getSSLContext(
		FileInputStream trustFileInputStream, String trustPasswd,
		FileInputStream keyFileInputStream, String keyPasswd)
		throws NoSuchAlgorithmException, KeyStoreException,
		CertificateException, IOException, UnrecoverableKeyException,
		KeyManagementException {

	// ca
	TrustManagerFactory tmf = TrustManagerFactory
			.getInstance(HttpClientUtil.SunX509);
	KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS);
	trustKeyStore.load(trustFileInputStream,
			HttpClientUtil.str2CharArray(trustPasswd));
	tmf.init(trustKeyStore);

	final char[] kp = HttpClientUtil.str2CharArray(keyPasswd);
	KeyManagerFactory kmf = KeyManagerFactory
			.getInstance(HttpClientUtil.SunX509);
	KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12);
	ks.load(keyFileInputStream, kp);
	kmf.init(ks, kp);

	SecureRandom rand = new SecureRandom();
	SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS);
	ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);

	return ctx;
}
 
Example 16
Source File: SecureChatServerInitializer.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
private SSLContext initSSLContext() throws Exception {

        KeyStore ks = KeyStore.getInstance("JKS");
        InputStream ksInputStream = new FileInputStream("/opt/cert/sChat.jks");
        ks.load(ksInputStream, "123456".toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, "123456".toCharArray());
        SSLContext sslContext = SSLContext.getInstance("TLS");
        try {
            sslContext.init(kmf.getKeyManagers(), null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sslContext;
    }
 
Example 17
Source File: SocketTcpBIO.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
private void setupSSLSocket(boolean clientMode) throws Exception
{
	String certificateAlgorithm = Config.getConfigByName("tls.properties").getString("cert.ALGORITHM");
    String certificateSSLVersion = Config.getConfigByName("tls.properties").getString("cert.SSL_VERSION");
    String certificateServerPath = Config.getConfigByName("tls.properties").getString("cert.SERVER.DIRECTORY");
    String certificateServerKeystorePassword = Config.getConfigByName("tls.properties").getString("cert.SERVER.KEYSTORE_PASSWORD");
    String certificateServerKeyPassword = Config.getConfigByName("tls.properties").getString("cert.SERVER.KEY_PASSWORD");      
    char[] certificateKeystorePasswordArray;
    char[] certificateKeyPasswordArray;
    
    if (null == certificateServerKeyPassword || certificateServerKeyPassword.length() == 0)
    	certificateKeyPasswordArray = null;
    else
    	certificateKeyPasswordArray = certificateServerKeyPassword.toCharArray();
    
    if (null == certificateServerKeystorePassword || certificateServerKeystorePassword.length() == 0)
    	certificateKeystorePasswordArray = null;
    else
    	certificateKeystorePasswordArray = certificateServerKeystorePassword.toCharArray();

    KeyStore keyStore = KeyStore.getInstance(certificateAlgorithm);
    keyStore.load(new FileInputStream(certificateServerPath), certificateKeystorePasswordArray);
    
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    keyManagerFactory.init(keyStore, certificateKeyPasswordArray);
    
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
    
    System.setProperty("javax.net.ssl.trustStore", certificateServerPath);
 System.setProperty("javax.net.ssl.trustStorePassword", certificateServerKeystorePassword);
 
 SSLContext sslc = SSLContext.getInstance(certificateSSLVersion);
 	sslc.init(keyManagers, null, null);
 	
 	SSLSocketFactory sslSocketFactory = (SSLSocketFactory)sslc.getSocketFactory();
 	this.sslSocket = (SSLSocket)sslSocketFactory.createSocket(this.socket,
                    										  this.socket.getInetAddress().getHostAddress(),
                    										  this.socket.getPort(),
                    										  false);
 	this.sslSocket.setUseClientMode(clientMode);
}
 
Example 18
Source File: TLSRestrictions.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
static SSLContext createSSLContext(String[] trustNames,
        String[] certNames) throws Exception {
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

    TrustManagerFactory tmf = null;
    if (trustNames != null && trustNames.length > 0
            && !trustNames[0].equals(NONE_CERT)) {
        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(null, null);
        for (int i = 0; i < trustNames.length; i++) {
            try (InputStream is = new ByteArrayInputStream(
                    loadCert(trustNames[i]).getBytes())) {
                Certificate trustCert = certFactory.generateCertificate(is);
                trustStore.setCertificateEntry("trustCert-" + i, trustCert);
            }
        }

        tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(trustStore);
    }

    Certificate[] certChain = new Certificate[certNames.length];
    for (int i = 0; i < certNames.length; i++) {
        try (InputStream is = new ByteArrayInputStream(
                loadCert(certNames[i]).getBytes())) {
            Certificate cert = certFactory.generateCertificate(is);
            certChain[i] = cert;
        }
    }

    PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(
            Base64.getMimeDecoder().decode(loadPrivKey(certNames[0])));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privKey = keyFactory.generatePrivate(privKeySpec);

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    keyStore.setKeyEntry("keyCert", privKey, PASSWORD, certChain);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
    kmf.init(keyStore, PASSWORD);

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(kmf.getKeyManagers(),
            tmf == null ? null : tmf.getTrustManagers(), null);
    return context;
}
 
Example 19
Source File: SSLFacadeTest.java    From getty with Apache License 2.0 4 votes vote down vote up
@Before
    public void setUp() throws IOException, NoSuchAlgorithmException, KeyStoreException, CertificateException, UnrecoverableKeyException, KeyManagementException {
        KeyStore ks = KeyStore.getInstance("JKS");
        KeyStore ts = KeyStore.getInstance("JKS");
        String keyStoreFile = JKS_FILE;
        String trustStoreFile = JKS_FILE;
        String passw = JKS_FILE_PASSWORD;

        char[] passphrase = passw.toCharArray();

        ks.load(new FileInputStream(keyStoreFile), passphrase);

        ts.load(new FileInputStream(trustStoreFile), passphrase);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ts);

        sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);


        sslClientSem = new Semaphore(0);
        sslServerSem = new Semaphore(0);

        sslClient = createSSL(CLIENT_TAG, true);
        sslServer = createSSL(SERVER_TAG, false);

        log("== Init SSL listeners");
        clientListener = crateListener(CLIENT_TAG, sslServer);
        serverListener = crateListener(SERVER_TAG, sslClient);
        sslClient.setSSLListener(clientListener);
        sslServer.setSSLListener(serverListener);

//    cleintIn1 = CharBuffer.wrap(HELLO_FROM_CLIENT_1);
//    serverIn1 = CharBuffer.wrap(HELLO_FROM_SERVER_1);
//    cleintIn2 = CharBuffer.wrap(HELLO_FROM_CLIENT_2);
//    serverIn2 = CharBuffer.wrap(HELLO_FROM_SERVER_2);
//    cleintIn3 = CharBuffer.wrap(HELLO_FROM_CLIENT_3);

    }
 
Example 20
Source File: DevicePluginContext.java    From DeviceConnect-Android with MIT License 3 votes vote down vote up
/**
 * SSLContext のインスタンスを作成します.
 *
 * <p>
 * プラグイン内で Web サーバを立ち上げて、Manager と同じ証明書を使いたい場合には、この SSLContext を使用します。
 * </p>
 *
 * @param keyStore キーストア
 * @param password パスワード
 * @return SSLContextのインスタンス
 * @throws GeneralSecurityException SSLContextの作成に失敗した場合に発生
 */
public SSLContext createSSLContext(final KeyStore keyStore, final String password) throws GeneralSecurityException {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
    return sslContext;
}