1 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 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 { 40 public static ServerSocket getServerSocket(int port) 41 throws IOException 42 { 43 return new ServerSocket (port); 44 } 45 46 public static ServerSocket getServerSocket(int port, String privateKey, String storePwd, String keyPwd) 47 throws Exception 48 { 49 SSLContext sslContext = createSSLContext(privateKey, storePwd, keyPwd); 50 SSLServerSocketFactory ssf = sslContext.getServerSocketFactory(); 51 SSLServerSocket serverSocket = (SSLServerSocket) ssf.createServerSocket(port); 52 serverSocket.setNeedClientAuth(false); 53 return serverSocket; 54 } 55 56 private static SSLContext createSSLContext(String privateKey, String storePwd, String keyPwd) 57 throws Exception 58 { 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).toCharArray()); 64 65 KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); 66 kmf.init(serverKeyStore, KeyTool.sixCharsMin(keyPwd).toCharArray()); 67 68 SSLContext sslContext = SSLContext.getInstance("TLS"); 69 sslContext.init(kmf.getKeyManagers(), null, new SecureRandom ()); 70 71 return sslContext; 72 } 73 } | Popular Tags |