01: /*
02: * Lucane - a collaborative platform
03: * Copyright (C) 2004 Gilles Viguie <gilles.viguie@free.fr>
04: *
05: * This library is free software; you can redistribute it and/or
06: * modify it under the terms of the GNU Lesser General Public
07: * License as published by the Free Software Foundation; either
08: * version 2.1 of the License, or (at your option) any later version.
09: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library; if not, write to the Free Software
17: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18: */
19: package org.lucane.common.net;
20:
21: import java.io.ByteArrayInputStream;
22: import java.io.IOException;
23: import java.io.InputStream;
24:
25: import java.net.ServerSocket;
26:
27: // SSL classes
28: import java.security.KeyStore;
29: import java.security.SecureRandom;
30: import javax.net.ssl.KeyManagerFactory;
31: import javax.net.ssl.SSLServerSocketFactory;
32: import javax.net.ssl.SSLContext;
33: import javax.net.ssl.SSLServerSocket;
34:
35: import org.lucane.common.crypto.Base64;
36: import org.lucane.common.crypto.KeyTool;
37:
38: public class ServerSocketFactory {
39: public static ServerSocket getServerSocket(int port)
40: throws IOException {
41: return new ServerSocket(port);
42: }
43:
44: public static ServerSocket getServerSocket(int port,
45: String privateKey, String storePwd, String keyPwd)
46: throws Exception {
47: SSLContext sslContext = createSSLContext(privateKey, storePwd,
48: keyPwd);
49: SSLServerSocketFactory ssf = sslContext
50: .getServerSocketFactory();
51: SSLServerSocket serverSocket = (SSLServerSocket) ssf
52: .createServerSocket(port);
53: serverSocket.setNeedClientAuth(false);
54: return serverSocket;
55: }
56:
57: private static SSLContext createSSLContext(String privateKey,
58: String storePwd, String keyPwd) throws Exception {
59: byte[] key = Base64.decode(privateKey);
60: InputStream input = new ByteArrayInputStream(key);
61:
62: KeyStore serverKeyStore = KeyStore.getInstance("JKS");
63: serverKeyStore.load(input, KeyTool.sixCharsMin(storePwd)
64: .toCharArray());
65:
66: KeyManagerFactory kmf = KeyManagerFactory
67: .getInstance("SunX509");
68: kmf.init(serverKeyStore, KeyTool.sixCharsMin(keyPwd)
69: .toCharArray());
70:
71: SSLContext sslContext = SSLContext.getInstance("TLS");
72: sslContext.init(kmf.getKeyManagers(), null, new SecureRandom());
73:
74: return sslContext;
75: }
76: }
|