1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.http.websocketx.sslserver;
17
18 import org.jboss.netty.logging.InternalLogger;
19 import org.jboss.netty.logging.InternalLoggerFactory;
20
21 import javax.net.ssl.KeyManagerFactory;
22 import javax.net.ssl.SSLContext;
23 import java.io.FileInputStream;
24 import java.security.KeyStore;
25 import java.security.Security;
26
27
28
29
30 public final class WebSocketSslServerSslContext {
31
32 private static final InternalLogger logger = InternalLoggerFactory.getInstance(WebSocketSslServerSslContext.class);
33 private static final String PROTOCOL = "TLS";
34
35 private final SSLContext _serverContext;
36
37
38
39
40 public static WebSocketSslServerSslContext getInstance() {
41 return SingletonHolder.INSTANCE;
42 }
43
44
45
46
47
48
49
50 private interface SingletonHolder {
51 WebSocketSslServerSslContext INSTANCE = new WebSocketSslServerSslContext();
52 }
53
54
55
56
57 private WebSocketSslServerSslContext() {
58 SSLContext serverContext = null;
59 try {
60
61 String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
62 if (algorithm == null) {
63 algorithm = "SunX509";
64 }
65
66 try {
67 String keyStoreFilePath = System.getProperty("keystore.file.path");
68 String keyStoreFilePassword = System.getProperty("keystore.file.password");
69
70 KeyStore ks = KeyStore.getInstance("JKS");
71 FileInputStream fin = new FileInputStream(keyStoreFilePath);
72 ks.load(fin, keyStoreFilePassword.toCharArray());
73
74
75
76
77 KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
78 kmf.init(ks, keyStoreFilePassword.toCharArray());
79
80
81 serverContext = SSLContext.getInstance(PROTOCOL);
82 serverContext.init(kmf.getKeyManagers(), null, null);
83 } catch (Exception e) {
84 throw new Error("Failed to initialize the server-side SSLContext", e);
85 }
86 } catch (Exception ex) {
87 if (logger.isErrorEnabled()) {
88 logger.error("Error initializing SslContextManager. " + ex.getMessage(), ex);
89 }
90 System.exit(1);
91 } finally {
92 _serverContext = serverContext;
93 }
94 }
95
96
97
98
99 public SSLContext getServerContext() {
100 return _serverContext;
101 }
102 }