Java Examples for javax.net.ssl.SSLEngine

The following java examples will help you to understand the usage of javax.net.ssl.SSLEngine. These source code samples are taken from different open source projects.

Example 1
Project: ARTPart-master  File: SSLDefaultConfigurationAsserts.java View source code
/**
   * Asserts that the provided {@link SSLEngine} has the expected default configuration.
   */
public static void assertSSLEngine(SSLEngine sslEngine) {
    assertFalse(sslEngine.getUseClientMode());
    assertSSLEngineSSLParameters(sslEngine.getSSLParameters());
    StandardNames.assertDefaultCipherSuites(sslEngine.getEnabledCipherSuites());
    StandardNames.assertSupportedCipherSuites(sslEngine.getSupportedCipherSuites());
    assertContainsAll("Unsupported enabled cipher suites", sslEngine.getSupportedCipherSuites(), sslEngine.getEnabledCipherSuites());
    StandardNames.assertSSLEngineDefaultProtocols(sslEngine.getEnabledProtocols());
    StandardNames.assertSupportedProtocols(sslEngine.getSupportedProtocols());
    assertContainsAll("Unsupported enabled protocols", sslEngine.getSupportedProtocols(), sslEngine.getEnabledProtocols());
    assertTrue(sslEngine.getEnableSessionCreation());
    assertFalse(sslEngine.getNeedClientAuth());
    assertFalse(sslEngine.getWantClientAuth());
}
Example 2
Project: android-sdk-sources-for-api-level-23-master  File: SSLContextSpiTest.java View source code
/**
     * javax.net.ssl.SSLContextSpi#engineCreateSSLEngine(String host, int port)
     * Verify exception when SSLContextSpi object wasn't initialiazed.
     */
public void test_engineCreateSSLEngine_02() {
    int[] invalid_port = { Integer.MIN_VALUE, -65535, -1, 65536, Integer.MAX_VALUE };
    SSLContextSpiImpl ssl = new SSLContextSpiImpl();
    try {
        SSLEngine sleng = ssl.engineCreateSSLEngine("localhost", 1080);
        fail("RuntimeException wasn't thrown");
    } catch (RuntimeException re) {
        String str = re.getMessage();
        if (!str.equals("Not initialiazed"))
            fail("Incorrect exception message: " + str);
    } catch (Exception e) {
        fail("Incorrect exception " + e + " was thrown");
    }
    for (int i = 0; i < invalid_port.length; i++) {
        try {
            SSLEngine sleng = ssl.engineCreateSSLEngine("localhost", invalid_port[i]);
            fail("IllegalArgumentException wasn't thrown");
        } catch (IllegalArgumentException iae) {
        }
    }
}
Example 3
Project: android_platform_libcore-master  File: SSLContext2Test.java View source code
private void checkSSLContext(SSLContext sslC) throws KeyManagementException {
    try {
        sslC.getSocketFactory();
        fail("RuntimeException must be thrown");
    } catch (RuntimeException e) {
        assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
    }
    try {
        sslC.getServerSocketFactory();
        fail("RuntimeException must be thrown");
    } catch (RuntimeException e) {
        assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
    }
    try {
        sslC.getServerSessionContext();
        fail("RuntimeException must be thrown");
    } catch (RuntimeException e) {
        assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
    }
    try {
        sslC.getClientSessionContext();
        fail("RuntimeException must be thrown");
    } catch (RuntimeException e) {
        assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
    }
    try {
        sslC.createSSLEngine();
        fail("RuntimeException must be thrown");
    } catch (RuntimeException e) {
        assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
    }
    try {
        sslC.createSSLEngine("host", 1);
        fail("RuntimeException must be thrown");
    } catch (RuntimeException e) {
        assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
    }
    TrustManager[] tm = new TManager[10];
    KeyManager[] km = new KManager[5];
    try {
        sslC.init(km, tm, null);
        fail("KeyManagementException must be thrown");
    } catch (KeyManagementException e) {
    }
    sslC.init(km, tm, new SecureRandom());
    SSLEngine sslE = sslC.createSSLEngine();
    assertTrue("Not null result", sslE instanceof SSLEngine);
    assertNull("Incorrect host", sslE.getPeerHost());
    assertEquals("Incorrect port", 0, sslE.getPeerPort());
    String host = "ZZZ";
    int port = 8080;
    sslE = sslC.createSSLEngine(host, port);
    assertTrue("Not null result", sslE instanceof SSLEngine);
    assertEquals("Incorrect host", sslE.getPeerHost(), host);
    assertEquals("Incorrect port", sslE.getPeerPort(), port);
    try {
        assertNull("Not null result", sslC.getServerSessionContext());
    } catch (NullPointerException e) {
    }
    try {
        assertNull("Not null result", sslC.getClientSessionContext());
    } catch (NullPointerException e) {
    }
}
Example 4
Project: android-libcore64-master  File: SSLContext2Test.java View source code
private void checkSSLContext(SSLContext sslC) throws KeyManagementException {
    try {
        sslC.getSocketFactory();
        fail("RuntimeException must be thrown");
    } catch (RuntimeException e) {
        assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
    }
    try {
        sslC.getServerSocketFactory();
        fail("RuntimeException must be thrown");
    } catch (RuntimeException e) {
        assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
    }
    try {
        sslC.getServerSessionContext();
        fail("RuntimeException must be thrown");
    } catch (RuntimeException e) {
        assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
    }
    try {
        sslC.getClientSessionContext();
        fail("RuntimeException must be thrown");
    } catch (RuntimeException e) {
        assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
    }
    try {
        sslC.createSSLEngine();
        fail("RuntimeException must be thrown");
    } catch (RuntimeException e) {
        assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
    }
    try {
        sslC.createSSLEngine("host", 1);
        fail("RuntimeException must be thrown");
    } catch (RuntimeException e) {
        assertEquals("Incorrect message", "Not initialiazed", e.getMessage());
    }
    TrustManager[] tm = new TManager[10];
    KeyManager[] km = new KManager[5];
    try {
        sslC.init(km, tm, null);
        fail("KeyManagementException must be thrown");
    } catch (KeyManagementException e) {
    }
    sslC.init(km, tm, new SecureRandom());
    SSLEngine sslE = sslC.createSSLEngine();
    assertTrue("Not null result", sslE instanceof SSLEngine);
    assertNull("Incorrect host", sslE.getPeerHost());
    assertEquals("Incorrect port", 0, sslE.getPeerPort());
    String host = "ZZZ";
    int port = 8080;
    sslE = sslC.createSSLEngine(host, port);
    assertTrue("Not null result", sslE instanceof SSLEngine);
    assertEquals("Incorrect host", sslE.getPeerHost(), host);
    assertEquals("Incorrect port", sslE.getPeerPort(), port);
    try {
        assertNull("Not null result", sslC.getServerSessionContext());
    } catch (NullPointerException e) {
    }
    try {
        assertNull("Not null result", sslC.getClientSessionContext());
    } catch (NullPointerException e) {
    }
}
Example 5
Project: sitebricks-master  File: MailClientPipelineFactory.java View source code
public ChannelPipeline getPipeline() throws Exception {
    // Create a default pipeline implementation.
    ChannelPipeline pipeline = Channels.pipeline();
    if (config.getAuthType() != Auth.PLAIN) {
        SSLEngine sslEngine = SSLContext.getDefault().createSSLEngine();
        sslEngine.setUseClientMode(true);
        SslHandler sslHandler = new SslHandler(sslEngine);
        sslHandler.setEnableRenegotiation(true);
        pipeline.addLast("ssl", sslHandler);
    }
    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());
    // and then business logic.
    pipeline.addLast("handler", mailClientHandler);
    return pipeline;
}
Example 6
Project: openjdk-master  File: SSLSecurity.java View source code
/*
     * JSSE 1.0.x was only socket based, but it's possible someone might
     * want to install a really old provider.  We should at least
     * try to be nice.
     */
public String chooseEngineClientAlias(String[] keyTypes, Principal[] issuers, javax.net.ssl.SSLEngine engine) {
    String retval;
    if (keyTypes == null) {
        return null;
    }
    /*
         * Scan the list, look for something we can pass back.
         */
    for (int i = 0; i < keyTypes.length; i++) {
        if ((retval = theX509KeyManager.chooseClientAlias(keyTypes[i], issuers)) != null)
            return retval;
    }
    return null;
}
Example 7
Project: streamline-master  File: HttpTunnelingClientSocketChannel.java View source code
public void operationComplete(ChannelFuture f) {
    final String serverName = config.getServerName();
    final int serverPort = ((InetSocketAddress) remoteAddress).getPort();
    final String serverPath = config.getServerPath();
    if (f.isSuccess()) {
        // Configure SSL
        SSLContext sslContext = config.getSslContext();
        ChannelFuture sslHandshakeFuture = null;
        if (sslContext != null) {
            // Create a new SSLEngine from the specified SSLContext.
            SSLEngine engine;
            if (serverName != null) {
                engine = sslContext.createSSLEngine(serverName, serverPort);
            } else {
                engine = sslContext.createSSLEngine();
            }
            // Configure the SSLEngine.
            engine.setUseClientMode(true);
            engine.setEnableSessionCreation(config.isEnableSslSessionCreation());
            String[] enabledCipherSuites = config.getEnabledSslCipherSuites();
            if (enabledCipherSuites != null) {
                engine.setEnabledCipherSuites(enabledCipherSuites);
            }
            String[] enabledProtocols = config.getEnabledSslProtocols();
            if (enabledProtocols != null) {
                engine.setEnabledProtocols(enabledProtocols);
            }
            SslHandler sslHandler = new SslHandler(engine);
            realChannel.getPipeline().addFirst("ssl", sslHandler);
            sslHandshakeFuture = sslHandler.handshake();
        }
        // Send the HTTP request.
        final HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, serverPath);
        if (serverName != null) {
            req.setHeader(HttpHeaders.Names.HOST, serverName);
        }
        req.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/octet-stream");
        req.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
        req.setHeader(HttpHeaders.Names.CONTENT_TRANSFER_ENCODING, HttpHeaders.Values.BINARY);
        req.setHeader(HttpHeaders.Names.USER_AGENT, HttpTunnelingClientSocketChannel.class.getName());
        if (sslHandshakeFuture == null) {
            realChannel.write(req);
            requestHeaderWritten = true;
            future.setSuccess();
            fireChannelConnected(virtualChannel, remoteAddress);
        } else {
            sslHandshakeFuture.addListener(new ChannelFutureListener() {

                public void operationComplete(ChannelFuture f) {
                    if (f.isSuccess()) {
                        realChannel.write(req);
                        requestHeaderWritten = true;
                        future.setSuccess();
                        fireChannelConnected(virtualChannel, remoteAddress);
                    } else {
                        future.setFailure(f.getCause());
                        fireExceptionCaught(virtualChannel, f.getCause());
                    }
                }
            });
        }
    } else {
        future.setFailure(f.getCause());
        fireExceptionCaught(virtualChannel, f.getCause());
    }
}
Example 8
Project: dcache-master  File: CanlContextFactory.java View source code
protected SSLEngine wrapEngine(SSLEngine engine) {
    if (isGsiEnabled) {
        ServerGsiEngine gsiEngine = new ServerGsiEngine(engine, cf);
        gsiEngine.setUsingLegacyClose(isUsingLegacyClose);
        gsiEngine.setKeyPairCache(keyPairCache);
        return new GsiFrameEngine(gsiEngine);
    } else {
        return engine;
    }
}
Example 9
Project: openjdk8-jdk-master  File: SSLSecurity.java View source code
/*
     * JSSE 1.0.x was only socket based, but it's possible someone might
     * want to install a really old provider.  We should at least
     * try to be nice.
     */
public String chooseEngineClientAlias(String[] keyTypes, Principal[] issuers, javax.net.ssl.SSLEngine engine) {
    String retval;
    if (keyTypes == null) {
        return null;
    }
    /*
         * Scan the list, look for something we can pass back.
         */
    for (int i = 0; i < keyTypes.length; i++) {
        if ((retval = theX509KeyManager.chooseClientAlias(keyTypes[i], issuers)) != null)
            return retval;
    }
    return null;
}
Example 10
Project: wso2-synapse-master  File: ClientSSLSetupHandler.java View source code
public void initalize(SSLEngine sslengine) {
    /*
            set handshake protocols if they are specified in transport configuration.
            eg: <parameter name="HttpsProtocols">TLSv1.1,TLSv1.2</parameter>
        */
    if (null != httpsProtocols) {
        sslengine.setEnabledProtocols(httpsProtocols);
    }
}
Example 11
Project: jdk7u-jdk-master  File: SSLSecurity.java View source code
/*
     * JSSE 1.0.x was only socket based, but it's possible someone might
     * want to install a really old provider.  We should at least
     * try to be nice.
     */
public String chooseEngineClientAlias(String[] keyTypes, Principal[] issuers, javax.net.ssl.SSLEngine engine) {
    String retval;
    if (keyTypes == null) {
        return null;
    }
    /*
         * Scan the list, look for something we can pass back.
         */
    for (int i = 0; i < keyTypes.length; i++) {
        if ((retval = theX509KeyManager.chooseClientAlias(keyTypes[i], issuers)) != null)
            return retval;
    }
    return null;
}
Example 12
Project: netty4.0.27Learn-master  File: SpdyOrHttpChooser.java View source code
/**
     * Return the {@link SelectedProtocol} for the {@link SSLEngine}. If its not known yet implementations MUST return
     * {@link SelectedProtocol#UNKNOWN}.
     *
     */
protected SelectedProtocol getProtocol(SSLEngine engine) {
    String[] protocol = StringUtil.split(engine.getSession().getProtocol(), ':');
    if (protocol.length < 2) {
        // Use HTTP/1.1 as default
        return SelectedProtocol.HTTP_1_1;
    }
    SelectedProtocol selectedProtocol = SelectedProtocol.protocol(protocol[1]);
    return selectedProtocol;
}
Example 13
Project: usergrid-master  File: WebSocketServerPipelineFactory.java View source code
@Override
public ChannelPipeline getPipeline() throws Exception {
    // Create a default pipeline implementation.
    ChannelPipeline pipeline = pipeline();
    if (ssl) {
        SSLEngine sslEngine = WebSocketSslContextFactory.getServerContext().createSSLEngine();
        sslEngine.setUseClientMode(false);
        pipeline.addLast("ssl", new SslHandler(sslEngine));
    }
    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("aggregator", new HttpChunkAggregator(65536));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("execution", executionHandler);
    pipeline.addLast("handler", new WebSocketChannelHandler(emf, smf, management, securityManager, ssl));
    return pipeline;
}
Example 14
Project: jlibs-master  File: TCPEndpoint.java View source code
public TCPServer startServer(TCPServer.Listener listener) throws IOException {
    TCPServer server = new TCPServer(new TCPServer.Listener() {

        @Override
        public void accept(TCPConnection con) {
            try {
                if (sslContext != null) {
                    SSLEngine engine = sslContext.createSSLEngine();
                    engine.setUseClientMode(false);
                    new SSLSocket(con.in(), con.out(), engine);
                }
            } catch (Throwable thr) {
                Reactor.current().handleException(thr);
                con.close();
                return;
            }
            listener.accept(con);
        }

        @Override
        public String toString() {
            return listener.getClass().getSimpleName();
        }
    });
    try {
        server.bind(socketAddress());
    } catch (Throwable thr) {
        server.close();
        throw thr;
    }
    return server;
}
Example 15
Project: ManagedRuntimeInitiative-master  File: SSLSecurity.java View source code
/*
     * JSSE 1.0.x was only socket based, but it's possible someone might
     * want to install a really old provider.  We should at least
     * try to be nice.
     */
public String chooseEngineClientAlias(String[] keyTypes, Principal[] issuers, javax.net.ssl.SSLEngine engine) {
    String retval;
    if (keyTypes == null) {
        return null;
    }
    /*
         * Scan the list, look for something we can pass back.
         */
    for (int i = 0; i < keyTypes.length; i++) {
        if ((retval = theX509KeyManager.chooseClientAlias(keyTypes[i], issuers)) != null)
            return retval;
    }
    return null;
}
Example 16
Project: rabbitmq-java-client-master  File: SslEngineHelper.java View source code
public static boolean doHandshake(SocketChannel socketChannel, SSLEngine engine) throws IOException {
    ByteBuffer plainOut = ByteBuffer.allocate(engine.getSession().getApplicationBufferSize());
    ByteBuffer plainIn = ByteBuffer.allocate(engine.getSession().getApplicationBufferSize());
    ByteBuffer cipherOut = ByteBuffer.allocate(engine.getSession().getPacketBufferSize());
    ByteBuffer cipherIn = ByteBuffer.allocate(engine.getSession().getPacketBufferSize());
    SSLEngineResult.HandshakeStatus handshakeStatus = engine.getHandshakeStatus();
    while (handshakeStatus != FINISHED && handshakeStatus != NOT_HANDSHAKING) {
        switch(handshakeStatus) {
            case NEED_TASK:
                handshakeStatus = runDelegatedTasks(engine);
                break;
            case NEED_UNWRAP:
                handshakeStatus = unwrap(cipherIn, plainIn, socketChannel, engine);
                break;
            case NEED_WRAP:
                handshakeStatus = wrap(plainOut, cipherOut, socketChannel, engine);
                break;
        }
    }
    return true;
}
Example 17
Project: usercenter-master  File: WrapperKeyManager.java View source code
@Override()
public final synchronized String chooseEngineClientAlias(final String[] keyType, final Principal[] issuers, final SSLEngine engine) {
    if (certificateAlias == null) {
        for (final X509KeyManager m : keyManagers) {
            if (m instanceof X509ExtendedKeyManager) {
                final X509ExtendedKeyManager em = (X509ExtendedKeyManager) m;
                final String alias = em.chooseEngineClientAlias(keyType, issuers, engine);
                if (alias != null) {
                    return alias;
                }
            } else {
                final String alias = m.chooseClientAlias(keyType, issuers, null);
                if (alias != null) {
                    return alias;
                }
            }
        }
        return null;
    } else {
        for (final String s : keyType) {
            for (final X509KeyManager m : keyManagers) {
                final String[] aliases = m.getClientAliases(s, issuers);
                if (aliases != null) {
                    for (final String alias : aliases) {
                        if (alias.equals(certificateAlias)) {
                            return certificateAlias;
                        }
                    }
                }
            }
        }
        return null;
    }
}
Example 18
Project: flink-master  File: NettyClient.java View source code
@Override
public void initChannel(SocketChannel channel) throws Exception {
    // SSL handler should be added first in the pipeline
    if (clientSSLContext != null) {
        SSLEngine sslEngine = clientSSLContext.createSSLEngine(serverSocketAddress.getAddress().getHostAddress(), serverSocketAddress.getPort());
        sslEngine.setUseClientMode(true);
        // Enable hostname verification for remote SSL connections
        if (!serverSocketAddress.getAddress().isLoopbackAddress()) {
            SSLParameters newSSLParameters = sslEngine.getSSLParameters();
            config.setSSLVerifyHostname(newSSLParameters);
            sslEngine.setSSLParameters(newSSLParameters);
        }
        channel.pipeline().addLast("ssl", new SslHandler(sslEngine));
    }
    channel.pipeline().addLast(protocol.getClientChannelHandlers());
}
Example 19
Project: cdo-master  File: SSLUtil.java View source code
public static synchronized SSLEngine createSSLEngine(boolean client, String host, int port) throws Exception {
    // Get values from the system properties.
    SSLProperties sslProperties = new SSLProperties();
    String keyPath = sslProperties.getKeyPath();
    String trustPath = sslProperties.getTrustPath();
    String passPhrase = sslProperties.getPassPhrase();
    if ((keyPath == null || trustPath == null || passPhrase == null) && configFile != null) {
        sslProperties.load(configFile);
    }
    // In case, the system properties does not have the key path property. It will load from local config file.
    if (keyPath == null) {
        keyPath = sslProperties.getKeyPath();
        if (keyPath == null) {
            keyPath = keyPathVar;
        }
    }
    // In case, the system properties does not have the trust path property. It will load from local config file.
    if (trustPath == null) {
        trustPath = sslProperties.getTrustPath();
        if (trustPath == null) {
            trustPath = trustPathVar;
        }
    }
    // In case, the system properties does not have the passphrase property. It will load from local config file.
    if (passPhrase == null) {
        passPhrase = sslProperties.getPassPhrase();
        if (passPhrase == null) {
            passPhrase = passPhraseVar;
        }
    }
    // Handle assign the value of handshake timeout and handshake timewait from local properties or system properties by
    // giving the value form system properties is high priority.
    String value = sslProperties.getHandShakeTimeOut();
    if (value != null) {
        handShakeTimeOutVar = Integer.parseInt(value);
    }
    value = sslProperties.getHandShakeWaitTime();
    if (value != null) {
        handShakeWaitTimeVar = Integer.parseInt(value);
    }
    if (keyPath == null && !client || trustPath == null && client || passPhrase == null) {
        if (client) {
            throw new KeyStoreException("Trust Store[" + (trustPath != null) + "] or Pass Phrase[" + (passPhrase != null) + "] is not provided. [false] means it does not exist.");
        }
        throw new KeyStoreException("Key Store[" + (keyPath != null) + "] or Pass Phrase[" + (passPhrase != null) + "] is not provided. [false] means it does not exist.");
    }
    char[] pass = passPhrase.toCharArray();
    KeyManager[] keyManagers = null;
    TrustManager[] trustManagers = null;
    String checkValidity = OMPlatform.INSTANCE.getProperty(SSLProperties.CHECK_VALIDITY_CERTIFICATE);
    boolean checkValidtyStatus = checkValidity == null || Boolean.valueOf(checkValidity);
    if (client) {
        // Initial key material(private key) for the client.
        KeyStore ksTrust = createKeyStore(trustPath, pass, checkValidtyStatus);
        // Initial the trust manager factory
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ksTrust);
        trustManagers = tmf.getTrustManagers();
    } else {
        // Initial key material (private key) for the server.
        KeyStore ksKeys = createKeyStore(keyPath, pass, checkValidtyStatus);
        // Initial the key manager factory.
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ksKeys, pass);
        keyManagers = kmf.getKeyManagers();
    }
    SSLContext sslContext = SSLContext.getInstance(PROTOCOL);
    sslContext.init(keyManagers, trustManagers, null);
    SSLEngine sslEngine = sslContext.createSSLEngine(host, port);
    sslEngine.setUseClientMode(client);
    return sslEngine;
}
Example 20
Project: Payara-master  File: HttpRedirectFilter.java View source code
// --------------------------------------------- Methods from Filter
@Override
public NextAction handleRead(final FilterChainContext ctx) throws IOException {
    final Connection connection = ctx.getConnection();
    final HttpContent httpContent = ctx.getMessage();
    final HttpRequestPacket request = (HttpRequestPacket) httpContent.getHttpHeader();
    final URI requestURI;
    try {
        final String uri = request.getQueryString() == null ? request.getRequestURI() : request.getRequestURI() + "?" + request.getQueryString();
        requestURI = new URI(uri);
    } catch (URISyntaxException ignored) {
        return ctx.getStopAction();
    }
    final boolean redirectToSecure;
    if (secure != null) {
        // if secure is set - we use it
        redirectToSecure = secure;
    } else {
        // if secure is not set - use secure settings opposite to the current request
        final SSLEngine sslEngine = SSLUtils.getSSLEngine(connection);
        redirectToSecure = sslEngine == null;
    }
    final StringBuilder hostPort = new StringBuilder();
    String hostHeader = request.getHeader("host");
    if (hostHeader == null) {
        String hostRequestURI = requestURI.getHost();
        if (hostRequestURI == null) {
            hostPort.append(request.getLocalHost());
        } else {
            hostPort.append(hostRequestURI);
        }
        hostPort.append(':');
        if (redirectPort == null) {
            int port = requestURI.getPort();
            if (port == -1) {
                hostPort.append(request.getLocalPort());
            } else {
                hostPort.append(port);
            }
        } else {
            hostPort.append(redirectPort);
        }
    } else if (redirectPort != null) {
        // if port is specified - cut it from host header
        final int colonIdx = hostHeader.indexOf(':');
        if (colonIdx != -1) {
            hostHeader = hostHeader.substring(0, colonIdx);
        }
        hostPort.append(hostHeader).append(':').append(redirectPort);
    } else {
        hostPort.append(hostHeader);
    }
    if (hostPort.length() > 0) {
        String path = requestURI.toString();
        assert path != null;
        final StringBuilder sb = new StringBuilder();
        sb.append((redirectToSecure ? "https://" : "http://")).append(hostPort).append(path);
        request.setSkipRemainder(true);
        final HttpResponsePacket response = HttpResponsePacket.builder(request).status(302).header("Location", sb.toString()).contentLength(0).build();
        ctx.write(response);
    } else {
        connection.closeSilently();
    }
    return ctx.getStopAction();
}
Example 21
Project: milton2-master  File: MiltonSNICertificateManager.java View source code
@Override
public String chooseEngineServerAlias(final String type, Principal[] issuers, SSLEngine engine) {
    log.trace("Https (SSL/TLS) Handshaking start....");
    log.trace("Choose the EngineServer Alias Name, and the engine type is: {}", type);
    // Get the Host Name of the SNI Server for this SSL request from the browser/client
    ExtendedSSLSession handshakeSession = (ExtendedSSLSession) engine.getHandshakeSession();
    log.debug("Choose EngineServer Alias Name, and the handshake session is:" + handshakeSession.hashCode());
    String domainName = null;
    for (SNIServerName name : handshakeSession.getRequestedServerNames()) {
        if (name.getType() == StandardConstants.SNI_HOST_NAME) {
            domainName = ((SNIHostName) name).getAsciiName();
            break;
        }
    }
    log.trace("chooseEngineServerAlias, SNIServerName is: {}", domainName);
    // Check the hostname is existed or not form the certificate store(database)
    boolean hostNameCheck = keyStoreSpi.engineContainsAlias(domainName);
    if (hostNameCheck) {
        return domainName;
    }
    return null;
}
Example 22
Project: wildfly-core-master  File: WrapperSSLContext.java View source code
private void setSslParams(final SSLEngine engine) {
    if (enabledCipherSuites.length > 0) {
        engine.setEnabledCipherSuites(enabledCipherSuites);
    }
    if (enabledProtocols.length > 0) {
        engine.setEnabledProtocols(enabledProtocols);
    }
}
Example 23
Project: classlib6-master  File: SSLSecurity.java View source code
/*
     * JSSE 1.0.x was only socket based, but it's possible someone might
     * want to install a really old provider.  We should at least
     * try to be nice.
     */
public String chooseEngineClientAlias(String[] keyTypes, Principal[] issuers, javax.net.ssl.SSLEngine engine) {
    String retval;
    if (keyTypes == null) {
        return null;
    }
    /*
	 * Scan the list, look for something we can pass back.
	 */
    for (int i = 0; i < keyTypes.length; i++) {
        if ((retval = theX509KeyManager.chooseClientAlias(keyTypes[i], issuers)) != null)
            return retval;
    }
    return null;
}
Example 24
Project: ikvm-openjdk-master  File: SSLSecurity.java View source code
/*
     * JSSE 1.0.x was only socket based, but it's possible someone might
     * want to install a really old provider.  We should at least
     * try to be nice.
     */
public String chooseEngineClientAlias(String[] keyTypes, Principal[] issuers, javax.net.ssl.SSLEngine engine) {
    String retval;
    if (keyTypes == null) {
        return null;
    }
    /*
         * Scan the list, look for something we can pass back.
         */
    for (int i = 0; i < keyTypes.length; i++) {
        if ((retval = theX509KeyManager.chooseClientAlias(keyTypes[i], issuers)) != null)
            return retval;
    }
    return null;
}
Example 25
Project: gluu-opendj-master  File: SelectableCertificateKeyManager.java View source code
/**
   * Chooses the alias of the client certificate that should be used based on
   * the provided critieria.  This will either return the preferred alias
   * configured for this key manager, or {@code null} if no client certificate
   * with that alias is configured in the underlying key manager.
   *
   * @param  keyType  The set of key algorithm names, ordered with the most
   *                  preferred key type first.
   * @param  issuers  The list of acceptable issuer subject names, or
   *                  {@code null} if any issuer may be used.
   * @param  engine   The SSL engine to be used for this connection.
   *
   * @return  The alias configured for this key manager, or {@code null} if no
   *          such client certificate is available with that alias.
   */
@Override
public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, SSLEngine engine) {
    for (String type : keyType) {
        String[] clientAliases = keyManager.getClientAliases(type, issuers);
        if (clientAliases != null) {
            for (String clientAlias : clientAliases) {
                if (clientAlias.equals(alias)) {
                    return alias;
                }
            }
        }
    }
    return null;
}