Java Code Examples for javax.net.ssl.SSLEngine

The following are top voted examples for showing how to use javax.net.ssl.SSLEngine. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-servicecomb-java-chassis   File: SSLManager.java   View source code 7 votes vote down vote up
public static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom) {
  SSLContext context = createSSLContext(option, custom);
  SSLEngine engine =
      context.createSSLEngine();
  engine.setEnabledProtocols(option.getProtocols().split(","));
  String[] supported = engine.getSupportedCipherSuites();
  String[] eanbled = option.getCiphers().split(",");
  engine.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled));
  engine.setNeedClientAuth(option.isAuthPeer());
  return engine;
}
 
Example 2
Project: lazycat   File: NioEndpoint.java   View source code 7 votes vote down vote up
protected SSLEngine createSSLEngine() {
	SSLEngine engine = sslContext.createSSLEngine();
	if ("false".equals(getClientAuth())) {
		engine.setNeedClientAuth(false);
		engine.setWantClientAuth(false);
	} else if ("true".equals(getClientAuth()) || "yes".equals(getClientAuth())) {
		engine.setNeedClientAuth(true);
	} else if ("want".equals(getClientAuth())) {
		engine.setWantClientAuth(true);
	}
	engine.setUseClientMode(false);
	engine.setEnabledCipherSuites(enabledCiphers);
	engine.setEnabledProtocols(enabledProtocols);

	configureUseServerCipherSuitesOrder(engine);

	return engine;
}
 
Example 3
Project: kafka-0.11.0.0-src-with-comment   File: SslFactory.java   View source code 7 votes vote down vote up
public SSLEngine createSslEngine(String peerHost, int peerPort) {
    SSLEngine sslEngine = sslContext.createSSLEngine(peerHost, peerPort);
    if (cipherSuites != null) sslEngine.setEnabledCipherSuites(cipherSuites);
    if (enabledProtocols != null) sslEngine.setEnabledProtocols(enabledProtocols);

    // SSLParameters#setEndpointIdentificationAlgorithm enables endpoint validation
    // only in client mode. Hence, validation is enabled only for clients.
    if (mode == Mode.SERVER) {
        sslEngine.setUseClientMode(false);
        if (needClientAuth)
            sslEngine.setNeedClientAuth(needClientAuth);
        else
            sslEngine.setWantClientAuth(wantClientAuth);
    } else {
        sslEngine.setUseClientMode(true);
        SSLParameters sslParams = sslEngine.getSSLParameters();
        sslParams.setEndpointIdentificationAlgorithm(endpointIdentification);
        sslEngine.setSSLParameters(sslParams);
    }
    return sslEngine;
}
 
Example 4
Project: openjdk-jdk10   File: SSLEngineTestCase.java   View source code 6 votes vote down vote up
/**
 * Unwraps data with the specified engine.
 *
 * @param engine       - SSLEngine that unwraps data.
 * @param unwrapper    - Set unwrapper id, e.g. "server" of "client".
 *                       Used for logging only.
 * @param net          - Buffer with data to unwrap.
 * @param wantedStatus - Specifies expected result status of wrapping.
 * @param result       - Array which first element will be used to output
 *                       wrap result object.
 * @return - Buffer with unwrapped data.
 * @throws SSLException - thrown on engine errors.
 */
public static ByteBuffer doUnWrap(SSLEngine engine, String unwrapper,
        ByteBuffer net, SSLEngineResult.Status wantedStatus,
        SSLEngineResult[] result) throws SSLException {

    ByteBuffer app = ByteBuffer.allocate(
            engine.getSession().getApplicationBufferSize());
    int length = net.remaining();
    System.out.println(unwrapper + " unwrapping " + length + " bytes...");
    SSLEngineResult r = engine.unwrap(net, app);
    app.flip();
    System.out.println(unwrapper + " handshake status is "
            + engine.getHandshakeStatus());
    checkResult(r, wantedStatus);
    if (result != null && result.length > 0) {
        result[0] = r;
    }
    return app;
}
 
Example 5
Project: incubator-servicecomb-java-chassis   File: SSLManagerTest.java   View source code 6 votes vote down vote up
@Test
public void testCreateSSLEngine() {
  SSLOption option = SSLOption.build(DIR + "/server.ssl.properties");
  SSLCustom custom = new SSLCustom() {
    @Override
    public String getFullPath(String filename) {
      return DIR + "/ssl/" + filename;
    }

    @Override
    public char[] decode(char[] encrypted) {
      return encrypted;
    }
  };

  SSLEngine aSSLEngine = SSLManager.createSSLEngine(option, custom);
  Assert.assertEquals(false, aSSLEngine.getUseClientMode());
  Assert.assertNotNull(aSSLEngine);
}
 
Example 6
Project: incubator-servicecomb-java-chassis   File: SSLManagerTest.java   View source code 6 votes vote down vote up
@Test
public void testCreateSSLEnginewithPort() {
  SSLOption option = SSLOption.build(DIR + "/server.ssl.properties");
  SSLCustom custom = new SSLCustom() {
    @Override
    public String getFullPath(String filename) {
      return DIR + "/ssl/" + filename;
    }

    @Override
    public char[] decode(char[] encrypted) {
      return encrypted;
    }
  };

  int port = 39093;
  String peerHost = "host1";
  SSLEngine aSSLEngine = SSLManager.createSSLEngine(option, custom, peerHost, port);
  Assert.assertNotNull(aSSLEngine);
  Assert.assertEquals("host1", aSSLEngine.getPeerHost().toString());
}
 
Example 7
Project: incubator-servicecomb-java-chassis   File: TestTrustAllManager.java   View source code 6 votes vote down vote up
@Test
public void testTrustAllManager() throws Exception {
  TrustAllManager manager = new TrustAllManager();
  manager.checkClientTrusted((X509Certificate[]) null, (String) null);
  manager.checkServerTrusted((X509Certificate[]) null, (String) null);

  manager.checkClientTrusted((X509Certificate[]) null,
      (String) null,
      (Socket) null);
  manager.checkClientTrusted((X509Certificate[]) null,
      (String) null,
      (SSLEngine) null);

  manager.checkServerTrusted((X509Certificate[]) null,
      (String) null,
      (Socket) null);
  manager.checkServerTrusted((X509Certificate[]) null,
      (String) null,
      (SSLEngine) null);
  Assert.assertEquals(manager.getAcceptedIssuers() == null, true);
}
 
Example 8
Project: onedatashare   File: HTTPInitializer.java   View source code 6 votes vote down vote up
/**
 * Adds pipelines to channel.
 * 
 *  @param ch channel to be operated on
 */
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipe = ch.pipeline();

  if (ssl) {
    // HTTPs connection
    SSLEngine sslEng = getSsl(null);
    sslEng.setUseClientMode(true);
    pipe.addLast("SSL", new SslHandler(sslEng, false));
  }

  pipe.addFirst("Timer", new ReadTimeoutHandler(30));
  pipe.addLast("Codec", new HttpClientCodec());
  pipe.addLast("Inflater", new HttpContentDecompressor());
  pipe.addLast("Handler", new HTTPMessageHandler(builder));
}
 
Example 9
Project: Responder-Android   File: SSLSocketChannel2.java   View source code 6 votes vote down vote up
public SSLSocketChannel2( SocketChannel channel , SSLEngine sslEngine , ExecutorService exec , SelectionKey key ) throws IOException {
	if( channel == null || sslEngine == null || exec == null )
		throw new IllegalArgumentException( "parameter must not be null" );

	this.socketChannel = channel;
	this.sslEngine = sslEngine;
	this.exec = exec;

	readEngineResult = writeEngineResult = new SSLEngineResult( Status.BUFFER_UNDERFLOW, sslEngine.getHandshakeStatus(), 0, 0 ); // init to prevent NPEs

	tasks = new ArrayList<Future<?>>( 3 );
	if( key != null ) {
		key.interestOps( key.interestOps() | SelectionKey.OP_WRITE );
		this.selectionKey = key;
	}
	createBuffers( sslEngine.getSession() );
	// kick off handshake
	socketChannel.write( wrap( emptybuffer ) );// initializes res
	processHandshake();
}
 
Example 10
Project: openjdk-jdk10   File: DTLSIncorrectAppDataTest.java   View source code 6 votes vote down vote up
private void checkIncorrectAppDataUnwrap(SSLEngine sendEngine,
        SSLEngine recvEngine) throws SSLException {
    String direction = sendEngine.getUseClientMode() ? "client"
            : "server";
    System.out.println("================================================="
            + "===========");
    System.out.println("Testing DTLS incorrect app data packages unwrapping"
            + " by sending data from " + direction);
    ByteBuffer app = ByteBuffer.wrap(MESSAGE.getBytes());
    ByteBuffer net = doWrap(sendEngine, direction, 0, app);
    final Random RNG = RandomFactory.getRandom();
    int randomPlace = RNG.nextInt(net.remaining());
    net.array()[randomPlace] += 1;
    app = ByteBuffer.allocate(recvEngine.getSession()
            .getApplicationBufferSize());
    recvEngine.unwrap(net, app);
    app.flip();
    int length = app.remaining();
    System.out.println("Unwrapped " + length + " bytes.");
}
 
Example 11
Project: flume-release-1.7.0   File: TestAvroSource.java   View source code 6 votes vote down vote up
@Override
public SocketChannel newChannel(ChannelPipeline pipeline) {
  try {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[]{new PermissiveTrustManager()},
                    null);
    SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(true);
    // addFirst() will make SSL handling the first stage of decoding
    // and the last stage of encoding
    pipeline.addFirst("ssl", new SslHandler(sslEngine));
    return super.newChannel(pipeline);
  } catch (Exception ex) {
    throw new RuntimeException("Cannot create SSL channel", ex);
  }
}
 
Example 12
Project: Stork   File: HTTPInitializer.java   View source code 6 votes vote down vote up
/**
 * Adds pipelines to channel.
 * 
 *  @param ch channel to be operated on
 */
protected void initChannel(SocketChannel ch) throws Exception {
  ChannelPipeline pipe = ch.pipeline();

  if (ssl) {
    // HTTPs connection
    SSLEngine sslEng = getSsl(null);
    sslEng.setUseClientMode(true);
    pipe.addLast("SSL", new SslHandler(sslEng, false));
  }

  pipe.addFirst("Timer", new ReadTimeoutHandler(30));
  pipe.addLast("Codec", new HttpClientCodec());
  pipe.addLast("Inflater", new HttpContentDecompressor());
  pipe.addLast("Handler", new HTTPMessageHandler(builder));
}
 
Example 13
Project: openjdk-jdk10   File: SSLEngineTestCase.java   View source code 6 votes vote down vote up
/**
 * Wraps data with the specified engine.
 *
 * @param engine        - SSLEngine that wraps data.
 * @param wrapper       - Set wrapper id, e.g. "server" of "client".
 *                        Used for logging only.
 * @param maxPacketSize - Max packet size to check that MFLN extension
 *                        works or zero for no check.
 * @param app           - Buffer with data to wrap.
 * @param wantedStatus  - Specifies expected result status of wrapping.
 * @param result        - Array which first element will be used to output
 *                        wrap result object.
 * @return - Buffer with wrapped data.
 * @throws SSLException - thrown on engine errors.
 */
public static ByteBuffer doWrap(SSLEngine engine, String wrapper,
                                int maxPacketSize, ByteBuffer app,
                                SSLEngineResult.Status wantedStatus,
                                SSLEngineResult[] result)
        throws SSLException {
    ByteBuffer net = ByteBuffer.allocate(engine.getSession()
            .getPacketBufferSize());
    SSLEngineResult r = engine.wrap(app, net);
    net.flip();
    int length = net.remaining();
    System.out.println(wrapper + " wrapped " + length + " bytes.");
    System.out.println(wrapper + " handshake status is "
            + engine.getHandshakeStatus());
    if (maxPacketSize < length && maxPacketSize != 0) {
        throw new AssertionError("Handshake wrapped net buffer length "
                + length + " exceeds maximum packet size "
                + maxPacketSize);
    }
    checkResult(r, wantedStatus);
    if (result != null && result.length > 0) {
        result[0] = r;
    }
    return net;
}
 
Example 14
Project: apache-tomcat-7.0.73-with-comment   File: NioEndpoint.java   View source code 6 votes vote down vote up
protected SSLEngine createSSLEngine() {
    SSLEngine engine = sslContext.createSSLEngine();
    if ("false".equals(getClientAuth())) {
        engine.setNeedClientAuth(false);
        engine.setWantClientAuth(false);
    } else if ("true".equals(getClientAuth()) || "yes".equals(getClientAuth())){
        engine.setNeedClientAuth(true);
    } else if ("want".equals(getClientAuth())) {
        engine.setWantClientAuth(true);
    }
    engine.setUseClientMode(false);
    engine.setEnabledCipherSuites(enabledCiphers);
    engine.setEnabledProtocols(enabledProtocols);

    configureUseServerCipherSuitesOrder(engine);

    return engine;
}
 
Example 15
Project: boohee_v5.6   File: SSLSocketChannel2.java   View source code 6 votes vote down vote up
public SSLSocketChannel2(SocketChannel channel, SSLEngine sslEngine, ExecutorService exec, SelectionKey key) throws IOException {
    if (channel == null || sslEngine == null || exec == null) {
        throw new IllegalArgumentException("parameter must not be null");
    }
    this.socketChannel = channel;
    this.sslEngine = sslEngine;
    this.exec = exec;
    this.tasks = new ArrayList(3);
    if (key != null) {
        key.interestOps(key.interestOps() | 4);
        this.selectionKey = key;
    }
    createBuffers(sslEngine.getSession());
    this.socketChannel.write(wrap(emptybuffer));
    processHandshake();
}
 
Example 16
Project: openjdk-jdk10   File: BufferOverflowUnderflowTest.java   View source code 6 votes vote down vote up
private void checkBufferOverflowOnUnWrap(SSLEngine wrappingEngine,
        SSLEngine unwrappingEngine)
        throws SSLException {
    String wrapperMode = wrappingEngine.getUseClientMode() ? "client"
            : "server";
    String unwrapperMode = unwrappingEngine.getUseClientMode() ? "client"
            : "server";
    if (wrapperMode.equals(unwrapperMode)) {
        throw new Error("Test error: both engines are in the same mode!");
    }
    System.out.println("================================================="
            + "===========");
    System.out.println("Testing SSLEngine buffer overflow"
            + " on unwrap by " + unwrapperMode);
    ByteBuffer app = ByteBuffer.wrap(MESSAGE.getBytes());
    ByteBuffer net = ByteBuffer
            .allocate(wrappingEngine.getSession().getPacketBufferSize());
    SSLEngineResult r = wrappingEngine.wrap(app, net);
    checkResult(r, SSLEngineResult.Status.OK);
    //Making app buffer size less than required by 1 byte.
    app = ByteBuffer.allocate(MESSAGE.length() - 1);
    net.flip();
    r = unwrappingEngine.unwrap(net, app);
    checkResult(r, SSLEngineResult.Status.BUFFER_OVERFLOW);
    System.out.println("Passed");
}
 
Example 17
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedTrustManagerTest.java   View source code 5 votes vote down vote up
@Test
public void checkServerTrustedSslEngineNonePass() throws CertificateException {
    X509Certificate[] x509Certificates = new X509Certificate[0];
    String s = "";
    SSLEngine sslEngine = mock(SSLEngine.class);

    doThrow(new CertificateException("1")).when(this.trustManager1).checkServerTrusted(x509Certificates, s, sslEngine);
    doThrow(new CertificateException("2")).when(this.trustManager2).checkServerTrusted(x509Certificates, s, sslEngine);

    try {
        this.delegatingTrustManager.checkServerTrusted(x509Certificates, s, sslEngine);
    } catch (CertificateException e) {
        assertThat(e).hasMessage("2");
    }
}
 
Example 18
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedKeyManagerTest.java   View source code 5 votes vote down vote up
@Test
public void chooseEngineServerAliasNone() {
    String s = "";
    Principal[] principals = new Principal[0];
    SSLEngine sslEngine = mock(SSLEngine.class);

    assertThat(this.delegatingKeyManager.chooseEngineServerAlias(s, principals, sslEngine)).isNull();
}
 
Example 19
Project: incubator-servicecomb-java-chassis   File: SSLManager.java   View source code 5 votes vote down vote up
public static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom, String peerHost, int peerPort) {
  SSLContext context = createSSLContext(option, custom);
  SSLEngine engine =
      context.createSSLEngine(peerHost, peerPort);
  engine.setEnabledProtocols(option.getProtocols().split(","));
  String[] supported = engine.getSupportedCipherSuites();
  String[] eanbled = option.getCiphers().split(",");
  engine.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled));
  engine.setNeedClientAuth(option.isAuthPeer());
  return engine;
}
 
Example 20
Project: incubator-servicecomb-java-chassis   File: TrustManagerExt.java   View source code 5 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType,
    SSLEngine engine) throws CertificateException {
  if (!option.isAuthPeer()) {
    return;
  }

  String ip = null;
  if (engine != null) {
    SSLSession session = engine.getHandshakeSession();
    ip = session.getPeerHost();
  }
  checkTrustedCustom(chain, ip);
  trustManager.checkClientTrusted(chain, authType, engine);
}
 
Example 21
Project: incubator-servicecomb-java-chassis   File: TrustManagerExtTest.java   View source code 5 votes vote down vote up
@Test
public void testCheckClientTrusted(@Mocked CertificateUtil certificateUtil) {
  MyX509Certificate myX509Certificate1 = new MyX509Certificate();
  MyX509Certificate myX509Certificate2 = new MyX509Certificate();

  MyX509Certificate[] MyX509CertificateArray = new MyX509Certificate[2];
  MyX509CertificateArray[0] = myX509Certificate1;
  MyX509CertificateArray[1] = myX509Certificate2;

  new Expectations() {
    {
      CertificateUtil.findOwner((X509Certificate[]) any);
      result = any;

      CertificateUtil.getCN((X509Certificate) any);
      result = "10.67.147.115";
    }
  };

  MyX509ExtendedTrustManager myX509ExtendedTrustManager = new MyX509ExtendedTrustManager();
  TrustManagerExt trustManagerExt = new TrustManagerExt(myX509ExtendedTrustManager, option, custom);

  Socket socket = null;
  SSLEngine sslengine = null;
  boolean validAssert = true;
  try {
    trustManagerExt.checkClientTrusted(MyX509CertificateArray, "pks", socket);
    trustManagerExt.checkClientTrusted(MyX509CertificateArray, "pks", sslengine);
    trustManagerExt.checkServerTrusted(MyX509CertificateArray, "pks", socket);
    trustManagerExt.checkServerTrusted(MyX509CertificateArray, "pks", sslengine);
  } catch (Exception e) {
    validAssert = false;
  }
  Assert.assertTrue(validAssert);
}
 
Example 22
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedKeyManagerTest.java   View source code 5 votes vote down vote up
@Test
public void chooseEngineClientAliasFirst() {
    String[] strings = new String[0];
    Principal[] principals = new Principal[0];
    SSLEngine sslEngine = mock(SSLEngine.class);

    String alias = "alias";
    when(this.keyManager1.chooseEngineClientAlias(strings, principals, sslEngine)).thenReturn(alias);

    assertThat(this.delegatingKeyManager.chooseEngineClientAlias(strings, principals, sslEngine)).isEqualTo(alias);
}
 
Example 23
Project: hadoop-oss   File: SSLFactory.java   View source code 5 votes vote down vote up
/**
 * Returns a configured SSLEngine.
 *
 * @return the configured SSLEngine.
 * @throws GeneralSecurityException thrown if the SSL engine could not
 * be initialized.
 * @throws IOException thrown if and IO error occurred while loading
 * the server keystore.
 */
public SSLEngine createSSLEngine()
  throws GeneralSecurityException, IOException {
  SSLEngine sslEngine = context.createSSLEngine();
  if (mode == Mode.CLIENT) {
    sslEngine.setUseClientMode(true);
  } else {
    sslEngine.setUseClientMode(false);
    sslEngine.setNeedClientAuth(requireClientCert);
  }
  sslEngine.setEnabledProtocols(enabledProtocols);
  return sslEngine;
}
 
Example 24
Project: directory-ldap-api   File: NoVerificationTrustManager.java   View source code 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void checkClientTrusted( X509Certificate[] x509Certificates, String authType, SSLEngine engine )
    throws CertificateException 
{
    LOG.debug( "checkClientTrusted {}", x509Certificates[0] );
}
 
Example 25
Project: directory-ldap-api   File: NoVerificationTrustManager.java   View source code 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void checkServerTrusted( X509Certificate[] x509Certificates, String authType, SSLEngine engine )
    throws CertificateException 
{
    LOG.debug( "checkServerTrusted {}", x509Certificates[0] );
}
 
Example 26
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedTrustManagerTest.java   View source code 5 votes vote down vote up
@Test
public void checkClientTrustedSslEngineNonePass() throws CertificateException {
    X509Certificate[] x509Certificates = new X509Certificate[0];
    String s = "";
    SSLEngine sslEngine = mock(SSLEngine.class);

    doThrow(new CertificateException("1")).when(this.trustManager1).checkClientTrusted(x509Certificates, s, sslEngine);
    doThrow(new CertificateException("2")).when(this.trustManager2).checkClientTrusted(x509Certificates, s, sslEngine);

    try {
        this.delegatingTrustManager.checkClientTrusted(x509Certificates, s, sslEngine);
    } catch (CertificateException e) {
        assertThat(e).hasMessage("2");
    }
}
 
Example 27
Project: openjdk-jdk10   File: CipherSuite.java   View source code 5 votes vote down vote up
@Override
SSLEngine createSSLEngine(boolean isClient) throws Exception {
    SSLEngine engine = super.createSSLEngine(isClient);

    if (isClient) {
        engine.setEnabledCipherSuites(new String[]{cipherSuite});
    }

    return engine;
}
 
Example 28
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedKeyManagerTest.java   View source code 5 votes vote down vote up
@Test
public void chooseEngineClientAliasLast() {
    String[] strings = new String[0];
    Principal[] principals = new Principal[0];
    SSLEngine sslEngine = mock(SSLEngine.class);

    String alias = "alias";
    when(this.keyManager2.chooseEngineClientAlias(strings, principals, sslEngine)).thenReturn(alias);

    assertThat(this.delegatingKeyManager.chooseEngineClientAlias(strings, principals, sslEngine)).isEqualTo(alias);
}
 
Example 29
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedTrustManager.java   View source code 5 votes vote down vote up
@Override
public void checkServerTrusted(final X509Certificate[] x509Certificates, final String s, final SSLEngine sslEngine) throws CertificateException {
    with(new Consumer() {

        @Override
        public void accept(X509ExtendedTrustManager delegate) throws CertificateException {
            delegate.checkServerTrusted(x509Certificates, s, sslEngine);
        }

    });
}
 
Example 30
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedTrustManagerTest.java   View source code 5 votes vote down vote up
@Test
public void checkServerTrustedSslEngineFirstPass() throws CertificateException {
    X509Certificate[] x509Certificates = new X509Certificate[0];
    String s = "";
    SSLEngine sslEngine = mock(SSLEngine.class);

    this.delegatingTrustManager.checkServerTrusted(x509Certificates, s, sslEngine);

    verify(this.trustManager1).checkServerTrusted(x509Certificates, s, sslEngine);
    verifyZeroInteractions(this.trustManager2);
}
 
Example 31
Project: onedatashare   File: HTTPInitializer.java   View source code 5 votes vote down vote up
private SSLEngine getSsl(String proto) throws NoSuchAlgorithmException {
  String protocol = (proto == null) ? "TLS" : proto;
  SSLContext context = SSLContext.getInstance(protocol);
  try {
    context.init(null, null, null);
  } catch (KeyManagementException e) {
    System.err.println(e.getMessage());
  }

  return context.createSSLEngine();
}
 
Example 32
Project: tasfe-framework   File: HttpChannelInitializer.java   View source code 5 votes vote down vote up
@Override
 protected void initChannel(SocketChannel ch) throws Exception {
     ChannelPipeline pipeline = ch.pipeline();

     // SSL的安全链接
     if (ServerConfig.isSsl()) {
         SSLContext sslcontext = SSLContext.getInstance("TLS");
         KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
         KeyStore ks = KeyStore.getInstance("JKS");
         String keyStorePath = ServerConfig.getKeyStorePath();
         String keyStorePassword = ServerConfig.getKeyStorePassword();
         ks.load(new FileInputStream(keyStorePath), keyStorePassword.toCharArray());
         String keyPassword = ServerConfig.getKeyPassword();
         kmf.init(ks, keyPassword.toCharArray());
         sslcontext.init(kmf.getKeyManagers(), null, null);
         SSLEngine sslEngine = sslcontext.createSSLEngine();
         sslEngine.setUseClientMode(false);
         sslEngine.setNeedClientAuth(false);
         /**
          * 务必放在第一位
          */
         pipeline.addLast(new SslHandler(sslEngine));
         logger.info("initChannel: addLast SslHandler");
         /**
          * Generates a temporary self-signed certificate for testing purposes.
          */
/*SelfSignedCertificate ssc = new SelfSignedCertificate();
SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
//SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
if (sslCtx != null) {
	pipeline.addLast(sslCtx.newHandler(ch.alloc()));
}*/
     }
     // Register HTTP handler chain.
     this.appendHttpPipeline(pipeline);
 }
 
Example 33
Project: java-buildpack-security-provider   File: DelegatingX509ExtendedKeyManagerTest.java   View source code 5 votes vote down vote up
@Test
public void chooseEngineServerAliasLast() {
    String s = "";
    Principal[] principals = new Principal[0];
    SSLEngine sslEngine = mock(SSLEngine.class);

    String alias = "alias";
    when(this.keyManager2.chooseEngineServerAlias(s, principals, sslEngine)).thenReturn(alias);

    assertThat(this.delegatingKeyManager.chooseEngineServerAlias(s, principals, sslEngine)).isEqualTo(alias);
}
 
Example 34
Project: openjdk-jdk10   File: CipherTestUtils.java   View source code 5 votes vote down vote up
@Override
public String chooseEngineClientAlias(String[] keyType,
        Principal[] issuers, SSLEngine engine) {
    if (authType == null) {
        return null;
    }
    return keyManager.chooseEngineClientAlias(new String[]{authType},
            issuers, engine);
}
 
Example 35
Project: openjdk-jdk10   File: MyX509ExtendedKeyManager.java   View source code 5 votes vote down vote up
@Override
public String chooseEngineServerAlias(String keyType, Principal[] issuers,
        SSLEngine engine) {
    String nap = engine.getHandshakeApplicationProtocol();
    checkALPN(nap);

    return akm.chooseEngineServerAlias(keyType, issuers, engine);
}
 
Example 36
Project: fresco_floodlight   File: OFChannelInitializer.java   View source code 5 votes vote down vote up
@Override
protected void initChannel(Channel ch) throws Exception {
	ChannelPipeline pipeline = ch.pipeline();
	OFChannelHandler handler = new OFChannelHandler(
			switchManager,
			connectionListener,
			pipeline,
			debugCounters,
			timer,
			ofBitmaps,
			defaultFactory);

	if (keyStore != null && keyStorePassword != null) {
		try {
			/* Set up factories and stores. */
			TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
			KeyStore tmpKS = null;
			tmFactory.init(tmpKS);

			/* Use keystore/pass defined in properties file. */
			KeyStore ks = KeyStore.getInstance("JKS");
			ks.load(new FileInputStream(keyStore), keyStorePassword.toCharArray());

			KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			kmf.init(ks, keyStorePassword.toCharArray());

			KeyManager[] km = kmf.getKeyManagers();
			TrustManager[] tm = tmFactory.getTrustManagers();

			/* Set up SSL prereqs for Netty. */
			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(km, tm, null);
			SSLEngine sslEngine = sslContext.createSSLEngine();

			/* We are the server and we will create secure sessions. */
			sslEngine.setUseClientMode(false);
			sslEngine.setEnableSessionCreation(true);

			/* These are redundant (default), but for clarity... */
			sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols()); 
			sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
			
			/* First, decrypt w/handler+engine; then, proceed with rest of handlers. */
			pipeline.addLast(PipelineHandler.SSL_TLS_ENCODER_DECODER, new SslHandler(sslEngine));
			log.info("SSL OpenFlow socket initialized and handler ready for switch.");
		} catch (Exception e) { /* There are lots of possible exceptions to catch, so this should get them all. */
			log.error("Exception initializing SSL OpenFlow socket: {}", e.getMessage());
			throw e; /* If we wanted secure but didn't get it, we should bail. */
		}
	}
	
	pipeline.addLast(PipelineHandler.OF_MESSAGE_DECODER,
			new OFMessageDecoder());
	pipeline.addLast(PipelineHandler.OF_MESSAGE_ENCODER,
			new OFMessageEncoder());
	pipeline.addLast(PipelineHandler.MAIN_IDLE,
			new IdleStateHandler(PipelineIdleReadTimeout.MAIN,
					PipelineIdleWriteTimeout.MAIN,
					0));
	pipeline.addLast(PipelineHandler.READ_TIMEOUT, new ReadTimeoutHandler(30));
	pipeline.addLast(PipelineHandler.CHANNEL_HANDSHAKE_TIMEOUT,
			new HandshakeTimeoutHandler(
					handler,
					timer,
					PipelineHandshakeTimeout.CHANNEL));

	pipeline.addLast(PipelineHandler.CHANNEL_HANDLER, handler);
}
 
Example 37
Project: openjdk-jdk10   File: UnsupportedCiphersTest.java   View source code 5 votes vote down vote up
private void unsupTest(String cipher, boolean clientTest) {
    SSLContext context = getContext();
    SSLEngine clientEngine = context.createSSLEngine();
    clientEngine.setUseClientMode(true);
    SSLEngine serverEngine = context.createSSLEngine();
    serverEngine.setUseClientMode(false);
    if (clientTest) {
        clientEngine.setEnabledCipherSuites(new String[]{cipher});
    } else {
        serverEngine.setEnabledCipherSuites(new String[]{cipher});
    }
}
 
Example 38
Project: openjdk-jdk10   File: MyX509ExtendedKeyManager.java   View source code 5 votes vote down vote up
@Override
public String chooseEngineClientAlias(String[] keyType, Principal[] issuers,
        SSLEngine engine) {
    String nap = engine.getHandshakeApplicationProtocol();
    checkALPN(nap);

    return akm.chooseEngineClientAlias(keyType, issuers, engine);
}
 
Example 39
Project: NioSmtpClient   File: SmtpSession.java   View source code 5 votes vote down vote up
SmtpSession(Channel channel, ResponseHandler responseHandler, SmtpSessionConfig config, Executor executor, Supplier<SSLEngine> sslEngineSupplier) {
  this.channel = channel;
  this.responseHandler = responseHandler;
  this.config = config;
  this.executor = executor;
  this.sslEngineSupplier = sslEngineSupplier;
  this.closeFuture = new CompletableFuture<>();

  this.channel.pipeline().addLast(new ErrorHandler());
}
 
Example 40
Project: openjdk-jdk10   File: HandshakeTest.java   View source code 5 votes vote down vote up
@Override
protected void testOneCipher(String cipher) throws SSLException {
    SSLContext context = getContext();
    int maxPacketSize = getMaxPacketSize();
    boolean useSNI = !TEST_MODE.equals("norm");
    SSLEngine clientEngine = getClientSSLEngine(context, useSNI);
    SSLEngine serverEngine = getServerSSLEngine(context, useSNI);
    clientEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setNeedClientAuth(!cipher.contains("anon"));
    doHandshake(clientEngine, serverEngine, maxPacketSize,
            HandshakeMode.INITIAL_HANDSHAKE);
}