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: 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 #2
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 #3
Source File: HttpClientFactory.java    From hsac-fitnesse-fixtures with Apache License 2.0 7 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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
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 #20
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 #21
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 #22
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 #23
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 #24
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 #25
Source File: IOReactor.java    From mts with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Open a SSL Socket. This method is based on class SSLSocketChannel we got
 * from some LGPL library.
 * @param localSocketAddress
 * @param remoteSocketAddress
 * @param handler
 * @param context
 * @throws Exception
 */
public void openTLS(SocketAddress localSocketAddress, SocketAddress remoteSocketAddress, IOHandler handler, SSLContext context) throws Exception
{
    // create an engine based on an already initialized context. This context
    // contains the certificates.
    SSLEngine engine = context.createSSLEngine();
    engine.setUseClientMode(true);
    // create, connect (TCP only, no exchange yet).
    SSLSocketChannel channel = new SSLSocketChannel(SocketChannel.open(), engine);
    channel.socket().bind(localSocketAddress);
    channel.configureBlocking(true);
    channel.connect(remoteSocketAddress);
    channel.configureBlocking(false);

    synchronized(selectorLock)
    {
        // wakeup the selector (it will leave the .select() method then block
        // on the synchronized(selectorLock){]} instruction. If we don't do this,
        // the .register method is blocking until select() leaves, which can
        // take some time if there is no network traffic.
        this.selector.wakeup();
        SocketChannel adapteeChannel = ((SocketChannel)channel.getAdapteeChannel());
        
        // call the init() method of the handler to give him the channel and
        // selectionKey he will use for later calls to outputReadey and inputReady.
        //
        // NB for SSL: we do not give the handler the same channel we register into
        //             the selector because we can only register sun's channels
        //             into the selector.
        handler.onIorInit(adapteeChannel.register(selector, SelectionKey.OP_READ, handler), channel);
    }
}
 
Example #26
Source File: UnboundSSLUtils.java    From openjdk-jdk9 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 #27
Source File: QoSService.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param executor
 * @param socket
 */
public QoSService(ExecutorService executor, ServerSocket socket, SSLContext sslContext) {
	this.executor = executor;
	this.socket = socket;
	this.sslContext = sslContext;
	this.name = "[QoSService " +  socket.getInetAddress() + ":" + socket.getLocalPort() +"]: ";
}
 
Example #28
Source File: SSLConfig.java    From AndroidUtilCode with Apache License 2.0 5 votes vote down vote up
DefaultSSLSocketFactory() {
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, DEFAULT_TRUST_MANAGERS, new SecureRandom());
        mFactory = sslContext.getSocketFactory();
    } catch (GeneralSecurityException e) {
        throw new AssertionError();
    }
}
 
Example #29
Source File: LdapUserDAO.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected InitialLdapContext getDirContext() throws NamingException, CommunicationException, ConnectException {
    InitialLdapContext dirCtx = null;
    try {
        if (this.isTlsSecurityConnection()) {
            dirCtx = new InitialLdapContext(this.getParams(true), null);
            StartTlsResponse tls = (StartTlsResponse) dirCtx.extendedOperation(new StartTlsRequest());
            if (this.isTlsFreeSecurityConnection()) {
                // Set the (our) HostVerifier
                tls.setHostnameVerifier(new MyTLSHostnameVerifier());
                SSLSocketFactory sslsf = null;
                try {
                    TrustManager[] tm = new TrustManager[]{new MyX509TrustManager()};
                    SSLContext sslC = SSLContext.getInstance("TLSv1.2");
                    sslC.init(null, tm, null);
                    sslsf = sslC.getSocketFactory();
                } catch (NoSuchAlgorithmException nSAE) {
                    logger.error("error Hier: {}", nSAE.getMessage(), nSAE);
                } catch (KeyManagementException kME) {
                    logger.error("error Hier: {}", kME.getMessage(), kME);
                }
                tls.negotiate(sslsf);
            } else {
                tls.negotiate();
            }
            if (null != this.getSecurityPrincipal() && null != this.getSecurityCredentials()) {
                dirCtx.addToEnvironment(Context.SECURITY_PRINCIPAL, this.getSecurityPrincipal());
                dirCtx.addToEnvironment(Context.SECURITY_CREDENTIALS, this.getSecurityCredentials());
                dirCtx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            }
        } else {
            dirCtx = new InitialLdapContext(this.getParams(false), null);
        }
    } catch (IOException ex) {
        logger.error("error in getDirContext", ex);
    } catch (NamingException e) {
        throw e;
    }
    return dirCtx;
}
 
Example #30
Source File: DisabledAlgorithms.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
static SSLClient init(int port, String ciphersuite)
        throws NoSuchAlgorithmException, IOException {
    SSLContext context = SSLContext.getDefault();
    SSLSocketFactory ssf = (SSLSocketFactory)
            context.getSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket("localhost", port);

    if (ciphersuite != null) {
        System.out.println("Client: enable cipher suite: "
                + ciphersuite);
        socket.setEnabledCipherSuites(new String[] { ciphersuite });
    }

    return new SSLClient(socket);
}