Java Code Examples for javax.net.ssl.SSLContext#createSSLEngine()

The following examples show how to use javax.net.ssl.SSLContext#createSSLEngine() . 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: OvsdbConnectionService.java    From ovsdb with Eclipse Public License 1.0 7 votes vote down vote up
@Override
void initChannelImpl(final SocketChannel channel) {
    /* Add SSL handler first if SSL context is provided */
    final SSLContext sslContext = certManagerSrv.getServerContext();
    if (sslContext != null) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false); // work in a server mode
        engine.setNeedClientAuth(true); // need client authentication
        if (protocols != null && protocols.length > 0) {
            //Set supported protocols
            engine.setEnabledProtocols(protocols);
            LOG.debug("Supported ssl protocols {}",
                Arrays.toString(engine.getSupportedProtocols()));
            LOG.debug("Enabled ssl protocols {}",
                Arrays.toString(engine.getEnabledProtocols()));
        }
        if (cipherSuites != null && cipherSuites.length > 0) {
            //Set supported cipher suites
            engine.setEnabledCipherSuites(cipherSuites);
            LOG.debug("Enabled cipher suites {}",
                Arrays.toString(engine.getEnabledCipherSuites()));
        }
        channel.pipeline().addLast("ssl", new SslHandler(engine));
    }
    super.initChannelImpl(channel);
}
 
Example 2
Source File: HttpChannelInitializer.java    From netstrap with Apache License 2.0 6 votes vote down vote up
/**
    * 初始化SSL
    */
private void initSSL(ChannelPipeline pipeline, SslConfig ssl) throws Exception {
       KeyStore ks = KeyStore.getInstance("JKS");

       InputStream ksInputStream = HttpChannelInitializer.class.getResourceAsStream(ssl.getJksPath());
       ks.load(ksInputStream, ssl.getJksPwd().toCharArray());
       KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
       kmf.init(ks,ssl.getJksPwd().toCharArray());
       SSLContext sslCtx = SSLContext.getInstance("TLS");
       sslCtx.init(kmf.getKeyManagers(), null, null);

       SSLEngine engine = sslCtx.createSSLEngine();
       engine.setUseClientMode(false);
       engine.setNeedClientAuth(false);
       pipeline.addLast("ssl",new SslHandler(engine));
   }
 
Example 3
Source File: SSLEngineTestCase.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns client ssl engine.
 *
 * @param context - SSLContext to get SSLEngine from.
 * @param useSNI  - flag used to enable or disable using SNI extension.
 *                Needed for Kerberos.
 */
public static SSLEngine getClientSSLEngine(
        SSLContext context, boolean useSNI) {

    SSLEngine clientEngine = context.createSSLEngine(HOST, 80);
    clientEngine.setUseClientMode(true);
    if (useSNI) {
        SNIHostName serverName = new SNIHostName(SERVER_NAME);
        List<SNIServerName> serverNames = new ArrayList<>();
        serverNames.add(serverName);
        SSLParameters params = clientEngine.getSSLParameters();
        params.setServerNames(serverNames);
        clientEngine.setSSLParameters(params);
    }
    return clientEngine;
}
 
Example 4
Source File: SSLSocketChannel.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public SSLSocketChannel(final SSLContext sslContext, final String hostname, final int port, final InetAddress localAddress, final boolean client) throws IOException {
    this.socketAddress = new InetSocketAddress(hostname, port);
    this.channel = SocketChannel.open();
    if (localAddress != null) {
        final SocketAddress localSocketAddress = new InetSocketAddress(localAddress, 0);
        this.channel.bind(localSocketAddress);
    }
    this.hostname = hostname;
    this.port = port;
    this.engine = sslContext.createSSLEngine();
    this.engine.setUseClientMode(client);
    engine.setNeedClientAuth(true);

    streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
}
 
Example 5
Source File: AbstractBootstrapServer.java    From InChat with Apache License 2.0 6 votes vote down vote up
/**
 * @param channelPipeline  channelPipeline
 * @param serverBean  服务配置参数
 */
protected  void initHandler(ChannelPipeline channelPipeline, InitNetty serverBean){
    if (serverBean.isSsl()){
        if (!ObjectUtils.allNotNull(serverBean.getJksCertificatePassword(),serverBean.getJksFile(),serverBean.getJksStorePassword())){
            throw new NullPointerException(UndefinedInChatConstant.SSL_NOT_FIND);
        }
        try {
            SSLContext context = SslUtil.createSSLContext("JKS",serverBean.getJksFile(),serverBean.getJksStorePassword());
            SSLEngine engine = context.createSSLEngine();
            engine.setUseClientMode(false);
            engine.setNeedClientAuth(false);
            channelPipeline.addLast(BootstrapConstant.SSL,new SslHandler(engine));
            System.out.println("open ssl  success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    intProtocolHandler(channelPipeline,serverBean);
    channelPipeline.addLast(new IdleStateHandler(serverBean.getHeart(),0,0));
    channelPipeline.addLast(new DefaultAbstractHandler(new AbstractHandlerService(ConfigManager.inChatVerifyService, ConfigManager.asyncListener)));
}
 
Example 6
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 7
Source File: SSLSocketChannel.java    From nifi with Apache License 2.0 6 votes vote down vote up
public SSLSocketChannel(final SSLContext sslContext, final String hostname, final int port, final InetAddress localAddress, final boolean client) throws IOException {
    this.socketAddress = new InetSocketAddress(hostname, port);
    this.channel = SocketChannel.open();
    if (localAddress != null) {
        final SocketAddress localSocketAddress = new InetSocketAddress(localAddress, 0);
        this.channel.bind(localSocketAddress);
    }
    this.hostname = hostname;
    this.port = port;
    this.engine = sslContext.createSSLEngine();
    this.engine.setUseClientMode(client);
    engine.setNeedClientAuth(true);

    streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
    appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
}
 
Example 8
Source File: SSLStreams.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
SSLStreams(ServerImpl server, SSLContext sslctx, SocketChannel chan) throws IOException {
   this.server = server;
   this.time = server;
   this.sslctx = sslctx;
   this.chan = chan;
   InetSocketAddress addr = (InetSocketAddress)chan.socket().getRemoteSocketAddress();
   this.engine = sslctx.createSSLEngine(addr.getHostName(), addr.getPort());
   this.engine.setUseClientMode(false);
   HttpsConfigurator cfg = server.getHttpsConfigurator();
   this.configureEngine(cfg, addr);
   this.wrapper = new SSLStreams.EngineWrapper(chan, this.engine);
}
 
Example 9
Source File: HttpInitializer.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
private SSLEngine createInsecureSSLEngine() throws KeyManagementException, NoSuchAlgorithmException {
	SSLContext context = SSLContext.getInstance("SSL");
	context.init(null, INSECURE_TRUST_MANAGER, new SecureRandom());
	SSLEngine engine = context.createSSLEngine();
	engine.setUseClientMode(true);
	return engine;
}
 
Example 10
Source File: SSLManager.java    From servicecomb-java-chassis with Apache License 2.0 5 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 11
Source File: SSLStreams.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
SSLStreams(ServerImpl server, SSLContext sslctx, SocketChannel chan) throws IOException {
   this.server = server;
   this.time = server;
   this.sslctx = sslctx;
   this.chan = chan;
   InetSocketAddress addr = (InetSocketAddress)chan.socket().getRemoteSocketAddress();
   this.engine = sslctx.createSSLEngine(addr.getHostName(), addr.getPort());
   this.engine.setUseClientMode(false);
   HttpsConfigurator cfg = server.getHttpsConfigurator();
   this.configureEngine(cfg, addr);
   this.wrapper = new SSLStreams.EngineWrapper(chan, this.engine);
}
 
Example 12
Source File: NettyHelper.java    From PeonyFramwork with Apache License 2.0 5 votes vote down vote up
private static SslHandler createSslHandler(){
    try {
        SSLContext sslContext = createSSLContext("JKS", ClassUtil.getClassLoader().getResource("wss.jks").getPath(), "netty123");
        //SSLEngine 此类允许使用ssl安全套接层协议进行安全通信            
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);
        return new SslHandler(engine);
    }catch (Exception e){
        e.printStackTrace();
        return null;
    }
}
 
Example 13
Source File: SSLStreams.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
SSLStreams(ServerImpl server, SSLContext sslctx, SocketChannel chan) throws IOException {
   this.server = server;
   this.time = server;
   this.sslctx = sslctx;
   this.chan = chan;
   InetSocketAddress addr = (InetSocketAddress)chan.socket().getRemoteSocketAddress();
   this.engine = sslctx.createSSLEngine(addr.getHostName(), addr.getPort());
   this.engine.setUseClientMode(false);
   HttpsConfigurator cfg = server.getHttpsConfigurator();
   this.configureEngine(cfg, addr);
   this.wrapper = new SSLStreams.EngineWrapper(chan, this.engine);
}
 
Example 14
Source File: AcceptLargeFragments.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    SSLContext context = SSLContext.getDefault();

    // set the property before initialization SSLEngine.
    System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");

    SSLEngine cliEngine = context.createSSLEngine();
    cliEngine.setUseClientMode(true);

    SSLEngine srvEngine = context.createSSLEngine();
    srvEngine.setUseClientMode(false);

    SSLSession cliSession = cliEngine.getSession();
    SSLSession srvSession = srvEngine.getSession();

    // check packet buffer sizes.
    if (cliSession.getPacketBufferSize() < 33049 ||
        srvSession.getPacketBufferSize() < 33049) {
            throw new Exception("Don't accept large SSL/TLS fragments");
    }

    // check application data buffer sizes.
    if (cliSession.getApplicationBufferSize() < 32768 ||
        srvSession.getApplicationBufferSize() < 32768) {
            throw new Exception(
                    "Don't accept large SSL/TLS application data ");
    }
}
 
Example 15
Source File: HttpInitializer.java    From The-5zig-Mod with GNU General Public License v3.0 5 votes vote down vote up
private SSLEngine createInsecureSSLEngine() throws KeyManagementException, NoSuchAlgorithmException {
	SSLContext context = SSLContext.getInstance("SSL");
	context.init(null, INSECURE_TRUST_MANAGER, new SecureRandom());
	SSLEngine engine = context.createSSLEngine();
	engine.setUseClientMode(true);
	return engine;
}
 
Example 16
Source File: ClientTlsChannel.java    From tls-channel with MIT License 4 votes vote down vote up
private static SSLEngine defaultSSLEngineFactory(SSLContext sslContext) {
  SSLEngine engine = sslContext.createSSLEngine();
  engine.setUseClientMode(true);
  return engine;
}
 
Example 17
Source File: AsyncTcpSocketSsl.java    From datakernel with Apache License 2.0 4 votes vote down vote up
public static AsyncTcpSocketSsl wrapServerSocket(AsyncTcpSocket asyncTcpSocket,
		SSLContext sslContext, Executor executor) {
	SSLEngine sslEngine = sslContext.createSSLEngine();
	sslEngine.setUseClientMode(false);
	return create(asyncTcpSocket, sslEngine, executor);
}
 
Example 18
Source File: SSLFacade.java    From t-io with Apache License 2.0 4 votes vote down vote up
private SSLEngine makeSSLEngine(SSLContext context, boolean client, boolean clientAuthRequired) {
	SSLEngine engine = context.createSSLEngine();
	engine.setUseClientMode(client);
	engine.setNeedClientAuth(clientAuthRequired);
	return engine;
}
 
Example 19
Source File: SSLEngineFactory.java    From couchbase-jvm-core with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a new {@link SSLEngine} constructed from the config settings.
 *
 * @return a {@link SSLEngine} ready to be used.
 */
public SSLEngine get() {
    try {
        String pass = env.sslKeystorePassword();
        char[] password = pass == null || pass.isEmpty() ? null : pass.toCharArray();

        KeyStore ks = env.sslKeystore();
        if (ks == null) {
            String ksFile = env.sslKeystoreFile();
            if (ksFile != null && !ksFile.isEmpty()) {
                ks = KeyStore.getInstance(KeyStore.getDefaultType());
                ks.load(new FileInputStream(ksFile), password);
            }
        }

        KeyStore ts = env.sslTruststore();
        if (ts == null) {
            String tsFile = env.sslTruststoreFile();
            if (tsFile != null && !tsFile.isEmpty()) {
                // filepath found, open and init
                String tsPassword = env.sslTruststorePassword();
                char[] tspass = tsPassword == null || tsPassword.isEmpty() ? null : tsPassword.toCharArray();
                ts = KeyStore.getInstance(KeyStore.getDefaultType());
                ts.load(new FileInputStream(tsFile), tspass);
            }
        }

        if (ks == null && ts == null) {
            throw new IllegalStateException("Either a KeyStore or a TrustStore " +
                "need to be provided (or both).");
        } else if (ks == null) {
            ks = ts;
            LOGGER.debug("No KeyStore provided, using provided TrustStore to initialize both factories.");
        } else if (ts == null) {
            ts = ks;
            LOGGER.debug("No TrustStore provided, using provided KeyStore to initialize both factories.");
        }

        String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
        kmf.init(ks, password);
        tmf.init(ts);

        if (!sslContextProtocol.startsWith("TLS")) {
            throw new IllegalArgumentException(
                "SSLContext Protocol does not start with TLS, this is to prevent "
                    + "insecure protocols (Like SSL*) to be used. Potential candidates "
                    + "are TLS (default), TLSv1, TLSv1.1, TLSv1.2, TLSv1.3 depending on "
                    + "the Java version used.");
        }
        SSLContext ctx = SSLContext.getInstance(sslContextProtocol);
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        SSLEngine engine = ctx.createSSLEngine(hostname, port);
        engine.setUseClientMode(true);

        if (env.sslHostnameVerificationEnabled()) {
            SSLParameters sslParameters = engine.getSSLParameters();
            sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
            engine.setSSLParameters(sslParameters);
        }
        return engine;
    } catch (Exception ex) {
        throw new SSLException("Could not create SSLEngine.", ex);
    }
}
 
Example 20
Source File: SecureChatClientInitializer.java    From x-pipe with Apache License 2.0 4 votes vote down vote up
private ChannelHandler createSslHandler(SSLContext sslContext) {
    SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(true);
    return new SslHandler(sslEngine);
}