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

The following examples show how to use javax.net.ssl.SSLContext#getServerSocketFactory() . 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
Source File: SiteSpecificTrustStoreTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
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
Source File: EmptyCertificateAuthorities.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: JSSEServer.java    From dragonwell8_jdk with 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 4
Source File: TestAmqpPeerRunner.java    From qpid-jms with 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 5
Source File: JSSEServer.java    From hottub with 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 6
Source File: SSLServerSocketHelper.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
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 7
Source File: ApnsUtils.java    From wildfly-camel with 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 8
Source File: JSSEServer.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
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 9
Source File: NanoHTTPD.java    From VBrowser-Android with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 10
Source File: NanoHTTPD.java    From AndroidHttpServer with 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 11
Source File: JSSEServer.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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 12
Source File: SSLUtils.java    From Flink-CEPplus with 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 13
Source File: TestSSLUtils.java    From ambry with 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 14
Source File: JsonLogServer.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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 15
Source File: JSSEServer.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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 16
Source File: JSSEServer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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 17
Source File: ServerSocketRunner.java    From davmail with GNU General Public License v2.0 4 votes vote down vote up
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 18
Source File: SSLFactoryJsse.java    From baratine with GNU General Public License v2.0 4 votes vote down vote up
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 19
Source File: JSSESocketFactory.java    From Tomcat7.0.67 with 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 File: SslRedirectHandler.java    From AndroidPirateBox with 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;
}