forked from marianobarrios/tls-channel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleBlockingServer.java
77 lines (64 loc) · 3.01 KB
/
SimpleBlockingServer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package tlschannel.example;
import tlschannel.ServerTlsChannel;
import tlschannel.TlsChannel;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
/**
* <p> Server example. Accepts one connection and echos bytes sent by the client into standard output.</p>
* <p> To test, use: </p>
* <code>
* openssl s_client -connect localhost:10000
* </code>
*/
public class SimpleBlockingServer {
private static final Charset utf8 = StandardCharsets.UTF_8;
public static void main(String[] args) throws IOException, GeneralSecurityException {
// initialize the SSLContext, a configuration holder, reusable object
SSLContext sslContext = authenticatedContext("TLSv1.2");
// connect server socket channel normally
try (ServerSocketChannel serverSocket = ServerSocketChannel.open()) {
serverSocket.socket().bind(new InetSocketAddress(10000));
// accept raw connections normally
System.out.println("Waiting for connection...");
try (SocketChannel rawChannel = serverSocket.accept()) {
// create TlsChannel builder, combining the raw channel and the SSLEngine, using minimal options
ServerTlsChannel.Builder builder = ServerTlsChannel.newBuilder(rawChannel, sslContext);
// instantiate TlsChannel
try (TlsChannel tlsChannel = builder.build()) {
// write to stdout all data sent by the client
ByteBuffer res = ByteBuffer.allocate(10000);
while (tlsChannel.read(res) != -1) {
res.flip();
System.out.print(utf8.decode(res).toString());
res.compact();
}
}
}
}
}
static SSLContext authenticatedContext(String protocol) throws GeneralSecurityException, IOException {
SSLContext sslContext = SSLContext.getInstance(protocol);
KeyStore ks = KeyStore.getInstance("JKS");
try (InputStream keystoreFile =
SimpleBlockingServer.class.getClassLoader().getResourceAsStream("keystore.jks")) {
ks.load(keystoreFile, "password".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, "password".toCharArray());
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
return sslContext;
}
}
}