javatips.net counter

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 [email protected] 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: 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 3
Project: openjdk-master  File: EngineCloseOnAlert.java View source code
@Override
public void runTest() throws Exception {
    System.out.println("");
    System.out.println("=======================================");
    System.out.println("Test: Client receives alert from server");
    System.out.println("=======================================");
    // For this test, we won't initialize any keystore so the
    // server will throw an exception because it has no key/cert to
    // match the requested ciphers offered by the client.  This
    // will generate an alert from the server to the client.
    SSLContext context = SSLContext.getDefault();
    SSLEngine client = context.createSSLEngine();
    SSLEngine server = context.createSSLEngine();
    client.setUseClientMode(true);
    server.setUseClientMode(false);
    SSLEngineResult clientResult;
    SSLEngineResult serverResult;
    ByteBuffer raw = ByteBuffer.allocate(32768);
    ByteBuffer plain = ByteBuffer.allocate(32768);
    // Generate the client hello and have the server unwrap it
    client.wrap(plain, raw);
    checkEngineState(client, NEED_UNWRAP, false, false);
    raw.flip();
    System.out.println("Client-to-Server:\n-----------------\n" + dumpHexBytes(raw, 16, "\n", ":"));
    // The server should need to run a delegated task while processing
    // the client hello data.
    serverResult = server.unwrap(raw, plain);
    checkEngineState(server, NEED_TASK, false, false);
    System.out.println("Server result: " + serverResult);
    runDelegatedTasks(serverResult, server);
    checkEngineState(server, NEED_WRAP, true, false);
    try {
        raw.clear();
        serverResult = server.wrap(plain, raw);
        System.out.println("Server result: " + serverResult);
        runDelegatedTasks(serverResult, server);
    } catch (SSLException e) {
        System.out.println("Server throws exception: " + e);
        System.out.println("Server engine state: " + "isInboundDone = " + server.isInboundDone() + ", isOutboundDone = " + server.isOutboundDone() + ", handshake status = " + server.getHandshakeStatus());
        checkEngineState(server, NEED_WRAP, true, false);
    }
    raw.clear();
    // The above should show that isInboundDone returns true, and
    // handshake status is NEED_WRAP. That is the correct behavior,
    // wrap will put a fatal alert message in the buffer.
    serverResult = server.wrap(plain, raw);
    System.out.println("Server result (wrap after exception): " + serverResult);
    System.out.println("Server engine closure state: isInboundDone=" + server.isInboundDone() + ", isOutboundDone=" + server.isOutboundDone());
    checkEngineState(server, NEED_UNWRAP, true, true);
    raw.flip();
    System.out.println("Server-to-Client:\n-----------------\n" + dumpHexBytes(raw, 16, "\n", ":"));
    // Client side will read the fatal alert and throw exception.
    try {
        clientResult = client.unwrap(raw, plain);
        System.out.println("Client result (unwrap alert): " + clientResult);
    } catch (SSLException e) {
        System.out.println("Client throws exception: " + e);
        System.out.println("Engine closure status: isInboundDone=" + client.isInboundDone() + ", isOutboundDone=" + client.isOutboundDone() + ", handshake status=" + client.getHandshakeStatus());
        checkEngineState(client, NOT_HANDSHAKING, true, true);
    }
    raw.clear();
    // Last test, we try to unwrap
    clientResult = client.unwrap(raw, plain);
    checkEngineState(client, NOT_HANDSHAKING, true, true);
    System.out.println("Client result (wrap after exception): " + clientResult);
}
Example 4
Project: streamline-master  File: SslHandler.java View source code
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    // been closed during handshake.
    synchronized (handshakeLock) {
        if (handshaking) {
            handshakeFuture.setFailure(new ClosedChannelException());
        }
    }
    try {
        super.channelDisconnected(ctx, e);
    } finally {
        unwrap(ctx, e.getChannel(), ChannelBuffers.EMPTY_BUFFER, 0, 0);
        engine.closeOutbound();
        if (!sentCloseNotify.get() && handshaken) {
            try {
                engine.closeInbound();
            } catch (SSLException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Failed to clean up SSLEngine.", ex);
                }
            }
        }
    }
}
Example 5
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 6
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 7
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 8
Project: netty4.0.27Learn-master  File: JdkSslEngineTest.java View source code
@Override
public ProtocolSelector newSelector(SSLEngine engine, Set<String> supportedProtocols) {
    return new ProtocolSelector() {

        @Override
        public void unsupported() {
        }

        @Override
        public String select(List<String> protocols) {
            return APPLICATION_LEVEL_PROTOCOL_NOT_COMPATIBLE;
        }
    };
}
Example 9
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 10
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 11
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 12
Project: android_platform_libcore-master  File: SSLContext1Test.java View source code
/**
     * Test for <code>SSLContext</code> constructor Assertion: returns
     * SSLContext object
     */
public void test_ConstructorLjavax_net_ssl_SSLContextSpiLjava_security_ProviderLjava_lang_String() throws NoSuchAlgorithmException, KeyManagementException {
    if (!DEFSupported) {
        fail(NotSupportMsg);
        return;
    }
    SSLContextSpi spi = new MySSLContextSpi();
    SSLContext sslContext = new MySslContext(spi, defaultProvider, defaultProtocol);
    assertEquals("Incorrect protocol", defaultProtocol, sslContext.getProtocol());
    assertEquals("Incorrect provider", defaultProvider, sslContext.getProvider());
    TrustManager[] tm = null;
    KeyManager[] km = null;
    sslContext.init(km, tm, new SecureRandom());
    assertNotNull("No SSLEngine created", sslContext.createSSLEngine());
    assertNotNull("No SSLEngine created", sslContext.createSSLEngine("host", 8888));
    try {
        sslContext.init(km, tm, null);
        fail("KeyManagementException should be thrown for null " + "SecureRandom");
    } catch (KeyManagementException e) {
    }
    sslContext = new MySslContext(null, null, null);
    assertNull("Incorrect protocol", sslContext.getProtocol());
    assertNull("Incorrect provider", sslContext.getProvider());
    try {
        sslContext.createSSLEngine();
        fail("NullPointerException should be thrown");
    } catch (NullPointerException e) {
    }
    try {
        sslContext.getSocketFactory();
        fail("NullPointerException should be thrown");
    } catch (NullPointerException e) {
    }
}
Example 13
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 14
Project: flink-master  File: WebRuntimeMonitor.java View source code
@Override
protected void initChannel(SocketChannel ch) {
    Handler handler = new Handler(router);
    // SSL should be the first handler in the pipeline
    if (serverSSLContext != null) {
        SSLEngine sslEngine = serverSSLContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        ch.pipeline().addLast("ssl", new SslHandler(sslEngine));
    }
    ch.pipeline().addLast(new HttpServerCodec()).addLast(new ChunkedWriteHandler()).addLast(new HttpRequestHandler(uploadDir)).addLast(handler.name(), handler).addLast(new PipelineErrorHandler(LOG));
}
Example 15
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 16
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 17
Project: milton2-master  File: SslSimpletonServer.java View source code
public void process(Socket pipeline) throws IOException {
    final SocketChannel channel = pipeline.getChannel();
    final Map map = new HashMap();
    Socket secure = new Socket() {

        private SSLEngine engine;

        public Map getAttributes() {
            return map;
        }

        public SocketChannel getChannel() {
            return channel;
        }

        public SSLEngine getEngine() {
            if (engine == null) {
                engine = context.createSSLEngine();
            }
            return engine;
        }
    };
    processor.process(secure);
}
Example 18
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 19
Project: gluu-opendj-master  File: LDAPConnectionHandler.java View source code
private SSLEngine createSSLEngine(LDAPConnectionHandlerCfg config, SSLContext sslContext) throws DirectoryException {
    try {
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        final Set<String> protocols = config.getSSLProtocol();
        if (!protocols.isEmpty()) {
            sslEngine.setEnabledProtocols(protocols.toArray(new String[0]));
        }
        final Set<String> ciphers = config.getSSLCipherSuite();
        if (!ciphers.isEmpty()) {
            sslEngine.setEnabledCipherSuites(ciphers.toArray(new String[0]));
        }
        switch(config.getSSLClientAuthPolicy()) {
            case DISABLED:
                sslEngine.setNeedClientAuth(false);
                sslEngine.setWantClientAuth(false);
                break;
            case REQUIRED:
                sslEngine.setWantClientAuth(true);
                sslEngine.setNeedClientAuth(true);
                break;
            case OPTIONAL:
            default:
                sslEngine.setNeedClientAuth(false);
                sslEngine.setWantClientAuth(true);
                break;
        }
        return sslEngine;
    } catch (Exception e) {
        if (debugEnabled()) {
            TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
        ResultCode resCode = DirectoryServer.getServerErrorResultCode();
        Message message = ERR_CONNHANDLER_SSL_CANNOT_INITIALIZE.get(getExceptionMessage(e));
        throw new DirectoryException(resCode, message, e);
    }
}
Example 20
Project: resin-master  File: JsseSSLFactory.java View source code
private SSLServerSocketFactory createAnonymousFactory(InetAddress hostAddr, int port) throws IOException, GeneralSecurityException {
    SSLContext sslContext = SSLContext.getInstance(_sslContext);
    String[] cipherSuites = _cipherSuites;
    /*
    if (cipherSuites == null) {
      cipherSuites = sslContext.createSSLEngine().getSupportedCipherSuites();
    }
    */
    String selfSignedName = _selfSignedName;
    if (selfSignedName == null || "".equals(selfSignedName) || "*".equals(selfSignedName)) {
        if (hostAddr != null)
            selfSignedName = hostAddr.getHostName();
        else {
            InetAddress addr = InetAddress.getLocalHost();
            selfSignedName = addr.getHostAddress();
        }
    }
    SelfSignedCert cert = createSelfSignedCert(selfSignedName, cipherSuites);
    if (cert == null)
        throw new ConfigException(L.l("Cannot generate anonymous certificate"));
    sslContext.init(cert.getKeyManagers(), null, null);
    // SSLEngine engine = sslContext.createSSLEngine();
    SSLServerSocketFactory factory = sslContext.getServerSocketFactory();
    return factory;
}