List of usage examples for io.netty.handler.ssl.util SelfSignedCertificate privateKey
File privateKey
To view the source code for io.netty.handler.ssl.util SelfSignedCertificate privateKey.
Click Source Link
From source file:reactor.ipc.netty.http.client.HttpClientTest.java
License:Open Source License
@Test public void secureSendFile() throws CertificateException, SSLException, InterruptedException { Path largeFile = Paths.get(getClass().getResource("/largeFile.txt").getFile()); SelfSignedCertificate ssc = new SelfSignedCertificate(); SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); SslContext sslClient = SslContextBuilder.forClient().trustManager(ssc.cert()).build(); AtomicReference<String> uploaded = new AtomicReference<>(); NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer)) .newRouter(//from w ww.j a va2s. c o m r -> r.post("/upload", (req, resp) -> req.receive().aggregate().asString().doOnNext(uploaded::set) .then(resp.status(201).sendString(Mono.just("Received File")).then()))) .block(); HttpClientResponse response = HttpClient .create(opt -> opt.port(context.address().getPort()).sslContext(sslClient)) .post("/upload", r -> r.sendFile(largeFile)).block(Duration.ofSeconds(120)); context.dispose(); context.onClose().block(); String responseBody = response.receive().aggregate().asString().block(); assertThat(response.status().code()).isEqualTo(201); assertThat(responseBody).isEqualTo("Received File"); assertThat(uploaded.get()) .startsWith( "This is an UTF-8 file that is larger than 1024 bytes.\n" + "It contains accents like .") .contains("1024 mark here -><- 1024 mark here").endsWith("End of File"); }
From source file:reactor.ipc.netty.http.server.HttpServerTests.java
License:Open Source License
@Test public void secureSendFile() throws CertificateException, SSLException, InterruptedException { Path largeFile = Paths.get(getClass().getResource("/largeFile.txt").getFile()); SelfSignedCertificate ssc = new SelfSignedCertificate(); SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); SslContext sslClient = SslContextBuilder.forClient().trustManager(ssc.cert()).build(); NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer)) .newHandler((req, resp) -> resp.sendFile(largeFile)).block(); HttpClientResponse response = HttpClient .create(opt -> opt.port(context.address().getPort()).sslContext(sslClient)).get("/foo") .block(Duration.ofSeconds(120)); context.dispose();// w ww .j a v a2s .c o m context.onClose().block(); String body = response.receive().aggregate().asString().block(); assertThat(body) .startsWith( "This is an UTF-8 file that is larger than 1024 bytes.\n" + "It contains accents like .") .contains("1024 mark here -><- 1024 mark here").endsWith("End of File"); }
From source file:reactor.ipc.netty.NettyOutboundTest.java
License:Open Source License
@Test public void sendFileWithTlsUsesChunkedFile() throws URISyntaxException, NoSuchAlgorithmException, SSLException, CertificateException { SelfSignedCertificate ssc = new SelfSignedCertificate(); SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); final SslHandler sslHandler = sslCtx.newHandler(ByteBufAllocator.DEFAULT); List<Class<?>> messageWritten = new ArrayList<>(2); List<Object> clearMessages = new ArrayList<>(2); EmbeddedChannel channel = new EmbeddedChannel( //outbound: pipeline reads inverted //bytes are encrypted sslHandler,//from www . j a v a 2s . c o m //capture the chunks unencrypted, transform as Strings: new MessageToMessageEncoder<ByteBuf>() { @Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { clearMessages.add(msg.toString(CharsetUtil.UTF_8)); out.add(msg.retain()); //the encoder will release the buffer, make sure it is retained for SslHandler } }, //transform the ChunkedFile into ByteBuf chunks: new ChunkedWriteHandler(), //helps to ensure a ChunkedFile was written outs new MessageToMessageEncoder<Object>() { @Override protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception { messageWritten.add(msg.getClass()); //passing the ChunkedFile through this method releases it, which is undesired ReferenceCountUtil.retain(msg); out.add(msg); } }); NettyContext mockContext = () -> channel; NettyOutbound outbound = new NettyOutbound() { @Override public NettyContext context() { return mockContext; } @Override public FileChunkedStrategy getFileChunkedStrategy() { return FILE_CHUNKED_STRATEGY_1024_NOPIPELINE; } }; channel.writeOneOutbound(1); try { outbound.sendFile(Paths.get(getClass().getResource("/largeFile.txt").toURI())).then() .block(Duration.ofSeconds(1)); //TODO investigate why this hangs } catch (IllegalStateException e) { if (!"Timeout on blocking read for 1000 MILLISECONDS".equals(e.getMessage())) throw e; System.err.println(e); } assertThat(messageWritten).containsExactly(Integer.class, ChunkedFile.class); assertThat(clearMessages).hasSize(2).element(0).asString().startsWith( "This is an UTF-8 file that is larger than 1024 bytes.\nIt contains accents like .\nGARBAGE") .endsWith("1024 mark here ->"); assertThat(clearMessages).element(1).asString().startsWith("<- 1024 mark here").endsWith("End of File"); }
From source file:reactor.ipc.netty.options.ServerOptions.java
License:Open Source License
/** * Enable SSL service with a self-signed certificate and allows extra * parameterization of the self signed {@link SslContextBuilder}. The builder is * then used to invoke {@link #sslContext(SslContext)}. * * @param configurator the builder callback to setup the self-signed {@link SslContextBuilder} * * @return {@code this}/*from w w w .j a v a 2 s . c o m*/ */ public ServerOptions sslSelfSigned(Consumer<? super SslContextBuilder> configurator) { Objects.requireNonNull(configurator, "configurator"); SelfSignedCertificate ssc; try { ssc = new SelfSignedCertificate(); SslContextBuilder builder = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()); configurator.accept(builder); return sslContext(builder.build()); } catch (Exception sslException) { throw Exceptions.bubble(sslException); } }
From source file:server.telnet.TelnetServer.java
License:Apache License
public Channel start() throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {//from w w w . j a v a2s. c o m SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new TelnetServerInitializer(sslCtx)); // b.bind(PORT).sync();// .channel().closeFuture().sync(); Channel ch = b.bind(PORT).sync().channel(); return ch; } finally { // bossGroup.shutdownGracefully(); // workerGroup.shutdownGracefully(); } }
From source file:subterranean.crimson.server.network.ClientListener.java
License:Open Source License
public ClientListener(String n, int p, SecretKeySpec k, EncType enc, boolean u, boolean s) { SSL = s;// ww w . j a v a 2 s .c o m PORT = p; UPNP = u; key = k; encryption = enc; connections = new ArrayList<Connection>(); if (SSL) { try { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SSLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { sslCtx = null; } this.start(); }
From source file:taichu.kafka.test.netty4.example.EchoServer.EchoServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*from w ww. ja va 2 s .c o m*/ SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100) // .option(ChannelOption., 100) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } //p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new EchoServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:test.httpupload.HttpUploadClient.java
License:Apache License
public static void main(String[] args) throws Exception { String postSimple, postFile, get; if (BASE_URL.endsWith("/")) { postSimple = BASE_URL + "formpost"; postFile = BASE_URL + "formpostmultipart"; get = BASE_URL + "formget"; } else {/*from w ww .j a v a 2 s . co m*/ postSimple = BASE_URL + "/formpost"; postFile = BASE_URL + "/formpostmultipart"; get = BASE_URL + "/formget"; } URI uriSimple = new URI(postFile); String scheme = uriSimple.getScheme() == null ? "http" : uriSimple.getScheme(); String host = uriSimple.getHost() == null ? "127.0.0.1" : uriSimple.getHost(); int port = uriSimple.getPort(); if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { port = 80; } else if ("https".equalsIgnoreCase(scheme)) { port = 443; } } if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) { System.err.println("Only HTTP(S) is supported."); return; } final boolean ssl = "https".equalsIgnoreCase(scheme); final SslContext sslCtx; if (ssl) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } else { sslCtx = null; } URI uriFile = new URI(postFile); File file = new File(FILE); if (!file.canRead()) { throw new FileNotFoundException(FILE); } // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); // setup the factory: here using a mixed memory/disk based on size threshold HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) DiskFileUpload.baseDirectory = null; // system temp directory DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit) DiskAttribute.baseDirectory = null; // system temp directory try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientIntializer(sslCtx)); // // Simple Get form: no factory used (not usable) List<Entry<String, String>> headers = formget(b, host, port, get, uriSimple); if (headers == null) { factory.cleanAllHttpData(); return; } // Simple Post form: factory used for big attributes List<InterfaceHttpData> bodylist = formpost(b, host, port, uriSimple, file, factory, headers); if (bodylist == null) { factory.cleanAllHttpData(); return; } // Multipart Post form: factory used formpostmultipart(b, host, port, uriFile, factory, headers, bodylist); } finally { // Shut down executor threads to exit. group.shutdownGracefully(); // Really clean all temporary files if they still exist factory.cleanAllHttpData(); } }
From source file:uidserver.UIDServer.java
/** * @param args the command line arguments *//* ww w . j av a 2 s. c om*/ public static void main(String[] args) throws Exception { if (args.length == 1) { if (args[0].toLowerCase().contains("help")) { System.out.println("This script can only run in Java 1.8"); System.out.println("java -jar ./UIDServer.jar " + "./config.xml"); System.exit(0); } else { new Config(args[0]); } } else { new Config("D:/projects/UIDTest/server/config.xml"); } new UIDGenerator(); final int PORT = Integer.parseInt(System.getProperty("port", Config.port)); SelfSignedCertificate ssc = new SelfSignedCertificate(); SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new UIDServerInitializer(sslCtx)); b.bind(PORT).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:websocketx.server.WebSocketServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*w w w .j a v a 2 s .c om*/ SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } new Thread(new Runnable() { public void run() { while (true) { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("channelGroup:" + WebSocketFrameHandler.channelGroup); System.out.println("channelGroup.isEmpty():" + WebSocketFrameHandler.channelGroup.isEmpty()); System.out.println("channelGroupMap:" + WebSocketFrameHandler.channelGroupMap); } } }).start(); EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new WebSocketServerInitializer(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); System.out.println("Open your web browser and navigate to " + (SSL ? "https" : "http") + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }