1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.example.tcp.perf;
21
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.security.GeneralSecurityException;
25 import java.security.KeyStore;
26 import java.security.Security;
27
28 import javax.net.ssl.KeyManagerFactory;
29 import javax.net.ssl.SSLContext;
30
31
32
33
34
35
36 public class BogusSslContextFactory {
37
38
39
40
41 private static final String PROTOCOL = "TLSv1.2";
42
43 private static final String KEY_MANAGER_FACTORY_ALGORITHM;
44
45 static {
46 String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
47
48 if (algorithm == null) {
49 algorithm = KeyManagerFactory.getDefaultAlgorithm();
50 }
51
52 KEY_MANAGER_FACTORY_ALGORITHM = algorithm;
53 }
54
55
56
57
58 private static final String BOGUS_KEYSTORE = "bogus.cert";
59
60
61
62
63
64
65
66
67
68
69 private static final char[] BOGUS_PW = { 'b', 'o', 'g', 'u', 's', 'p', 'w' };
70
71 private static SSLContext serverInstance = null;
72
73 private static SSLContext clientInstance = null;
74
75
76
77
78
79
80
81
82 public static SSLContext getInstance(boolean server) throws GeneralSecurityException {
83 SSLContext retInstance;
84
85 if (server) {
86 synchronized(BogusSslContextFactory.class) {
87 if (serverInstance == null) {
88 try {
89 serverInstance = createBougusServerSslContext();
90 } catch (Exception ioe) {
91 throw new GeneralSecurityException(
92 "Can't create Server SSLContext:" + ioe);
93 }
94 }
95 }
96
97 retInstance = serverInstance;
98 } else {
99 synchronized (BogusSslContextFactory.class) {
100 if (clientInstance == null) {
101 clientInstance = createBougusClientSslContext();
102 }
103 }
104
105 retInstance = clientInstance;
106 }
107
108 return retInstance;
109 }
110
111 private static SSLContext createBougusServerSslContext() throws GeneralSecurityException, IOException {
112
113 KeyStore ks = KeyStore.getInstance("JKS");
114 InputStream in = null;
115
116 try {
117 in = BogusSslContextFactory.class.getResourceAsStream(BOGUS_KEYSTORE);
118 ks.load(in, BOGUS_PW);
119 } finally {
120 if (in != null) {
121 try {
122 in.close();
123 } catch (IOException ignored) {
124 }
125 }
126 }
127
128
129 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_MANAGER_FACTORY_ALGORITHM);
130 kmf.init(ks, BOGUS_PW);
131
132
133 SSLContext sslContext = SSLContext.getInstance(PROTOCOL);
134 sslContext.init(kmf.getKeyManagers(), BogusTrustManagerFactory.X509_MANAGERS, null);
135
136 return sslContext;
137 }
138
139 private static SSLContext createBougusClientSslContext() throws GeneralSecurityException {
140 SSLContext context = SSLContext.getInstance(PROTOCOL);
141 context.init(null, BogusTrustManagerFactory.X509_MANAGERS, null);
142
143 return context;
144 }
145 }