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.net.Socket;
22:
23: import java.security.SecureRandom;
24: import java.security.KeyStore;
25: import javax.net.ssl.*;
26:
27: import org.lucane.common.ConnectInfo;
28: import org.lucane.common.crypto.Base64;
29: import org.lucane.common.crypto.KeyTool;
30:
31: import java.io.ByteArrayInputStream;
32: import java.io.InputStream;
33:
34: public class ClientSocketFactory {
35: public static Socket getSocket(ConnectInfo info) throws Exception {
36: if (info.getPublicKey().equals("nokey"))
37: return getSocket(info.getHostName(), info.getPort());
38:
39: String passwd = info.getName();
40: if (info.isService())
41: passwd = "server";
42:
43: return getSSLSocket(info.getHostName(), info.getPort(), info
44: .getPublicKey(), passwd);
45: }
46:
47: private static Socket getSocket(String hostName, int port)
48: throws Exception {
49: return new Socket(hostName, port);
50: }
51:
52: private static Socket getSSLSocket(String hostName, int port,
53: String publicKey, String password) throws Exception {
54: SSLContext sslContext = createSSLContext(publicKey, password);
55: SSLSocketFactory factory = sslContext.getSocketFactory();
56: SSLSocket socket = (SSLSocket) factory.createSocket(hostName,
57: port);
58: String[] supported = socket.getSupportedCipherSuites();
59: socket.setEnabledCipherSuites(supported);
60: socket.startHandshake();
61: return socket;
62: }
63:
64: private static SSLContext createSSLContext(String publicKey,
65: String password) throws Exception {
66: byte[] key = Base64.decode(publicKey);
67: InputStream input = new ByteArrayInputStream(key);
68:
69: KeyStore serverKeyStore = KeyStore.getInstance("JKS");
70: serverKeyStore.load(input, KeyTool.sixCharsMin(password)
71: .toCharArray());
72:
73: TrustManagerFactory tmf = TrustManagerFactory
74: .getInstance("SunX509");
75: tmf.init(serverKeyStore);
76:
77: SSLContext sslContext = SSLContext.getInstance("TLS");
78: sslContext.init(null, tmf.getTrustManagers(),
79: new SecureRandom());
80:
81: return sslContext;
82: }
83: }
|