Java Code Examples for javax.net.ssl.SSLContext#getServerSocketFactory()

The following examples show how to use javax.net.ssl.SSLContext#getServerSocketFactory() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private ServerSocket createTestSSLServerSocket() throws Exception
{
    char[] secret = "".toCharArray();

    java.security.KeyStore inMemoryKeyStore =
            TlsResourceHelper.createKeyStore(java.security.KeyStore.getDefaultType(),
                                             secret,
                                             new PrivateKeyEntry("1",
                                                                 _keyCertPair.getPrivateKey(),
                                                                 _keyCertPair.getCertificate()));

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(inMemoryKeyStore, secret);
    KeyManager[] keyManagers = kmf.getKeyManagers();
    SSLContext sslContext = SSLUtil.tryGetSSLContext();
    sslContext.init(keyManagers, null, new SecureRandom());
    SSLServerSocketFactory socketFactory = sslContext.getServerSocketFactory();
    ServerSocket serverSocket = socketFactory.createServerSocket(0);
    serverSocket.setSoTimeout(100);
    return serverSocket;
}
 
Example 2
private SSLServerSocketFactory getSSLServerSF() throws Exception {

        char [] password =
            System.getProperty("javax.net.ssl.keyStorePassword").toCharArray();
        String keyFilename = System.getProperty("javax.net.ssl.keyStore");

        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(keyFilename), password);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
        kmf.init(ks, password);

        KeyManager[] kms = kmf.getKeyManagers();
        TrustManager[] tms = new MyX509TM[] {new MyX509TM()};

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(kms, tms, null);

        return ctx.getServerSocketFactory();
    }
 
Example 3
JSSEServer(CipherTestUtils cipherTest, int serverPort,
        String protocol, String cipherSuite) throws Exception {
    super(cipherTest);
    this.serverPort = serverPort;
    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(new KeyManager[]{cipherTest.getServerKeyManager()},
            new TrustManager[]{cipherTest.getServerTrustManager()},
            CipherTestUtils.secureRandom);
    SSLServerSocketFactory factory =
            (SSLServerSocketFactory)serverContext.getServerSocketFactory();
    serverSocket =
            (SSLServerSocket) factory.createServerSocket(serverPort);
    serverSocket.setEnabledProtocols(protocol.split(","));
    serverSocket.setEnabledCipherSuites(cipherSuite.split(","));

    CipherTestUtils.printInfo(serverSocket);
}
 
Example 4
Source Project: hottub   File: JSSEServer.java    License: GNU General Public License v2.0 6 votes vote down vote up
JSSEServer(CipherTestUtils cipherTest, int serverPort,
        String protocol, String cipherSuite) throws Exception {
    super(cipherTest);
    this.serverPort = serverPort;
    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(new KeyManager[]{cipherTest.getServerKeyManager()},
            new TrustManager[]{cipherTest.getServerTrustManager()},
            CipherTestUtils.secureRandom);
    SSLServerSocketFactory factory =
            (SSLServerSocketFactory)serverContext.getServerSocketFactory();
    serverSocket =
            (SSLServerSocket) factory.createServerSocket(serverPort);
    serverSocket.setEnabledProtocols(protocol.split(","));
    serverSocket.setEnabledCipherSuites(cipherSuite.split(","));

    CipherTestUtils.printInfo(serverSocket);
}
 
Example 5
private static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException {
    final SSLServerSocketFactory factory;
    try {
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(loadedKeyStore);

        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);

        factory = sslContext.getServerSocketFactory();
    } catch (Exception e) {
        // simplify exception handling
        throw new IOException(e.getMessage());
    }
    return factory;
}
 
Example 6
Source Project: qpid-jms   File: TestAmqpPeerRunner.java    License: Apache License 2.0 6 votes vote down vote up
public TestAmqpPeerRunner(TestAmqpPeer peer, SSLContext sslContext, boolean needClientCert) throws IOException
{
    int port = useFixedPort ? PORT : 0;
    this.needClientCert = needClientCert;

    if (sslContext == null)
    {
        _serverSocket = new ServerSocket(port);
    }
    else
    {
        SSLServerSocketFactory socketFactory = sslContext.getServerSocketFactory();
        _serverSocket = socketFactory.createServerSocket(port);

        SSLServerSocket sslServerSocket = (SSLServerSocket) _serverSocket;
        if (this.needClientCert)
        {
            sslServerSocket.setNeedClientAuth(true);
        }
    }

    _testFrameParser = new TestFrameParser(peer);
    _peer = peer;
}
 
Example 7
Source Project: Flink-CEPplus   File: SSLUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a factory for SSL Server Sockets from the given configuration.
 * SSL Server Sockets are always part of internal communication.
 */
public static ServerSocketFactory createSSLServerSocketFactory(Configuration config) throws Exception {
	SSLContext sslContext = createInternalSSLContext(config);
	if (sslContext == null) {
		throw new IllegalConfigurationException("SSL is not enabled");
	}

	String[] protocols = getEnabledProtocols(config);
	String[] cipherSuites = getEnabledCipherSuites(config);

	SSLServerSocketFactory factory = sslContext.getServerSocketFactory();
	return new ConfiguringSSLServerSocketFactory(factory, protocols, cipherSuites);
}
 
Example 8
public JSSEServer(SSLContext context, String constraint,
        boolean needClientAuth) throws Exception {
    TLSRestrictions.setConstraint("Server", constraint);

    SSLServerSocketFactory serverFactory = context.getServerSocketFactory();
    server = (SSLServerSocket) serverFactory.createServerSocket(0);
    server.setSoTimeout(TLSRestrictions.TIMEOUT);
    server.setNeedClientAuth(needClientAuth); // for dual authentication
    System.out.println("Server: port=" + getPort());
}
 
Example 9
public JSSEServer(SSLContext context,
        boolean needClientAuth) throws Exception {
    SSLServerSocketFactory serverFactory = context.getServerSocketFactory();
    server = (SSLServerSocket) serverFactory.createServerSocket(0);
    server.setSoTimeout(TLSRestrictions.TIMEOUT);
    server.setNeedClientAuth(needClientAuth); // for dual authentication
    System.out.println("Server: port=" + getPort());
}
 
Example 10
/**
 * Creates a new SSL TCP listening log server.
 * <p>
 * This uses the {@link SSLServerSocketFactory#getDefault()} to get an SSL server socket.
 * </p>
 *
 * @param port the port to listen on
 *
 * @return the log server
 */
public static JsonLogServer createTlsServer(final int port, final Path keystorePath, final String keystorePassword) throws Exception {
    KeyManager[] keyManagers;
    final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    try (InputStream in = Files.newInputStream(keystorePath)) {
        final KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(in, keystorePassword.toCharArray());
        kmf.init(ks, keystorePassword.toCharArray());
        keyManagers = kmf.getKeyManagers();
    }

    final SSLContext context = SSLContext.getInstance("TLSv1.2");
    context.init(keyManagers, null, null);
    return new TcpServer(context.getServerSocketFactory(), port);
}
 
Example 11
Source Project: ambry   File: TestSSLUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test instantiating an implementation of {@link SSLFactory} using reflection and verify the {@link SSLEngine}
 * configuration.
 * @param factoryClassName the full class name for the {@link SSLFactory} to instantiate.
 * @throws Exception
 */
public static void testSSLFactoryImpl(String factoryClassName) throws Exception {
  //server
  File trustStoreFile = File.createTempFile("truststore", ".jks");
  SSLConfig serverSslConfig =
      new SSLConfig(TestSSLUtils.createSslProps("DC1,DC2,DC3", SSLFactory.Mode.SERVER, trustStoreFile, "server"));
  SSLFactory sslFactory = Utils.getObj(factoryClassName, serverSslConfig);
  SSLContext sslContext = sslFactory.getSSLContext();
  SSLSocketFactory socketFactory = sslContext.getSocketFactory();
  Assert.assertNotNull(socketFactory);
  SSLServerSocketFactory serverSocketFactory = sslContext.getServerSocketFactory();
  Assert.assertNotNull(serverSocketFactory);
  SSLEngine serverSideSSLEngine = sslFactory.createSSLEngine("localhost", 9095, SSLFactory.Mode.SERVER);
  TestSSLUtils.verifySSLConfig(sslContext, serverSideSSLEngine, false);

  //client
  SSLConfig clientSSLConfig =
      new SSLConfig(TestSSLUtils.createSslProps("DC1,DC2,DC3", SSLFactory.Mode.CLIENT, trustStoreFile, "client"));
  sslFactory = Utils.getObj(factoryClassName, clientSSLConfig);
  sslContext = sslFactory.getSSLContext();
  socketFactory = sslContext.getSocketFactory();
  Assert.assertNotNull(socketFactory);
  serverSocketFactory = sslContext.getServerSocketFactory();
  Assert.assertNotNull(serverSocketFactory);
  SSLEngine clientSideSSLEngine = sslFactory.createSSLEngine("localhost", 9095, SSLFactory.Mode.CLIENT);
  TestSSLUtils.verifySSLConfig(sslContext, clientSideSSLEngine, true);
}
 
Example 12
Source Project: wildfly-camel   File: ApnsUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static ApnsServerStub createServer(int gatePort, int feedPort) {
    InputStream stream = ApnsUtils.class.getResourceAsStream("/" + FixedCertificates.SERVER_STORE);
    SSLContext context = Utilities.newSSLContext(stream, FixedCertificates.SERVER_PASSWORD, "PKCS12", getAlgorithm());

    ApnsServerStub server = new ApnsServerStub(context.getServerSocketFactory(), gatePort, feedPort);
    return server;
}
 
Example 13
public JSSEServer(SSLContext context,
        boolean needClientAuth) throws Exception {
    SSLServerSocketFactory serverFactory = context.getServerSocketFactory();
    server = (SSLServerSocket) serverFactory.createServerSocket(0);
    server.setSoTimeout(TLSRestrictions.TIMEOUT);
    server.setNeedClientAuth(needClientAuth); // for dual authentication
    System.out.println("Server: port=" + getPort());
}
 
Example 14
Source Project: AndroidHttpServer   File: NanoHTTPD.java    License: MIT License 5 votes vote down vote up
/**
 * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a
 * loaded KeyManagerFactory. These objects must properly loaded/initialized
 * by the caller.
 */
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException {
    SSLServerSocketFactory res = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(loadedKeyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(loadedKeyFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        res = ctx.getServerSocketFactory();
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
    return res;
}
 
Example 15
/**
 * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and an
 * array of loaded KeyManagers. These objects must properly
 * loaded/initialized by the caller.
 */
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException {
    SSLServerSocketFactory res = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(loadedKeyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
        res = ctx.getServerSocketFactory();
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
    return res;
}
 
Example 16
public JSSEServer(SSLContext context,
        boolean needClientAuth) throws Exception {
    SSLServerSocketFactory serverFactory = context.getServerSocketFactory();
    server = (SSLServerSocket) serverFactory.createServerSocket(0);
    server.setSoTimeout(TLSRestrictions.TIMEOUT);
    server.setNeedClientAuth(needClientAuth); // for dual authentication
    System.out.println("Server: port=" + getPort());
}
 
Example 17
private SSLServerSocketFactory createAnonymousServerFactory(InetAddress hostAddr,
                                                      int port)
  throws IOException, GeneralSecurityException
{
  SSLContext sslContext = SSLContext.getInstance(_sslContext);

  String []cipherSuites = _cipherSuites;

  /*
  if (cipherSuites == null) {
    cipherSuites = sslContext.createSSLEngine().getSupportedCipherSuites();
  }
  */

  String selfSignedName = _selfSignedName;

  if (selfSignedName == null
      || "".equals(selfSignedName)
      || "*".equals(selfSignedName)) {
    if (hostAddr != null)
      selfSignedName = hostAddr.getHostName();
    else {
      InetAddress addr = InetAddress.getLocalHost();

      selfSignedName = addr.getHostAddress();
    }
  }
  
  SelfSignedCert cert = createSelfSignedCert(selfSignedName, cipherSuites);

  if (cert == null)
    throw new ConfigException(L.l("Cannot generate anonymous certificate"));
    
  sslContext.init(cert.getKeyManagers(), null, null);

  // SSLEngine engine = sslContext.createSSLEngine();

  SSLServerSocketFactory factory = sslContext.getServerSocketFactory();

  return factory;
}
 
Example 18
public static void main(String[] argv) throws NoSuchAlgorithmException, KeyManagementException, IOException, KeyStoreException, CertificateException, UnrecoverableKeyException {
    // SSL debug levels
    //System.setProperty("javax.net.debug", "ssl,handshake");
    System.setProperty("javax.net.debug", "all");

    // local truststore
    System.setProperty("javax.net.ssl.trustStore", "cacerts");
    System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    System.setProperty("javax.net.ssl.trustStoreType", "JKS");

    // access windows client certificates
    //System.setProperty("javax.net.ssl.trustStoreProvider", "SunMSCAPI");
    //System.setProperty("javax.net.ssl.trustStoreType", "Windows-ROOT");

    // load default trustmanager factory
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    System.out.println(trustManagerFactory.getProvider());

    // load server keystore
    KeyStore keystore = KeyStore.getInstance("PKCS12");
    try(FileInputStream keyStoreInputStream = new FileInputStream("davmail.p12")) {
        keystore.load(keyStoreInputStream, "password".toCharArray());
    }

    // KeyManagerFactory to create key managers
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

    // initialize KMF to work with keystore
    kmf.init(keystore, "password".toCharArray());

    // SSLContext is environment for implementing JSSE...
    // create ServerSocketFactory
    SSLContext sslContext = SSLContext.getInstance("TLS");

    // initialize sslContext to work with key managers and default trust manager
    sslContext.init(kmf.getKeyManagers(), null, null);

    // create ServerSocketFactory from sslContext
    ServerSocketFactory serverSocketFactory = sslContext.getServerSocketFactory();
    SSLServerSocket serverSocket = (SSLServerSocket) serverSocketFactory.createServerSocket(443);
    serverSocket.setNeedClientAuth(true);
    int count = 100;
    while (count-- > 0) {
        SSLSocket socket = (SSLSocket) serverSocket.accept();
        SSLSession session = socket.getSession();
        System.out.println("SubjectDN " + ((X509Certificate) session.getPeerCertificates()[0]).getSubjectDN());
    }
}
 
Example 19
Source Project: Tomcat7.0.67   File: JSSESocketFactory.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Reads the keystore and initializes the SSL socket factory.
 */
void init() throws IOException {
    try {

        String clientAuthStr = endpoint.getClientAuth();
        if("true".equalsIgnoreCase(clientAuthStr) ||
           "yes".equalsIgnoreCase(clientAuthStr)) {
            requireClientAuth = true;
        } else if("want".equalsIgnoreCase(clientAuthStr)) {
            wantClientAuth = true;
        }

        SSLContext context = createSSLContext();
        context.init(getKeyManagers(), getTrustManagers(), null);

        // Configure SSL session cache
        SSLSessionContext sessionContext =
            context.getServerSessionContext();
        if (sessionContext != null) {
            configureSessionContext(sessionContext);
        }

        // create proxy
        sslProxy = context.getServerSocketFactory();

        // Determine which cipher suites to enable
        enabledCiphers = getEnableableCiphers(context);
        enabledProtocols = getEnableableProtocols(context);

        allowUnsafeLegacyRenegotiation = "true".equals(
                endpoint.getAllowUnsafeLegacyRenegotiation());

        // Check the SSL config is OK
        checkConfig();

    } catch(Exception e) {
        if( e instanceof IOException )
            throw (IOException)e;
        throw new IOException(e.getMessage(), e);
    }
}
 
Example 20
Source Project: AndroidPirateBox   File: SslRedirectHandler.java    License: MIT License 4 votes vote down vote up
@Override
public boolean init(Server server, String prefix) {
	try {
		this.prefix = prefix;
		this.server = server;
		
		preferences = PreferenceManager.getDefaultSharedPreferences(PirateBoxService.getService());
		
		
		// Only initializes if SSL redirect is enabled in settings
		/*
		if(!preferences.getBoolean(Constants.PREF_SSL_REDIRECT, false)) {
			return false;
		}
		*/

		PORT = Integer.valueOf(PirateBoxService.getService().getPawServer().port) + 1;
		KEYSTORE = server.props.getProperty(prefix + CERT, PirateBoxService.pawHome + "conf/certs/pawKeystore");
		
		netUtil = new NetworkUtil(PirateBoxService.getService());
		apIp = netUtil.getApIp(2000);

	
		SSLContext ctx = SSLContext.getInstance("TLS");

		KeyManagerFactory kmf = KeyManagerFactory
				.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		// BKS
		KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());

		ks.load(new FileInputStream(KEYSTORE),
				PASSPHRASE.toCharArray());
		kmf.init(ks, PASSPHRASE.toCharArray());
		ctx.init(kmf.getKeyManagers(), null, null);

		SSLServerSocketFactory ssf = ctx.getServerSocketFactory();
		ssocket = ssf.createServerSocket(PORT);
		acceptThread = new AcceptThread();
		acceptThread.start();
		
		PirateBoxService.registerServiceListener(this);

		netUtil.redirectPort(NetworkUtil.IpTablesAction.IP_TABLES_ADD, apIp, NetworkUtil.PORT_HTTPS, PORT);
	} catch (Exception e) {
		e.printStackTrace();
		server.log(Server.LOG_ERROR, prefix, e.getMessage());
		return false;
	}

	return true;
}