javax.net.ssl.SSLContext Java Examples

The following examples show how to use javax.net.ssl.SSLContext. 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: ServerIdentityTest.java    From openjdk-jdk9 with GNU General Public License v2.0 7 votes vote down vote up
private static void initialize(String[] args) throws Exception {
    keystore = args[0];
    hostname = args[1];

    String password = "changeit";
    String keyFilename =
            System.getProperty("test.src", ".") + "/" + keystore;
    String trustFilename =
            System.getProperty("test.src", ".") + "/" + keystore;

    System.setProperty("javax.net.ssl.keyStore", keyFilename);
    System.setProperty("javax.net.ssl.keyStorePassword", password);
    System.setProperty("javax.net.ssl.trustStore", trustFilename);
    System.setProperty("javax.net.ssl.trustStorePassword", password);

    context = SSLContext.getDefault();
    HttpsURLConnection.setDefaultSSLSocketFactory(
            context.getSocketFactory());
}
 
Example #2
Source File: URLType.java    From webdsl with Apache License 2.0 7 votes vote down vote up
protected static void setAcceptAllVerifier(HttpsURLConnection connection) throws NoSuchAlgorithmException, KeyManagementException {

        // Create the socket factory.
        // Reusing the same socket factory allows sockets to be
        // reused, supporting persistent connections.
        if( null == sslSocketFactory) {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, ALL_TRUSTING_TRUST_MANAGER, new java.security.SecureRandom());
            sslSocketFactory = sc.getSocketFactory();
        }

        connection.setSSLSocketFactory(sslSocketFactory);

        // Since we may be using a cert with a different name, we need to ignore
        // the hostname as well.
        connection.setHostnameVerifier(ALL_TRUSTING_HOSTNAME_VERIFIER);
    }
 
Example #3
Source File: AthenzCredentialsService.java    From vespa with Apache License 2.0 6 votes vote down vote up
AthenzCredentials updateCredentials(SignedIdentityDocument document, SSLContext sslContext) {
    KeyPair newKeyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA);
    Pkcs10Csr csr = csrGenerator.generateInstanceCsr(
            tenantIdentity,
            document.providerUniqueId(),
            document.ipAddresses(),
            newKeyPair);

    try (ZtsClient ztsClient = new DefaultZtsClient(ztsEndpoint, sslContext)) {
        InstanceIdentity instanceIdentity =
                ztsClient.refreshInstance(
                        configserverIdentity,
                        tenantIdentity,
                        document.providerUniqueId().asDottedString(),
                        csr);
        X509Certificate certificate = instanceIdentity.certificate();
        writeCredentialsToDisk(newKeyPair.getPrivate(), certificate, document);
        return new AthenzCredentials(certificate, newKeyPair, document);
    }
}
 
Example #4
Source File: Link.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static SSLContext initManagementSSLContext(final CAService caService) throws GeneralSecurityException, IOException {
    if (caService == null) {
        throw new CloudRuntimeException("CAService is not available to load/get management server keystore");
    }
    final KeyStore ks = caService.getManagementKeyStore();
    char[] passphrase = caService.getKeyStorePassphrase();

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);
    final TrustManager[] tms = tmf.getTrustManagers();

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

    final SSLContext sslContext = SSLUtils.getSSLContext();
    sslContext.init(kmf.getKeyManagers(), tms, new SecureRandom());
    return sslContext;
}
 
Example #5
Source File: HttpClientFactory.java    From hsac-fitnesse-fixtures with Apache License 2.0 6 votes vote down vote up
protected SSLContext generateSSLContext() {
    SSLContextBuilder contextBuilder = SSLContexts.custom();
    try {
        if (getTrustStoreFile() != null) {
            contextBuilder.loadTrustMaterial(getTrustStoreFile(), getTrustStorePassword(), getTrustStrategy());
        }

        if (getKeyStoreFile() != null) {
            contextBuilder.loadKeyMaterial(getKeyStoreFile(), getKeyStorePassword(), getKeyPassword(), getPrivateKeyStrategy());
        }

        return contextBuilder.build();
    } catch (GeneralSecurityException | IOException e) {
        throw new RuntimeException("Unable to configure SSL", e);
    }
}
 
Example #6
Source File: HandshakeWithClient.java    From flashback with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public Future execute(ChannelMediator channelMediator, InetSocketAddress remoteAddress) {

  //dynamically create SSLEngine based on CN and SANs
  LOG.debug("Starting client to proxy connection handshaking");
  try {
    //TODO: if connect request only contains ip address, we need get either CA
    //TODO: or SANS from server response
    KeyStore keyStore = _certificateKeyStoreFactory.create(remoteAddress.getHostName(), new ArrayList<>());
    SSLContext sslContext = SSLContextGenerator.createClientContext(keyStore, _certificateAuthority.getPassPhrase());
    return channelMediator.handshakeWithClient(sslContext.createSSLEngine());
  } catch (NoSuchAlgorithmException | KeyStoreException | IOException | CertificateException | OperatorCreationException
      | NoSuchProviderException | InvalidKeyException | SignatureException | KeyManagementException | UnrecoverableKeyException e) {
    throw new RuntimeException("Failed to create server identity certificate", e);
  }
}
 
Example #7
Source File: VariableSSLConfig.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "docker-java uses runtime exceptions")
@Override
public SSLContext getSSLContext() throws KeyManagementException, UnrecoverableKeyException,
        NoSuchAlgorithmException, KeyStoreException {
    try {
        Security.addProvider(new BouncyCastleProvider());

        SslConfigurator sslConfig = SslConfigurator.newInstance(true);
        sslConfig.securityProtocol("TLSv1.2");

        // add keystore
        sslConfig.keyStore(createKeyStore(keypem, certpem));
        sslConfig.keyStorePassword("docker"); // ??

        if (isNotBlank(capem)) {
            sslConfig.trustStore(createTrustStore(capem));
        }

        return sslConfig.createSSLContext();
    } catch (Exception e) {
        throw new DockerClientException(e.getMessage(), e);
    }
}
 
Example #8
Source File: TransportSupportTest.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSslEngineFromJksStoreWithExplicitDisabledCiphersJDK() throws Exception {
    // Discover the default enabled ciphers
    TransportOptions options = createJksSslOptions();
    SSLEngine directEngine = createSSLEngineDirectly(options);
    String[] ciphers = directEngine.getEnabledCipherSuites();
    assertTrue("There were no initial ciphers to choose from!", ciphers.length > 0);

    // Pull out one to disable specifically
    String[] disabledCipher = new String[] { ciphers[ciphers.length - 1] };
    String[] trimmedCiphers = Arrays.copyOf(ciphers, ciphers.length - 1);
    options.setDisabledCipherSuites(disabledCipher);
    SSLContext context = TransportSupport.createJdkSslContext(options);
    SSLEngine engine = TransportSupport.createJdkSslEngine(null, context, options);

    // verify the option took effect
    assertNotNull(engine);
    assertArrayEquals("Enabled ciphers not as expected", trimmedCiphers, engine.getEnabledCipherSuites());
}
 
Example #9
Source File: TestUtils.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an SSLSocketFactory which contains {@code certChainFile} as its only root certificate.
 */
public static SSLSocketFactory newSslSocketFactoryForCa(Provider provider,
                                                        File certChainFile) throws Exception {
  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(null, null);
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  BufferedInputStream in = new BufferedInputStream(new FileInputStream(certChainFile));
  try {
    X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
    X500Principal principal = cert.getSubjectX500Principal();
    ks.setCertificateEntry(principal.getName("RFC2253"), cert);
  } finally {
    in.close();
  }

  // Set up trust manager factory to use our key store.
  TrustManagerFactory trustManagerFactory =
      TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(ks);
  SSLContext context = SSLContext.getInstance("TLS", provider);
  context.init(null, trustManagerFactory.getTrustManagers(), null);
  return context.getSocketFactory();
}
 
Example #10
Source File: HunterRequest.java    From Burp-Hunter with GNU General Public License v3.0 6 votes vote down vote up
public String notifyHunter(byte[] content) throws IOException {
    try {
        String request = new String(content);
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
        HttpClient httpclient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        HttpPost httpPost = new HttpPost("https://api"+hunterDomain.substring(hunterDomain.indexOf("."))+"/api/record_injection");
        String json = "{\"request\": \""+request.replace("\\", "\\\\").replace("\"", "\\\"").replace("\r\n", "\\n")+"\", \"owner_correlation_key\": \""+hunterKey+"\", \"injection_key\": \""+injectKey+"\"}";
        StringEntity entity = new StringEntity(json);
        entity.setContentType("applicaiton/json");
        httpPost.setEntity(entity);
        HttpResponse response = httpclient.execute(httpPost);
        String responseString = new BasicResponseHandler().handleResponse(response);
        return responseString;
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        
        Logger.getLogger(HunterRequest.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "Error Notifying Probe Server!";
}
 
Example #11
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 #12
Source File: TestUtils.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the ciphers preferred to use during tests. They may be chosen because they are widely
 * available or because they are fast. There is no requirement that they provide confidentiality
 * or integrity.
 *
 * @deprecated Not for public use
 */
@Deprecated
public static List<String> preferredTestCiphers() {
  String[] ciphers;
  try {
    ciphers = SSLContext.getDefault().getDefaultSSLParameters().getCipherSuites();
  } catch (NoSuchAlgorithmException ex) {
    throw new RuntimeException(ex);
  }
  List<String> ciphersMinusGcm = new ArrayList<>();
  for (String cipher : ciphers) {
    // The GCM implementation in Java is _very_ slow (~1 MB/s)
    if (cipher.contains("_GCM_")) {
      continue;
    }
    ciphersMinusGcm.add(cipher);
  }
  return Collections.unmodifiableList(ciphersMinusGcm);
}
 
Example #13
Source File: TestUtils.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an SSLSocketFactory which contains {@code certChainFile} as its only root certificate.
 *
 * @deprecated Not for public use
 */
@Deprecated
public static SSLSocketFactory newSslSocketFactoryForCa(Provider provider,
    File certChainFile) throws Exception {
  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(null, null);
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  X509Certificate cert = (X509Certificate) cf.generateCertificate(
      new BufferedInputStream(new FileInputStream(certChainFile)));
  X500Principal principal = cert.getSubjectX500Principal();
  ks.setCertificateEntry(principal.getName("RFC2253"), cert);

  // Set up trust manager factory to use our key store.
  TrustManagerFactory trustManagerFactory =
      TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(ks);
  SSLContext context = SSLContext.getInstance("TLS", provider);
  context.init(null, trustManagerFactory.getTrustManagers(), null);
  return context.getSocketFactory();
}
 
Example #14
Source File: SettingsBasedSSLConfigurator.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
public SSLConfig(SSLContext sslContext, String[] supportedProtocols, String[] supportedCipherSuites,
        HostnameVerifier hostnameVerifier, boolean hostnameVerificationEnabled, boolean trustAll,
        boolean startTlsEnabled, KeyStore effectiveTruststore, List<String> effectiveTruststoreAliases,
        KeyStore effectiveKeystore, char[] effectiveKeyPassword, String effectiveKeyAlias) {
    this.sslContext = sslContext;
    this.supportedProtocols = supportedProtocols;
    this.supportedCipherSuites = supportedCipherSuites;
    this.hostnameVerifier = hostnameVerifier;
    this.hostnameVerificationEnabled = hostnameVerificationEnabled;
    this.trustAll = trustAll;
    this.startTlsEnabled = startTlsEnabled;
    this.effectiveTruststore = effectiveTruststore;
    this.effectiveTruststoreAliases = effectiveTruststoreAliases;
    this.effectiveKeystore = effectiveKeystore;
    this.effectiveKeyPassword = effectiveKeyPassword;
    this.effectiveKeyAlias = effectiveKeyAlias;

    if (log.isDebugEnabled()) {
        log.debug("Created SSLConfig: " + this);
    }
}
 
Example #15
Source File: SecureSslContextFactory.java    From openAGV with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance of {@link SSLContext} for the server.
 *
 * @return The ssl context.
 * @throws IllegalStateException If the creation of the ssl context fails.
 */
public SSLContext createServerContext()
    throws IllegalStateException {
  SSLContext context = null;

  try {
    KeyStore ks = KeyStore.getInstance(sslParameterSet.getKeystoreType());
    ks.load(new FileInputStream(sslParameterSet.getKeystoreFile()),
            sslParameterSet.getKeystorePassword().toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_TRUST_MANAGEMENT_ALGORITHM);
    kmf.init(ks, sslParameterSet.getKeystorePassword().toCharArray());

    context = SSLContext.getInstance(SSL_CONTEXT_PROTOCOL);
    context.init(kmf.getKeyManagers(), null, null);

  }
  catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException
             | KeyManagementException | UnrecoverableKeyException ex) {
    throw new IllegalStateException("Error creating the server's ssl context", ex);
  }

  return context;
}
 
Example #16
Source File: IntegrationTestBase.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
private static Client createClientFromConfig(NiFiRegistryClientConfig registryClientConfig) {

        final ClientConfig clientConfig = new ClientConfig();
        clientConfig.register(jacksonJaxbJsonProvider());

        final ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig);

        final SSLContext sslContext = registryClientConfig.getSslContext();
        if (sslContext != null) {
            clientBuilder.sslContext(sslContext);
        }

        final HostnameVerifier hostnameVerifier = registryClientConfig.getHostnameVerifier();
        if (hostnameVerifier != null) {
            clientBuilder.hostnameVerifier(hostnameVerifier);
        }

        return clientBuilder.build();
    }
 
Example #17
Source File: DefaultSchemaRegistryClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
public DefaultSchemaRegistryClient(Map<String, ?> conf) {
    configuration = new Configuration(conf);
    login = SecurityUtils.initializeSecurityContext(conf);
    ClientConfig config = createClientConfig(conf);
    final boolean SSLEnabled = SecurityUtils.isHttpsConnection(conf);
    ClientBuilder clientBuilder = JerseyClientBuilder.newBuilder()
            .withConfig(config)
            .property(ClientProperties.FOLLOW_REDIRECTS, Boolean.TRUE);
    if (SSLEnabled) {
        SSLContext ctx;
        try {
            ctx = SecurityUtils.createSSLContext(conf, SSL_ALGORITHM);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        clientBuilder.sslContext(ctx);
    }
    client = clientBuilder.build();

    // get list of urls and create given or default UrlSelector.
    urlSelector = createUrlSelector();
    urlWithTargets = new ConcurrentHashMap<>();
}
 
Example #18
Source File: HttpClientConfig.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
@Bean
    @Primary
    @Autowired
    public HttpClient httpClientWithOutProxy(TrustManager[] trustAllCertificates, ExecutorService httpclientExecutorService) throws NoSuchAlgorithmException, KeyManagementException {
        SSLParameters sslParams = new SSLParameters();
        sslParams.setEndpointIdentificationAlgorithm("");
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCertificates, new SecureRandom());
        return HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
//                .sslParameters(sslParams)
//                .sslContext(sc)
                .connectTimeout(Duration.ofSeconds(30))
              //          .proxy(ProxySelector.of(new InetSocketAddress("127.0.0.1", 8888)))
                .executor(httpclientExecutorService)
                .followRedirects(HttpClient.Redirect.NEVER)
                .build();
    }
 
Example #19
Source File: TrustStoreImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public SSLContext getSSLContext() {
  SSLContext _sslcontext = this.sslcontext; // local variable allows concurrent removeTrustCertificate
  if (_sslcontext == null) {
    try {
      // the trusted key store may have asychronously changed when NXRM is clustered, reload the managed store used
      // for fallback so the context doesn't use stale key store
      this.managedTrustManager = getManagedTrustManager(keyStoreManager);
      _sslcontext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
      _sslcontext.init(keyManagers, trustManagers, DEFAULT_RANDOM);
      this.sslcontext = _sslcontext;
    }
    catch (Exception e) {
      log.debug("Could not create SSL context", e);
      Throwables.throwIfUnchecked(e);
      throw new RuntimeException(e);
    }
  }
  return _sslcontext;
}
 
Example #20
Source File: AsyncTcpSocketSslTest.java    From datakernel with Apache License 2.0 6 votes vote down vote up
static SSLContext createSslContext() throws Exception {
	SSLContext instance = SSLContext.getInstance("TLSv1.2");

	KeyStore keyStore = KeyStore.getInstance("JKS");
	KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	try (InputStream input = new FileInputStream(new File(KEYSTORE_PATH))) {
		keyStore.load(input, KEYSTORE_PASS.toCharArray());
	}
	kmf.init(keyStore, KEY_PASS.toCharArray());

	KeyStore trustStore = KeyStore.getInstance("JKS");
	TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	try (InputStream input = new FileInputStream(new File(TRUSTSTORE_PATH))) {
		trustStore.load(input, TRUSTSTORE_PASS.toCharArray());
	}
	tmf.init(trustStore);

	instance.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
	return instance;
}
 
Example #21
Source File: SSLConfigClient.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public SSLContext initJDKSSLContext() throws DrillException {
  final SSLContext sslCtx;

  if (!userSslEnabled) {
    return null;
  }

  TrustManagerFactory tmf;
  try {
    tmf = initializeTrustManagerFactory();
    sslCtx = SSLContext.getInstance(protocol);
    sslCtx.init(null, tmf.getTrustManagers(), null);
  } catch (Exception e) {
    // Catch any SSL initialization Exceptions here and abort.
    throw new DrillException(new StringBuilder()
        .append("SSL is enabled but cannot be initialized due to the following exception: ")
        .append("[ ")
        .append(e.getMessage())
        .append("]. ")
        .toString());
  }
  this.jdkSSlContext = sslCtx;
  return sslCtx;
}
 
Example #22
Source File: AvroSource.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
private SSLContext createServerSSLContext() {
  try {
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(new FileInputStream(keystore), keystorePassword.toCharArray());

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

    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(kmf.getKeyManagers(), null, null);
    return serverContext;
  } catch (Exception e) {
    throw new Error("Failed to initialize the server-side SSLContext", e);
  }
}
 
Example #23
Source File: SslReadWriteSelectorHandler.java    From simplewebserver with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor for a secure ChannelIO variant.
 */
public SslReadWriteSelectorHandler(SocketChannel sc, SelectionKey selectionKey,
                                   SSLContext sslContext) throws IOException {
    super(sc);

    sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(false);
    initialHSStatus = HandshakeStatus.NEED_UNWRAP;
    initialHSComplete = false;

    int netBBSize = sslEngine.getSession().getPacketBufferSize();
    inNetBB = ByteBuffer.allocate(netBBSize);
    outNetBB = ByteBuffer.allocate(netBBSize);
    outNetBB.position(0);
    outNetBB.limit(0);

    int appBBSize = sslEngine.getSession().getApplicationBufferSize();
    requestBB = ByteBuffer.allocate(appBBSize);

    while (!doHandshake(selectionKey)) {

    }
}
 
Example #24
Source File: HttpClient.java    From ballerina-message-broker with Apache License 2.0 5 votes vote down vote up
public HttpClient(Configuration configuration) {
    this.url = configuration.getUrl() + BROKER_CONNECTION_URL_SUFFIX;
    this.encodedCredentials = configuration.getEncodedCredentials();

    // turn off SSL verification
    try {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509UntrustManagerImpl() };

        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = (hostname, session) -> true;

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        BrokerClientException exception = new BrokerClientException();
        exception.addMessage("error initializing the connection");
        exception.addMessage(e.getMessage());
        throw exception;
    }
}
 
Example #25
Source File: TLSSocketFactory.java    From braintree_android with MIT License 5 votes vote down vote up
/**
 * @see <a href="http://developer.android.com/training/articles/security-ssl.html#UnknownCa">Android Documentation</a>
 */
public TLSSocketFactory(InputStream certificateStream) throws SSLException {
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);

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

        Collection<? extends Certificate> certificates =
                cf.generateCertificates(certificateStream);
        for (Certificate cert : certificates) {
            if (cert instanceof X509Certificate) {
                String subject = ((X509Certificate) cert).getSubjectDN().getName();
                keyStore.setCertificateEntry(subject, cert);
            }
        }

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

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);
        mInternalSSLSocketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        throw new SSLException(e.getMessage());
    } finally {
        try {
            certificateStream.close();
        } catch (IOException | NullPointerException ignored) {}
    }
}
 
Example #26
Source File: SimpleHttpClient.java    From vespa with Apache License 2.0 5 votes vote down vote up
public SimpleHttpClient(SSLContext sslContext, List<String> enabledProtocols, List<String> enabledCiphers,
                        int listenPort, boolean useCompression) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (!useCompression) {
        builder.disableContentCompression();
    }
    if (sslContext != null) {
        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(
                sslContext,
                toArray(enabledProtocols),
                toArray(enabledCiphers),
                new DefaultHostnameVerifier());
        builder.setSSLSocketFactory(sslConnectionFactory);

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionFactory)
                .build();
        builder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        scheme = "https";
    } else {
        scheme = "http";
    }
    this.delegate = builder.build();
    this.listenPort = listenPort;
}
 
Example #27
Source File: OptionsTests.java    From nats.java with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectOptionsWithNameAndContext() throws Exception {
    SSLContext ctx = TestSSLUtils.createTestSSLContext();
    Options o = new Options.Builder().sslContext(ctx).connectionName("c1").build();
    String expected = "{\"lang\":\"java\",\"version\":\"" + Nats.CLIENT_VERSION + "\",\"name\":\"c1\""
            + ",\"protocol\":1,\"verbose\":false,\"pedantic\":false,\"tls_required\":true,\"echo\":true}";
    assertEquals("default connect options", expected, o.buildProtocolConnectOptionsString("nats://localhost:4222", false, null).toString());
}
 
Example #28
Source File: SetCacheServer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public SetCacheServer(final String identifier, final SSLContext sslContext, final int port, final int maxSize,
        final EvictionPolicy evictionPolicy, final File persistencePath) throws IOException {
    super(identifier, sslContext, port);

    final SetCache simpleCache = new SimpleSetCache(identifier, maxSize, evictionPolicy);

    if (persistencePath == null) {
        this.cache = simpleCache;
    } else {
        final PersistentSetCache persistentCache = new PersistentSetCache(identifier, persistencePath, simpleCache);
        persistentCache.restore();
        this.cache = persistentCache;
    }
}
 
Example #29
Source File: UnboundSSLUtils.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
static SSLClient init(String host, int port, String cipherSuiteFilter,
        String sniHostName) throws NoSuchAlgorithmException, IOException {
    SSLContext sslContext = SSLContext.getDefault();
    SSLSocketFactory ssf = (SSLSocketFactory) sslContext.getSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket(host, port);
    SSLParameters params = new SSLParameters();

    if (cipherSuiteFilter != null) {
        String[] cipherSuites = UnboundSSLUtils.filterStringArray(
                ssf.getSupportedCipherSuites(), cipherSuiteFilter);
        System.out.println("Client: enabled cipher suites: "
                + Arrays.toString(cipherSuites));
        params.setCipherSuites(cipherSuites);
    }

    if (sniHostName != null) {
        System.out.println("Client: set SNI hostname: " + sniHostName);
        SNIHostName serverName = new SNIHostName(sniHostName);
        List<SNIServerName> serverNames = new ArrayList<>();
        serverNames.add(serverName);
        params.setServerNames(serverNames);
    }

    socket.setSSLParameters(params);

    return new SSLClient(socket);
}
 
Example #30
Source File: SslTestClusteredNetworkContext.java    From Chronicle-Network with Apache License 2.0 5 votes vote down vote up
@Override
public SSLContext sslContext() {
    try {
        return SSLContextLoader.getInitialisedContext();
    } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException |
            IOException | KeyManagementException | UnrecoverableKeyException e) {
        throw new RuntimeException("Failed to load ssl context", e);
    }
}