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

The following examples show how to use javax.net.ssl.SSLContext#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: EmptyCertificateAuthorities.java    From openjdk-jdk9 with GNU General Public License v2.0 7 votes vote down vote up
private SSLServerSocketFactory getSSLServerSF() throws Exception {

        char [] password =
            System.getProperty("javax.net.ssl.keyStorePassword").toCharArray();
        String keyFilename = System.getProperty("javax.net.ssl.keyStore");

        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(keyFilename), password);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, password);

        KeyManager[] kms = kmf.getKeyManagers();
        TrustManager[] tms = new MyX509TM[] {new MyX509TM()};

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(kms, tms, null);

        return ctx.getServerSocketFactory();
    }
 
Example 2
Source File: Client.java    From omise-java with MIT License 6 votes vote down vote up
/**
 * Returns a new {@link OkHttpClient} to use for performing {@link Request}(s). Override this to customize the HTTP
 * client. This method will be called once during construction and the result will be cached internally.
 * <p>
 * It is generally a good idea to implement this by adding to the builder created from
 * <code>super.buildHttpClient(config).newBuilder()</code> so that all configurations are properly applied and SSL
 * certificates are pinned.
 * </p>
 *
 * @param config A {@link Config} object built from constructor parameters.
 * @return A new {@link OkHttpClient} object for connecting to the Omise API.
 * @throws ClientException if client configuration fails (e.g. when TLSv1.2 is not supported)
 */
protected OkHttpClient buildHttpClient(Config config) throws ClientException {
    SSLContext sslContext;
    X509TrustManager trustManager;
    try {
        sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, null, null);

        trustManager = getX509TrustManager();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new ClientException(e);
    }

    ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
            .tlsVersions(TlsVersion.TLS_1_2)
            .build();

    return new OkHttpClient.Builder()
            .sslSocketFactory(sslContext.getSocketFactory(), trustManager)
            .addInterceptor(new Configurer(config))
            .connectionSpecs(Collections.singletonList(spec))
            .readTimeout(60, TimeUnit.SECONDS)
            .build();
}
 
Example 3
Source File: PandroidModule.java    From pandroid with Apache License 2.0 6 votes vote down vote up
protected SSLContext getSslContext(List<KeyManager> keyManagers, List<TrustManager> trustManagers, LogWrapper logWrapper) {
    KeyManager[] keyManagersArray = null;
    if (keyManagers != null && keyManagers.size() > 0) {
        keyManagersArray = new KeyManager[keyManagers.size()];
        keyManagers.toArray(keyManagersArray);
    }
    TrustManager[] trustManagersArray = null;
    if (trustManagers != null && trustManagers.size() > 0) {
        trustManagersArray = new TrustManager[trustManagers.size()];
        trustManagers.toArray(trustManagersArray);
    }
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagersArray, trustManagersArray, null);
        return sslContext;
    } catch (Exception e) {
        logWrapper.e(TAG, e);
    }
    return null;
}
 
Example 4
Source File: JSSEServer.java    From openjdk-jdk8u-backup 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 5
Source File: RequestRunner.java    From openshift-elasticsearch-plugin with Apache License 2.0 6 votes vote down vote up
protected final OkHttpClient getHttpClient() throws Exception {
    File ksFile = new File(keyStore);
    KeyStore trusted = KeyStore.getInstance("JKS");
    FileInputStream in = new FileInputStream(ksFile);
    trusted.load(in, password.toCharArray());
    in.close();
    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManagerFactory trustManagerFactory = InsecureTrustManagerFactory.INSTANCE;
    X509TrustManager trustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    OkHttpClient client = new okhttp3.OkHttpClient.Builder()
            .sslSocketFactory(sslContext.getSocketFactory(), trustManager)
            .readTimeout(1, TimeUnit.MINUTES)
            .writeTimeout(1, TimeUnit.MINUTES)
            .build();
    return client;
}
 
Example 6
Source File: NanoHTTPD.java    From AndroidHttpServer with MIT 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 {
    SSLServerSocketFactory res = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(loadedKeyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(loadedKeyFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        res = ctx.getServerSocketFactory();
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
    return res;
}
 
Example 7
Source File: TlsInit.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static void init() throws GeneralSecurityException {
  System.err.println("***** ONLY FOR TEST, DO NOT USE IT IN PRODUCTION ENVIRONMENT ******");
  TrustManager[] trustManagers = {new InternX509TrustManager()};
  SSLContext sc = SSLContext.getInstance("SSL");
  sc.init(null, trustManagers, new SecureRandom());
  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

  oldHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
  LOG.info("Register me as DefaultHostnameVerifier, and backup the old one {}",
      oldHostnameVerifier);
  HttpsURLConnection.setDefaultHostnameVerifier(SdkHostnameVerifier.INSTANCE);
}
 
Example 8
Source File: ApacheHttpClient.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
private SSLContext getSslContext(AttributeMap standardOptions) {
    Validate.isTrue(standardOptions.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER) == null ||
                    !standardOptions.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES),
                    "A TlsTrustManagerProvider can't be provided if TrustAllCertificates is also set");

    TrustManager[] trustManagers = null;
    if (standardOptions.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER) != null) {
        trustManagers = standardOptions.get(SdkHttpConfigurationOption.TLS_TRUST_MANAGERS_PROVIDER).trustManagers();
    }

    if (standardOptions.get(SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES)) {
        log.warn(() -> "SSL Certificate verification is disabled. This is not a safe setting and should only be "
                       + "used for testing.");
        trustManagers = trustAllTrustManager();
    }

    TlsKeyManagersProvider provider = standardOptions.get(SdkHttpConfigurationOption.TLS_KEY_MANAGERS_PROVIDER);
    KeyManager[] keyManagers = provider.keyManagers();

    try {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        // http://download.java.net/jdk9/docs/technotes/guides/security/jsse/JSSERefGuide.html
        sslcontext.init(keyManagers, trustManagers, null);
        return sslcontext;
    } catch (final NoSuchAlgorithmException | KeyManagementException ex) {
        throw new SSLInitializationException(ex.getMessage(), ex);
    }
}
 
Example 9
Source File: TestTlsSettings.java    From swim with Apache License 2.0 5 votes vote down vote up
public static TlsSettings tlsSettings() {
  if (tlsSettings == null) {
    try {
      final KeyStore keystore = KeyStore.getInstance("jks");
      final InputStream keystoreStream = TestTlsSettings.class.getResourceAsStream("/keystore.jks");
      final char[] keystorePassword = "default".toCharArray();
      try {
        keystore.load(keystoreStream, keystorePassword);
      } finally {
        keystoreStream.close();
      }

      final KeyStore cacerts = KeyStore.getInstance("jks");
      final InputStream cacertsStream = TestTlsSettings.class.getResourceAsStream("/cacerts.jks");
      final char[] cacertsPassword = "default".toCharArray();
      try {
        cacerts.load(cacertsStream, cacertsPassword);
      } finally {
        cacertsStream.close();
      }

      final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
      keyManagerFactory.init(keystore, keystorePassword);

      final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
      trustManagerFactory.init(cacerts);

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

      tlsSettings = new TlsSettings(sslContext, ClientAuth.NONE, null, null);
    } catch (IOException | GeneralSecurityException error) {
      throw new StationException(error);
    }
  }
  return tlsSettings;
}
 
Example 10
Source File: PEMCertInfo.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void applyTo(HttpClientFactory.Builder builder) {

    if (java.security.Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        java.security.Security.addProvider(new BouncyCastleProvider());
    }

    try (
            FileInputStream clientCert = new FileInputStream(new File(clientCertPath));
            FileInputStream key = new FileInputStream(new File(keyPath));
            FileInputStream certificateAuthoritiies = new FileInputStream(new File(caPath))
    ) {
        KeyStore keyStore = PemReader.loadKeyStore(clientCert, key, Optional.ofNullable(keyPassphrase));
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyPassphrase.toCharArray());

        KeyStore trustStore = PemReader.loadTrustStore(certificateAuthoritiies);

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

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

        // TODO: add support for hostname verification modes
        builder.withSslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        builder.withHttpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }

}
 
Example 11
Source File: HttpsUtils.java    From UltimateAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * Build SSLSocketFactory using certificate InputStream
 * @param certificates
 * @param key
 * @param keyPassword
 * @return
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws KeyManagementException
 * @throws CertificateException
 * @throws IOException
 */
public static SSLSocketFactory getSSLSocketFactory(InputStream certificates, InputStream key, String keyPassword) throws NoSuchAlgorithmException,
        KeyStoreException, KeyManagementException, CertificateException, IOException {


    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    InputStream caInput = new BufferedInputStream(certificates);
    Certificate ca;
    try {
        ca = cf.generateCertificate(caInput);
    } finally {
        caInput.close();
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    KeyManagerFactory kmf = null;
    if (key != null && keyPassword != null) {
        kmf = getKeyManagerFactory(key, keyPassword);
    }
    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext contexts = SSLContext.getInstance("TLS");
    contexts.init(kmf == null ? null : kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    return contexts.getSocketFactory();

}
 
Example 12
Source File: SSLContextFactory.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Create a {@link SSLContext} instance
 *
 * @param keyStoreFile a p12 or jks file depending on key store type
 * @param keyStorePassword password to access the key store
 * @param keyStoreType type of key store
 * @param trustStoreFile a jks file
 * @param trustStorePassword password to access the trust store
 */
public static SSLContext createInstance(File keyStoreFile, String keyStorePassword, String keyStoreType, File trustStoreFile,
    String trustStorePassword) {
  if (!keyStoreType.equalsIgnoreCase(P12_STORE_TYPE_NAME) && !keyStoreType.equalsIgnoreCase(JKS_STORE_TYPE_NAME)) {
    throw new IllegalArgumentException("Unsupported keyStoreType: " + keyStoreType);
  }

  try {
    // Load KeyStore
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(toInputStream(keyStoreFile), keyStorePassword.toCharArray());

    // Load TrustStore
    KeyStore trustStore = KeyStore.getInstance(JKS_STORE_TYPE_NAME);
    trustStore.load(toInputStream(trustStoreFile), trustStorePassword.toCharArray());

    // Set KeyManger from keyStore
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(DEFAULT_ALGORITHM);
    kmf.init(keyStore, keyStorePassword.toCharArray());

    // Set TrustManager from trustStore
    TrustManagerFactory trustFact = TrustManagerFactory.getInstance(DEFAULT_ALGORITHM);
    trustFact.init(trustStore);

    // Set Context to TLS and initialize it
    SSLContext sslContext = SSLContext.getInstance(DEFAULT_PROTOCOL);
    sslContext.init(kmf.getKeyManagers(), trustFact.getTrustManagers(), null);

    return sslContext;
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 13
Source File: RetrofitManager.java    From QuickDevFramework with Apache License 2.0 5 votes vote down vote up
/**
 * https TrustAll 配置,如果需要抓包的话可以打开此配置,否则没有必要
 * */
public static void configTrustAll(OkHttpClient.Builder builder) {
    final TrustManager[] trustAllCerts = new TrustManager[] {SSLHelper.createTrustAllTrustManager()};
    try {
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);
        builder.hostnameVerifier((hostname, session) -> true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 14
Source File: ExtendedHttpClientBuilder.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private static SSLContext setupSslContext() {
  try {
    X509TrustManager trustManager = new TrustManagerBuilder()
        .addBuiltinCertificates()
        .addFromResourceDirectory("/certificates")
        .build();

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new X509TrustManager[] { trustManager }, null);
    return context;
  } catch (Exception e) {
    log.error("Failed to build custom SSL context, using default one.", e);
    return SSLContexts.createDefault();
  }
}
 
Example 15
Source File: SSLEngineTestCase.java    From openjdk-jdk9 with GNU General Public License v2.0 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 16
Source File: Client.java    From ForPDA with GNU General Public License v3.0 5 votes vote down vote up
private SSLContext getNewSslContext() {
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, null, null);
    } catch (GeneralSecurityException e) {
        throw new AssertionError(); // The system has no TLS. Just give up.
    }
    return sslContext;
}
 
Example 17
Source File: NetworkUtils.java    From letv with Apache License 2.0 4 votes vote down vote up
public static final SSLSocketFactory getSSLSocketFactory(PinningInfoProvider provider) throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[]{new PinningTrustManager(new SystemKeyStore(provider.getKeyStoreStream(), provider.getKeyStorePassword()), provider)}, null);
    return sslContext.getSocketFactory();
}
 
Example 18
Source File: SelfSignedSocketFactory.java    From griffin with Apache License 2.0 4 votes vote down vote up
private SelfSignedSocketFactory() throws Exception {
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, new TrustManager[]{new NoopTrustManager()}, null);
    sf = ctx.getSocketFactory();
}
 
Example 19
Source File: TLSSocketFactory.java    From crazyflie-android-client with GNU General Public License v2.0 4 votes vote down vote up
public TLSSocketFactory() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, null, null);
    internalSSLSocketFactory = context.getSocketFactory();
}
 
Example 20
Source File: SslRedirectHandler.java    From AndroidPirateBox with MIT License 4 votes vote down vote up
@Override
public boolean init(Server server, String prefix) {
	try {
		this.prefix = prefix;
		this.server = server;
		
		preferences = PreferenceManager.getDefaultSharedPreferences(PirateBoxService.getService());
		
		
		// Only initializes if SSL redirect is enabled in settings
		/*
		if(!preferences.getBoolean(Constants.PREF_SSL_REDIRECT, false)) {
			return false;
		}
		*/

		PORT = Integer.valueOf(PirateBoxService.getService().getPawServer().port) + 1;
		KEYSTORE = server.props.getProperty(prefix + CERT, PirateBoxService.pawHome + "conf/certs/pawKeystore");
		
		netUtil = new NetworkUtil(PirateBoxService.getService());
		apIp = netUtil.getApIp(2000);

	
		SSLContext ctx = SSLContext.getInstance("TLS");

		KeyManagerFactory kmf = KeyManagerFactory
				.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		// BKS
		KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

		ks.load(new FileInputStream(KEYSTORE),
				PASSPHRASE.toCharArray());
		kmf.init(ks, PASSPHRASE.toCharArray());
		ctx.init(kmf.getKeyManagers(), null, null);

		SSLServerSocketFactory ssf = ctx.getServerSocketFactory();
		ssocket = ssf.createServerSocket(PORT);
		acceptThread = new AcceptThread();
		acceptThread.start();
		
		PirateBoxService.registerServiceListener(this);

		netUtil.redirectPort(NetworkUtil.IpTablesAction.IP_TABLES_ADD, apIp, NetworkUtil.PORT_HTTPS, PORT);
	} catch (Exception e) {
		e.printStackTrace();
		server.log(Server.LOG_ERROR, prefix, e.getMessage());
		return false;
	}

	return true;
}