1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.example.securechat;
17
18 import java.security.KeyStore;
19 import java.security.SecureRandom;
20 import java.security.Security;
21
22 import javax.net.ssl.KeyManager;
23 import javax.net.ssl.KeyManagerFactory;
24 import javax.net.ssl.SSLContext;
25 import javax.net.ssl.SSLEngine;
26 import javax.net.ssl.TrustManager;
27
28 import org.jboss.netty.handler.ssl.SslHandler;
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 public final class SecureChatSslContextFactory {
54
55 private static final String PROTOCOL = "TLS";
56 private static final SSLContext SERVER_CONTEXT;
57 private static final SSLContext CLIENT_CONTEXT;
58
59 static {
60 String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
61 if (algorithm == null) {
62 algorithm = "SunX509";
63 }
64
65 SSLContext serverContext = null;
66 SSLContext clientContext = null;
67 try {
68 KeyStore ks = KeyStore.getInstance("JKS");
69 ks.load(SecureChatKeyStore.asInputStream(),
70 SecureChatKeyStore.getKeyStorePassword());
71
72
73 KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
74 kmf.init(ks, SecureChatKeyStore.getCertificatePassword());
75
76
77 serverContext = SSLContext.getInstance(PROTOCOL);
78 serverContext.init(kmf.getKeyManagers(), null, null);
79 } catch (Exception e) {
80 throw new Error(
81 "Failed to initialize the server-side SSLContext", e);
82 }
83
84 try {
85 clientContext = SSLContext.getInstance(PROTOCOL);
86 clientContext.init(null, SecureChatTrustManagerFactory.getTrustManagers(), null);
87 } catch (Exception e) {
88 throw new Error(
89 "Failed to initialize the client-side SSLContext", e);
90 }
91
92 SERVER_CONTEXT = serverContext;
93 CLIENT_CONTEXT = clientContext;
94 }
95
96 public static SSLContext getServerContext() {
97 return SERVER_CONTEXT;
98 }
99
100 public static SSLContext getClientContext() {
101 return CLIENT_CONTEXT;
102 }
103
104 private SecureChatSslContextFactory() {
105
106 }
107 }