javax.net.ssl.KeyManager Java Examples

The following examples show how to use javax.net.ssl.KeyManager. 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: HttpWebConnectionInsecureSSLWithClientCertificateTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Before
public void setUp() throws Exception {
    final URL url = getClass().getClassLoader().getResource("insecureSSL.keystore");
    final KeyStore keystore = KeyStore.getInstance("jks");
    final char[] pwd = "nopassword".toCharArray();
    keystore.load(url.openStream(), pwd);

    final TrustManagerFactory trustManagerFactory = createTrustManagerFactory();
    trustManagerFactory.init(keystore);
    final TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    final KeyManagerFactory keyManagerFactory = createKeyManagerFactory();
    keyManagerFactory.init(keystore, pwd);
    final KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    final SSLContext serverSSLContext = SSLContext.getInstance("TLS");
    serverSSLContext.init(keyManagers, trustManagers, null);

    localServer_ = new LocalTestServer(serverSSLContext);
    localServer_.start();
}
 
Example #2
Source File: AndroidSslSocketFactoryFactory.java    From PresencePublisher with MIT License 6 votes vote down vote up
SSLSocketFactory getSslSocketFactory(@Nullable String clientCertAlias) {
    try {
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore androidCAStore = KeyStore.getInstance("AndroidCAStore");
        if (androidCAStore == null) {
            HyperLog.w(TAG, "Unable to load CA keystore");
            return null;
        }
        androidCAStore.load(null);
        trustManagerFactory.init(androidCAStore);
        KeyManager[] keyManagers = null;
        if (clientCertAlias != null) {
            keyManagers = getClientKeyManagers(clientCertAlias);
        }
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
        return sslContext.getSocketFactory();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException | IOException e) {
        HyperLog.w(TAG, "Unable to get socket factory", e);
        return null;
    }
}
 
Example #3
Source File: TesterSupport.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
protected static KeyManager[] getUser1KeyManagers() throws Exception {
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(getKeyStore(CLIENT_JKS), JKS_PASS.toCharArray());
    KeyManager[] managers = kmf.getKeyManagers();
    KeyManager manager;
    for (int i=0; i < managers.length; i++) {
        manager = managers[i];
        if (manager instanceof X509ExtendedKeyManager) {
            managers[i] = new TrackingExtendedKeyManager((X509ExtendedKeyManager)manager);
        } else if (manager instanceof X509KeyManager) {
            managers[i] = new TrackingKeyManager((X509KeyManager)manager);
        }
    }
    return managers;
}
 
Example #4
Source File: RestUtils.java    From huaweicloud-sdk-java-obs with Apache License 2.0 6 votes vote down vote up
private static SSLContext createSSLContext(KeyManager[] km, TrustManager[] tm, String provider) throws Exception {
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLSv1.2", provider);
    } catch (Exception e) {
        try {
            sslContext = SSLContext.getInstance("TLSv1.1", provider);
        } catch (Exception ex) {
            try {
                sslContext = SSLContext.getInstance("TLSv1.0", provider);
            } catch (Exception exx) {
                sslContext = SSLContext.getInstance("TLS", provider);
            }
        }
    }
    sslContext.init(km, tm, new SecureRandom());
    return sslContext;
}
 
Example #5
Source File: SslContextFactory.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a SSLContext instance using the given information.
 *
 * @param truststore the full path to the truststore
 * @param truststorePasswd the truststore password
 * @param truststoreType the type of truststore (e.g., PKCS12, JKS)
 * @param protocol the protocol to use for the SSL connection
 *
 * @return a SSLContext instance
 * @throws java.security.KeyStoreException if any issues accessing the keystore
 * @throws java.io.IOException for any problems loading the keystores
 * @throws java.security.NoSuchAlgorithmException if an algorithm is found to be used but is unknown
 * @throws java.security.cert.CertificateException if there is an issue with the certificate
 * @throws java.security.UnrecoverableKeyException if the key is insufficient
 * @throws java.security.KeyManagementException if unable to manage the key
 */
public static SSLContext createTrustSslContext(
        final String truststore, final char[] truststorePasswd, final String truststoreType, final String protocol)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, KeyManagementException {

    // prepare the truststore
    final KeyStore trustStore = KeyStoreUtils.getTrustStore(truststoreType);
    try (final InputStream trustStoreStream = new FileInputStream(truststore)) {
        trustStore.load(trustStoreStream, truststorePasswd);
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    // initialize the ssl context
    final SSLContext ctx = SSLContext.getInstance(protocol);
    ctx.init(new KeyManager[0], trustManagerFactory.getTrustManagers(), new SecureRandom());

    return ctx;

}
 
Example #6
Source File: SSLUtils.java    From ssltest with Apache License 2.0 6 votes vote down vote up
/**
     * Creates an SSLSocketFactory that supports only the specified protocols
     * and ciphers.
     */
    public static SSLSocketFactory getSSLSocketFactory(String protocol,
                                                       String[] sslEnabledProtocols,
                                                       String[] sslCipherSuites,
                                                       SecureRandom random,
                                                       TrustManager[] tms,
                                                       KeyManager[] kms)
        throws NoSuchAlgorithmException, KeyManagementException
    {
        SSLContext sc = SSLContext.getInstance(protocol);

//        System.out.println("Wanted protocol: " + protocol);
//        System.out.println("Got protocol:    " + sc.getProtocol());

        sc.init(kms, tms, random);

        SSLSocketFactory sf = sc.getSocketFactory();

        if(null != sslEnabledProtocols
           || null != sslCipherSuites)
            sf = new CustomSSLSocketFactory(sf,
                                            sslEnabledProtocols,
                                            sslCipherSuites);

        return sf;
    }
 
Example #7
Source File: BouncyCastleSslEngineSource.java    From PowerTunnel with MIT License 6 votes vote down vote up
private SSLContext createServerContext(String commonName,
        SubjectAlternativeNameHolder subjectAlternativeNames)
        throws GeneralSecurityException, IOException,
        OperatorCreationException {

    MillisecondsDuration duration = new MillisecondsDuration();

    KeyStore ks = CertificateHelper.createServerCertificate(commonName,
            subjectAlternativeNames, authority, caCert, caPrivKey);
    KeyManager[] keyManagers = CertificateHelper.getKeyManagers(ks,
            authority);

    SSLContext result = CertificateHelper.newServerContext(keyManagers);

    LOG.info("Impersonated {} in {}ms", commonName, duration);
    return result;
}
 
Example #8
Source File: NetworkTools.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public static SSLSocketFactory DefaultSSLSocketFactory() {
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream keyStoreFile = new FileInputStream(new File(SystemTools.keystore()));
        String keyStorePassword = SystemTools.keystorePassword();
        keyStore.load(keyStoreFile, keyStorePassword.toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, keyStorePassword.toCharArray());
        KeyManager[] keyManagers = kmf.getKeyManagers();

        SSLContext ctx = SSLContext.getInstance(CommonValues.HttpsProtocal);
        ctx.init(keyManagers, null, new SecureRandom());

        return ctx.getSocketFactory();
    } catch (Exception e) {
        logger.debug(e.toString());
        return AppVariables.defaultSSLSocketFactory;
    }

}
 
Example #9
Source File: SSLKeyStoreLoader.java    From tessera with Apache License 2.0 6 votes vote down vote up
static KeyManager[] fromJksKeyStore(Path keyStoreFile, char[] keyStorePassword)
        throws NoSuchAlgorithmException, IOException, KeyStoreException, CertificateException,
                UnrecoverableKeyException {

    final KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE);

    try (InputStream in = Files.newInputStream(keyStoreFile)) {
        keyStore.load(in, keyStorePassword);
    }

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

    return keyManagerFactory.getKeyManagers();
}
 
Example #10
Source File: KeyStoreUtil.java    From browserup-proxy with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve the KeyManagers for the specified KeyStore.
 *
 * @param keyStore            the KeyStore to retrieve KeyManagers from
 * @param keyStorePassword    the KeyStore password
 * @param keyManagerAlgorithm key manager algorithm to use, or null to use the system default
 * @param provider            JCA provider to use, or null to use the system default
 * @return KeyManagers for the specified KeyStore
 */
public static KeyManager[] getKeyManagers(KeyStore keyStore, String keyStorePassword, String keyManagerAlgorithm, String provider) {
    if (keyManagerAlgorithm == null) {
        keyManagerAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    }

    try {
        KeyManagerFactory kmf;
        if (provider == null) {
            kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
        } else {
            kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm, provider);
        }

        kmf.init(keyStore, keyStorePassword.toCharArray());

        return kmf.getKeyManagers();
    } catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | NoSuchProviderException e) {
        throw new KeyStoreAccessException("Unable to get KeyManagers for KeyStore", e);
    }
}
 
Example #11
Source File: JSSEServer.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
JSSEServer(CipherTestUtils cipherTest, int serverPort,
        String protocol, String cipherSuite) throws Exception {
    super(cipherTest);
    this.serverPort = serverPort;
    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(new KeyManager[]{cipherTest.getServerKeyManager()},
            new TrustManager[]{cipherTest.getServerTrustManager()},
            CipherTestUtils.secureRandom);
    SSLServerSocketFactory factory =
            (SSLServerSocketFactory)serverContext.getServerSocketFactory();
    serverSocket =
            (SSLServerSocket) factory.createServerSocket(serverPort);
    serverSocket.setEnabledProtocols(protocol.split(","));
    serverSocket.setEnabledCipherSuites(cipherSuite.split(","));

    CipherTestUtils.printInfo(serverSocket);
}
 
Example #12
Source File: ApplicationKeyManagerFactoryTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testCancelledPasswordOnSetCertificate() throws Exception {

	assertNull(ApplicationKeyManagerFactory.getKeyStore());
	ApplicationKeyManagerFactory instance = ApplicationKeyManagerFactory.getInstance();
	KeyManager[] keyManagers = instance.getKeyManagers();
	assertEquals(1, keyManagers.length);
	assertTrue("", keyManagers[0] instanceof X509ExtendedKeyManager);
	X509ExtendedKeyManager keyManager = (X509ExtendedKeyManager) keyManagers[0];

	// verify that no certs are installed
	assertNull(keyManager.getCertificateChain(ALIAS));
	assertNull(keyManager.getClientAliases("RSA", null));

	passwordProvider.cancelNextEntry();

	ApplicationKeyManagerFactory.setKeyStore(keystoreFile.getAbsolutePath(), false);

	// verify that no certs are installed
	assertEquals(null, ApplicationKeyManagerFactory.getKeyStore());
	assertNull(keyManager.getCertificateChain(ALIAS));
	assertNull(keyManager.getClientAliases("RSA", null));
}
 
Example #13
Source File: JSSEServer.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
JSSEServer(CipherTestUtils cipherTest, int serverPort,
        String protocol, String cipherSuite) throws Exception {
    super(cipherTest);
    this.serverPort = serverPort;
    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(new KeyManager[]{cipherTest.getServerKeyManager()},
            new TrustManager[]{cipherTest.getServerTrustManager()},
            CipherTestUtils.secureRandom);
    SSLServerSocketFactory factory =
            (SSLServerSocketFactory)serverContext.getServerSocketFactory();
    serverSocket =
            (SSLServerSocket) factory.createServerSocket(serverPort);
    serverSocket.setEnabledProtocols(protocol.split(","));
    serverSocket.setEnabledCipherSuites(cipherSuite.split(","));

    CipherTestUtils.printInfo(serverSocket);
}
 
Example #14
Source File: BouncyCastleSslEngineSource.java    From CapturePacket with MIT License 6 votes vote down vote up
private SSLContext createServerContext(String commonName,
        SubjectAlternativeNameHolder subjectAlternativeNames)
        throws GeneralSecurityException, IOException,
        OperatorCreationException {

    MillisecondsDuration duration = new MillisecondsDuration();

    KeyStore ks = CertificateHelper.createServerCertificate(commonName,
            subjectAlternativeNames, authority, caCert, caPrivKey);
    KeyManager[] keyManagers = CertificateHelper.getKeyManagers(ks,
            authority);

    SSLContext result = CertificateHelper.newServerContext(keyManagers);

    LOG.info("Impersonated {} in {}ms", commonName, duration);
    return result;
}
 
Example #15
Source File: HttpsUtils.java    From styT with Apache License 2.0 6 votes vote down vote up
public static SSLParams getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password) {
    SSLParams sslParams = new SSLParams();
    try {
        TrustManager[] trustManagers = prepareTrustManager(certificates);
        KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        X509TrustManager trustManager = null;
        if (trustManagers != null) {
            trustManager = new MyTrustManager(chooseTrustManager(trustManagers));
        } else {
            trustManager = new UnSafeTrustManager();
        }
        sslContext.init(keyManagers, new TrustManager[]{trustManager}, null);
        sslParams.sSLSocketFactory = sslContext.getSocketFactory();
        sslParams.trustManager = trustManager;
        return sslParams;
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw new AssertionError(e);
    }
}
 
Example #16
Source File: HttpWebConnectionTruststoreTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if an error occurs
 */
@Before
public void setUp() throws Exception {
    final URL url = getClass().getClassLoader().getResource("self-signed-cert.keystore");
    final KeyStore keystore = KeyStore.getInstance("jks");
    final char[] pwd = "nopassword".toCharArray();
    keystore.load(url.openStream(), pwd);

    final TrustManagerFactory trustManagerFactory = createTrustManagerFactory();
    trustManagerFactory.init(keystore);
    final TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    final KeyManagerFactory keyManagerFactory = createKeyManagerFactory();
    keyManagerFactory.init(keystore, pwd);
    final KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    final SSLContext serverSSLContext = SSLContext.getInstance("TLS");
    serverSSLContext.init(keyManagers, trustManagers, null);

    localServer_ = new LocalTestServer(serverSSLContext);
    localServer_.start();
}
 
Example #17
Source File: HttpsUtils.java    From DoraemonKit 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 #18
Source File: AbstractServer.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build key managers from keystore file.
 *
 * @return key managers
 * @throws CertificateException     on error
 * @throws NoSuchAlgorithmException on error
 * @throws IOException              on error
 * @throws KeyStoreException        on error
 */
protected KeyManager[] getKeyManagers() throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException, UnrecoverableKeyException {
    String keystoreFile = Settings.getProperty("davmail.ssl.keystoreFile");
    if (keystoreFile == null || keystoreFile.length() == 0) {
        return null;
    }
    try (FileInputStream keyStoreInputStream = new FileInputStream(keystoreFile)) {
        KeyStore keystore = KeyStore.getInstance(Settings.getProperty("davmail.ssl.keystoreType"));
        keystore.load(keyStoreInputStream, Settings.getCharArrayProperty("davmail.ssl.keystorePass"));

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keystore, Settings.getCharArrayProperty("davmail.ssl.keyPass"));
        return kmf.getKeyManagers();
    }
}
 
Example #19
Source File: ApnsPushService.java    From p2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public ApnsPushService() {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    Adapter.register(gsonBuilder);
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);

    final SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(new KeyManager[]{new ClientCertificateKeyManager()}, null, null);
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new AssertionError(e);
    }

    final X509TrustManager trustManager = TrustManager.getDefault();
    if (trustManager == null) {
        throw new AssertionError("Unable to find default trust manager");
    }
    final OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
    okHttpBuilder.sslSocketFactory(sslContext.getSocketFactory(), trustManager);

    ApnsConfiguration configuration = Configuration.getInstance().getApnsConfiguration();

    final Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
    if (configuration != null && configuration.isSandbox()) {
        retrofitBuilder.baseUrl(SANDBOX_BASE_URL);
    } else {
        retrofitBuilder.baseUrl(BASE_URL);
    }
    retrofitBuilder.addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()));
    retrofitBuilder.client(okHttpBuilder.build());

    final Retrofit retrofit = retrofitBuilder.build();

    this.httpInterface = retrofit.create(ApnsHttpInterface.class);
}
 
Example #20
Source File: HtmlUnitSSLConnectionSocketFactory.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private static KeyManager[] getKeyManagers(final WebClientOptions options) {
    if (options.getSSLClientCertificateStore() == null) {
        return null;
    }
    try {
        final KeyStore keyStore = options.getSSLClientCertificateStore();
        final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, options.getSSLClientCertificatePassword());
        return keyManagerFactory.getKeyManagers();
    }
    catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #21
Source File: BouncyCastleSslEngineSource.java    From CapturePacket with MIT License 5 votes vote down vote up
private void initializeSSLContext() throws GeneralSecurityException,
        IOException {
    KeyStore ks = loadKeyStore();
    caCert = ks.getCertificate(authority.alias());
    caPrivKey = (PrivateKey) ks.getKey(authority.alias(),
            authority.password());

    TrustManager[] trustManagers;
    if (trustAllServers) {
        trustManagers = InsecureTrustManagerFactory.INSTANCE
                .getTrustManagers();
    } else {
        trustManagers = new TrustManager[] { new MergeTrustManager(ks) };
    }

    KeyManager[] keyManagers;
    if (sendCerts) {
        keyManagers = CertificateHelper.getKeyManagers(ks, authority);
    } else {
        keyManagers = new KeyManager[0];
    }

    sslContext = CertificateHelper.newClientContext(keyManagers,
            trustManagers);
    SSLEngine sslEngine = sslContext.createSSLEngine();
    if (!tryHostNameVerificationJava7(sslEngine)) {
        LOG.warn("Host Name Verification is not supported, causes insecure HTTPS connection to upstream servers.");
    }
}
 
Example #22
Source File: CertificateHelper.java    From CapturePacket with MIT License 5 votes vote down vote up
public static SSLContext newServerContext(KeyManager[] keyManagers)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        KeyManagementException {
    SSLContext result = newSSLContext();
    SecureRandom random = new SecureRandom();
    random.setSeed(System.currentTimeMillis());
    result.init(keyManagers, null, random);
    return result;
}
 
Example #23
Source File: CertificateHelper.java    From CapturePacket with MIT License 5 votes vote down vote up
public static SSLContext newClientContext(KeyManager[] keyManagers,
        TrustManager[] trustManagers) throws NoSuchAlgorithmException,
        KeyManagementException, NoSuchProviderException {
    SSLContext result = newSSLContext();
    result.init(keyManagers, trustManagers, null);
    return result;
}
 
Example #24
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 #25
Source File: HttpUtil.java    From codewind-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private static SSLContext getTrustAllCertsContext(X509TrustManager manager) {
	try {
		SSLContext context = SSLContext.getInstance("TLSv1.2");
		context.init(new KeyManager[0], new TrustManager[] { manager }, new SecureRandom());
		return context;
	} catch (Exception e) {
		Logger.logError("An error occurred creating a trust all certs context", e);
	}
	return null;
}
 
Example #26
Source File: CertificateHelpers.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
public static KeyManager[] createKeyManagers(final TlsCertificateDefinition certToPresent)
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {
  if (certToPresent == null) {
    return null;
  }

  final String password = certToPresent.getPassword();

  final KeyStore clientCertStore = loadP12KeyStore(certToPresent.getPkcs12File(), password);

  final KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
  kmf.init(clientCertStore, password.toCharArray());
  return kmf.getKeyManagers();
}
 
Example #27
Source File: CertificateHelper.java    From PowerTunnel with MIT License 5 votes vote down vote up
public static SSLContext newServerContext(KeyManager[] keyManagers)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        KeyManagementException {
    SSLContext result = newSSLContext();
    SecureRandom random = new SecureRandom();
    random.setSeed(System.currentTimeMillis());
    result.init(keyManagers, null, random);
    return result;
}
 
Example #28
Source File: ServerConnectionManager.java    From hop with Apache License 2.0 5 votes vote down vote up
private ServerConnectionManager() {
  if ( needToInitializeSSLContext() ) {
    try {
      SSLContext context = SSLContext.getInstance( SSL );
      context.init( new KeyManager[ 0 ], new X509TrustManager[] { getDefaultTrustManager() }, new SecureRandom() );
      SSLContext.setDefault( context );
    } catch ( Exception e ) {
      //log.logError( "Default SSL context hasn't been initialized", e );
    }
  }
  manager = new PoolingHttpClientConnectionManager();
  manager.setDefaultMaxPerRoute( 100 );
  manager.setMaxTotal( 200 );
}
 
Example #29
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 #30
Source File: SSLEngineFactory.java    From NetBare with MIT License 5 votes vote down vote up
private SSLContext createContext(KeyManager[] keyManagers, TrustManager[] trustManagers)
        throws NoSuchAlgorithmException,
        KeyManagementException {
    SSLContext result = createSSLContext();
    SecureRandom random = new SecureRandom();
    random.setSeed(System.currentTimeMillis() + 1);
    result.init(keyManagers, trustManagers, random);
    return result;
}