1 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 { 36 public static Socket getSocket(ConnectInfo info) 37 throws Exception 38 { 39 if(info.getPublicKey().equals("nokey")) 40 return getSocket(info.getHostName(), info.getPort()); 41 42 String passwd = info.getName(); 43 if(info.isService()) 44 passwd = "server"; 45 46 return getSSLSocket(info.getHostName(), info.getPort(), info.getPublicKey(), passwd); 47 } 48 49 private static Socket getSocket(String hostName, int port) 50 throws Exception 51 { 52 return new Socket (hostName, port); 53 } 54 55 private static Socket getSSLSocket(String hostName, int port, String publicKey, String password) 56 throws Exception 57 { 58 SSLContext sslContext = createSSLContext(publicKey, password); 59 SSLSocketFactory factory = sslContext.getSocketFactory(); 60 SSLSocket socket = (SSLSocket) factory.createSocket(hostName, port); 61 String [] supported = socket.getSupportedCipherSuites(); 62 socket.setEnabledCipherSuites(supported); 63 socket.startHandshake(); 64 return socket; 65 } 66 67 private static SSLContext createSSLContext(String publicKey, String password) 68 throws Exception 69 { 70 byte[] key = Base64.decode(publicKey); 71 InputStream input = new ByteArrayInputStream (key); 72 73 KeyStore serverKeyStore = KeyStore.getInstance("JKS"); 74 serverKeyStore.load(input, KeyTool.sixCharsMin(password).toCharArray()); 75 76 TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); 77 tmf.init(serverKeyStore); 78 79 SSLContext sslContext = SSLContext.getInstance("TLS"); 80 sslContext.init(null,tmf.getTrustManagers(), new SecureRandom ()); 81 82 return sslContext; 83 } 84 } | Popular Tags |