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

The following examples show how to use javax.net.ssl.KeyManagerFactory#init() . 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: SecurityHelper.java    From MQTT-Essentials-A-Lightweight-IoT-Protocol with MIT 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 2
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 3
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private SSLContext createSSLContext() {
    if (!this.ssl) {
        return null;
    }

    try {
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        final KeyStore trustStore = KeyStore.getInstance("JKS");
        InputStream trustStream = new FileInputStream(
                FileHelper.getAbsoluteFilePathFromClassPath("jwt/truststore.jks").toFile());
        trustStore.load(trustStream, "changeit".toCharArray());
        tmf.init(trustStore);

        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        InputStream keyStream = new FileInputStream(
                FileHelper.getAbsoluteFilePathFromClassPath("jwt/node-0-keystore.jks").toFile());

        keyStore.load(keyStream, "changeit".toCharArray());
        kmf.init(keyStore, "changeit".toCharArray());

        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        return sslContext;
    } catch (GeneralSecurityException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: CipherTestUtils.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private CipherTestUtils()
        throws IOException, FileNotFoundException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, InvalidKeySpecException {
    factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    KeyStore serverKeyStore = createServerKeyStore(SERVER_PUBLIC_KEY,
            SERVER_PRIVATE_KEY);
    KeyStore serverTrustStore = createServerKeyStore(CA_PUBLIC_KEY,
            CA_PRIVATE_KEY);

    if (serverKeyStore != null) {
        KeyManagerFactory keyFactory1
                = KeyManagerFactory.getInstance(
                        KeyManagerFactory.getDefaultAlgorithm());
        keyFactory1.init(serverKeyStore, PASSWORD);
        serverKeyManager = (X509ExtendedKeyManager) keyFactory1.
                getKeyManagers()[0];
    } else {
        serverKeyManager = null;
    }
    serverTrustManager = serverTrustStore != null
            ? new AlwaysTrustManager(serverTrustStore) : null;

    KeyStore clientKeyStore, clientTrustStore;
    clientTrustStore = serverTrustStore;
    clientKeyStore =
            createServerKeyStore(CLIENT_PUBLIC_KEY,CLIENT_PRIVATE_KEY);
    if (clientKeyStore != null) {
        KeyManagerFactory keyFactory
                = KeyManagerFactory.getInstance(
                        KeyManagerFactory.getDefaultAlgorithm());
        keyFactory.init(clientKeyStore, PASSWORD);
        clientKeyManager = (X509ExtendedKeyManager) keyFactory.
                getKeyManagers()[0];
    } else {
        clientKeyManager = null;
    }
    clientTrustManager = (clientTrustStore != null)
            ? new AlwaysTrustManager(clientTrustStore) : null;
}
 
Example 5
Source File: NetUtils.java    From java-bot-sdk with Apache License 2.0 5 votes vote down vote up
public static KeyManagerFactory createKeyFactory(File pKeyFile, String pKeyPassword) throws Exception {

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        InputStream keyInput = new FileInputStream(pKeyFile);
        keyStore.load(keyInput, pKeyPassword.toCharArray());
        keyInput.close();

        keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());
        return keyManagerFactory;
    }
 
Example 6
Source File: NettySslFactory.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * @param config the {@link SSLConfig}.
 * @return an initialized {@link KeyManagerFactory}
 * @throws GeneralSecurityException
 * @throws IOException
 */
static KeyManagerFactory getKeyManagerFactory(SSLConfig config) throws GeneralSecurityException, IOException {
  KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
  KeyStore ks = loadKeyStore(config.sslKeystorePath, config.sslKeystoreType, config.sslKeystorePassword);
  String keyPassword = config.sslKeyPassword.isEmpty() ? config.sslKeystorePassword : config.sslKeyPassword;
  kmf.init(ks, keyPassword.toCharArray());
  return kmf;
}
 
Example 7
Source File: NettyHelper.java    From PeonyFramwork with Apache License 2.0 5 votes vote down vote up
public static SSLContext createSSLContext(String type , String path , String password) throws Exception {
    KeyStore ks = KeyStore.getInstance(type); /// "JKS"
    InputStream ksInputStream = new FileInputStream(path); /// 证书存放地址
    ks.load(ksInputStream, password.toCharArray());
    //KeyManagerFactory充当基于密钥内容源的密钥管理器的工厂。
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());//getDefaultAlgorithm:获取默认的 KeyManagerFactory 算法名称。
    kmf.init(ks, password.toCharArray());
    //SSLContext的实例表示安全套接字协议的实现,它充当用于安全套接字工厂或 SSLEngine 的工厂。
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), null, null);
    return sslContext;
}
 
Example 8
Source File: TLSParameterJaxBUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * This method converts the JAXB KeyManagersType into a list of
 * JSSE KeyManagers.
 */
public static KeyManager[] getKeyManagers(KeyManagersType kmc, String alias)
    throws GeneralSecurityException,
           IOException {

    KeyStore keyStore = getKeyStore(kmc.getKeyStore(), false);

    String alg = kmc.isSetFactoryAlgorithm()
                 ? kmc.getFactoryAlgorithm()
                 : KeyManagerFactory.getDefaultAlgorithm();

    char[] keyPass = getKeyPassword(kmc);

    KeyManagerFactory fac =
                 kmc.isSetProvider()
                 ? KeyManagerFactory.getInstance(alg, kmc.getProvider())
                 : KeyManagerFactory.getInstance(alg);

    try {
        fac.init(keyStore, keyPass);

        return fac.getKeyManagers();
    } catch (java.security.UnrecoverableKeyException uke) {
        //jsse has the restriction that different key in keystore
        //cannot has different password, use MultiKeyPasswordKeyManager
        //as fallback when this happen
        MultiKeyPasswordKeyManager manager
            = new MultiKeyPasswordKeyManager(keyStore, alias,
                                         new String(keyPass));
        return new KeyManager[]{manager};
    }
}
 
Example 9
Source File: MysqlServerHandler.java    From antsdb with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void switchToSSL() {
    if (enableSSL()) {
        String keyFile = getFish().getConfig().getSSLKeyFile();
        String password = getFish().getConfig().getSSLPassword();
        try (FileInputStream keyIn = new FileInputStream(keyFile)) {
            SSLContext serverContext;
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

            byte[] sslKeyVal = IOUtils.toByteArray(keyIn);

            char[] pass = password.toCharArray();
            ks.load(new ByteArrayInputStream(sslKeyVal), pass);

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

            // Initialize the SSLContext to work with our key managers.
            serverContext = SSLContext.getInstance("TLS");
            serverContext.init(kmf.getKeyManagers(), null, null);
            SSLEngine sslEngine = serverContext.createSSLEngine();
            sslEngine.setUseClientMode(false);
            channel.pipeline().addFirst("ssl", new SslHandler(sslEngine));
        }
        catch (Exception e) {
            throw new CodingError("Failed to switch to SSL: " + e.getMessage());
        }
    }
    else {
        throw new CodingError("ssl.key_file or ssl.password is not set in configuration and ssl is disabled.");
    }
}
 
Example 10
Source File: TLSUtils.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static SSLContext initializeTLS() {
   try {
      String keystorePath = System.getProperty("dependency.keystore");;
      if (keystorePath == null) {
         keystorePath = Paths.get(TLSUtils.class.getResource("/keycloak.jks").toURI()).toAbsolutePath().toString(); // when executed directly from IDE without Maven
      }

      KeyStore keystore = KeyStore.getInstance("jks");
      keystore.load(new FileInputStream(keystorePath), "secret".toCharArray());
      KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      keyManagerFactory.init(keystore, "secret".toCharArray());
      KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

      String truststorePath = System.getProperty("dependency.truststore");;
      if (truststorePath == null) {
         truststorePath = Paths.get(TLSUtils.class.getResource("/keycloak.truststore").toURI()).toAbsolutePath().toString(); // when executed directly from IDE without Maven
      }

      // Essentially, this is REQUEST CLIENT AUTH behavior. It doesn't fail if the client doesn't have a cert.
      // However it will challenge him to send it.
      KeyStore truststore = KeyStore.getInstance("jks");
      truststore.load(new FileInputStream(truststorePath), "secret".toCharArray());
      TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      trustManagerFactory.init(truststore);
      TrustManager[] trustManagers = new TrustManager[trustManagerFactory.getTrustManagers().length + 1];
      for (int i = 0; i < trustManagerFactory.getTrustManagers().length; ++i) {
         trustManagers[i] = trustManagerFactory.getTrustManagers()[i];
      }
      trustManagers[trustManagers.length - 1] = TRUST_ALL_MANAGER;

      SSLContext sslContext;
      sslContext = SSLContext.getInstance("TLS");
      sslContext.init(keyManagers, trustManagers, null);
      return sslContext;
   } catch (Exception e) {
      throw new IllegalStateException("Could not initialize TLS", e);
   }
}
 
Example 11
Source File: SecurityUtils.java    From RISE-V2G with MIT License 5 votes vote down vote up
/**
 * Sets the SSLContext of the TLSServer and TLSClient with the given keystore and truststore locations as
 * well as the password protecting the keystores/truststores.
 * 
 * @param keyStorePath The relative path and filename for the keystore
 * @param trustStorePath The relative path and filename for the truststore
 * @param keyStorePassword The password protecting the keystore
 */
public static void setSSLContext(
		String keyStorePath, 
		String trustStorePath,
		String keyStorePassword) {
    KeyStore keyStore = SecurityUtils.getKeyStore(keyStorePath, keyStorePassword);
    KeyStore trustStore = SecurityUtils.getKeyStore(trustStorePath, keyStorePassword);

	try {
		// Initialize a key manager factory with the keystore
	    KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		keyFactory.init(keyStore, keyStorePassword.toCharArray());
	    KeyManager[] keyManagers = keyFactory.getKeyManagers();

	    // Initialize a trust manager factory with the truststore
	    TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());    
	    trustFactory.init(trustStore);
	    TrustManager[] trustManagers = trustFactory.getTrustManagers();

	    // Initialize an SSL context to use these managers and set as default
	    SSLContext sslContext = SSLContext.getInstance("TLS");
	    sslContext.init(keyManagers, trustManagers, null);
	    SSLContext.setDefault(sslContext); 
	} catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | 
			KeyManagementException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to initialize SSL context");
	}    
}
 
Example 12
Source File: SSLConfigurationModule.java    From olat with Apache License 2.0 5 votes vote down vote up
public static KeyManager[] getKeyManagers() {
	try {
		final KeyStore keyStore = KeyStore.getInstance(keyStoreType);
		final FileInputStream kStream = new FileInputStream(keyStoreFile);
		keyStore.load(kStream, keyStorePass.toCharArray());
		final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
		keyManagerFactory.init(keyStore, keyStorePass.toCharArray());
		return keyManagerFactory.getKeyManagers();
	} catch (final Exception e) {
private static final Logger log = LoggerHelper.getLogger();

		e.printStackTrace();
		return null;
	}
}
 
Example 13
Source File: CertTool.java    From OkHttpPacker with Apache License 2.0 5 votes vote down vote up
public 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 keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(clientKeyStore, password.toCharArray());
        return keyManagerFactory.getKeyManagers();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 14
Source File: IdentityController.java    From Spark with Apache License 2.0 5 votes vote down vote up
public KeyManagerFactory initKeyManagerFactory()
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, NoSuchProviderException {
    loadKeyStores();
    KeyManagerFactory keyManFact = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    keyManFact.init(idStore, IdentityController.passwd);

    return keyManFact;
}
 
Example 15
Source File: SSLHandlerFactory.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public SSLHandlerFactory(InboundWebsocketSSLConfiguration sslConfiguration) {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
        algorithm = "SunX509";
    }
    try {
        KeyStore keyStore = getKeyStore(sslConfiguration.getKeyStore(), sslConfiguration.getKeyStorePass());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
        keyManagerFactory.init(keyStore, sslConfiguration.getCertPass() != null ?
                sslConfiguration.getCertPass().toCharArray() :
                sslConfiguration.getKeyStorePass().toCharArray());
        KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
        TrustManager[] trustManagers = null;
        if (sslConfiguration.getTrustStore() != null) {
            this.needClientAuth = true;
            KeyStore trustStore = getKeyStore(sslConfiguration.getTrustStore(),
                                              sslConfiguration.getTrustStorePass());
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(algorithm);
            trustManagerFactory.init(trustStore);
            trustManagers = trustManagerFactory.getTrustManagers();
        }
        serverContext = SSLContext.getInstance(protocol);
        serverContext.init(keyManagers, trustManagers, null);
        cipherSuites = sslConfiguration.getCipherSuites();
        sslProtocols = sslConfiguration.getSslProtocols();
    } catch (UnrecoverableKeyException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException | IOException ex) {
        throw new IllegalArgumentException("Failed to initialize the server side SSLContext", ex);
    }
}
 
Example 16
Source File: ReverseProxyComponent.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
private KeyManager[] getKeyManagers(OptionMap options) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {
    KeyStore keystore = (KeyStore) options.get("keystore");
    if (keystore != null) {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, options.getString("keystorePassword").toCharArray());
        return keyManagerFactory.getKeyManagers();
    } else {
        return null;
    }
}
 
Example 17
Source File: DefaultCassandanaSslContextCreator.java    From cassandana with Apache License 2.0 5 votes vote down vote up
private static SslContextBuilder builderWithJdkProvider(KeyStore ks, String keyPassword)
        throws GeneralSecurityException {
    LOG.info("Initializing key manager...");
    final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keyPassword.toCharArray());
    LOG.info("Initializing SSL context...");
    return SslContextBuilder.forServer(kmf);
}
 
Example 18
Source File: ConnectorBootstrap.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
private static SslRMIServerSocketFactory createSslRMIServerSocketFactory(
        String sslConfigFileName,
        String[] enabledCipherSuites,
        String[] enabledProtocols,
        boolean sslNeedClientAuth) {
    if (sslConfigFileName == null) {
        return new SslRMIServerSocketFactory(
                enabledCipherSuites,
                enabledProtocols,
                sslNeedClientAuth);
    } else {
        checkRestrictedFile(sslConfigFileName);
        try {
            // Load the SSL keystore properties from the config file
            Properties p = new Properties();
            try (InputStream in = new FileInputStream(sslConfigFileName)) {
                BufferedInputStream bin = new BufferedInputStream(in);
                p.load(bin);
            }
            String keyStore =
                    p.getProperty("javax.net.ssl.keyStore");
            String keyStorePassword =
                    p.getProperty("javax.net.ssl.keyStorePassword", "");
            String trustStore =
                    p.getProperty("javax.net.ssl.trustStore");
            String trustStorePassword =
                    p.getProperty("javax.net.ssl.trustStorePassword", "");

            char[] keyStorePasswd = null;
            if (keyStorePassword.length() != 0) {
                keyStorePasswd = keyStorePassword.toCharArray();
            }

            char[] trustStorePasswd = null;
            if (trustStorePassword.length() != 0) {
                trustStorePasswd = trustStorePassword.toCharArray();
            }

            KeyStore ks = null;
            if (keyStore != null) {
                ks = KeyStore.getInstance(KeyStore.getDefaultType());
                try (FileInputStream ksfis = new FileInputStream(keyStore)) {
                    ks.load(ksfis, keyStorePasswd);
                }
            }
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                    KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, keyStorePasswd);

            KeyStore ts = null;
            if (trustStore != null) {
                ts = KeyStore.getInstance(KeyStore.getDefaultType());
                try (FileInputStream tsfis = new FileInputStream(trustStore)) {
                    ts.load(tsfis, trustStorePasswd);
                }
            }
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                    TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(ts);

            SSLContext ctx = SSLContext.getInstance("SSL");
            ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

            return new SslRMIServerSocketFactory(
                    ctx,
                    enabledCipherSuites,
                    enabledProtocols,
                    sslNeedClientAuth);
        } catch (Exception e) {
            throw new AgentConfigurationError(AGENT_EXCEPTION, e, e.toString());
        }
    }
}
 
Example 19
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 20
Source File: SSLKeyStoreLoader.java    From tessera with Apache License 2.0 4 votes vote down vote up
static KeyManager[] fromPemKeyFile(Path key, Path certificate) throws IOException, GeneralSecurityException {

        final PKCS8EncodedKeySpec encodedKeySpec = getEncodedKeySpec(key);

        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        final PrivateKey privateKey = keyFactory.generatePrivate(encodedKeySpec);

        final List<X509Certificate> certificates = getCertificates(certificate);

        KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);
        keyStore.load(null, null);
        keyStore.setKeyEntry(ALIAS, privateKey, EMPTY_PASSWORD, certificates.stream().toArray(Certificate[]::new));

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

        return keyManagerFactory.getKeyManagers();
    }