'Possible to create Secure Websocket in Java for localhost only?

Is it possible to create a Java SSL Websocket, so peers can connect using wss://127.0.0.1?

My current implementation is using org.java_websocket.server.DefaultSSLWebSocketServerFactory:

        WebSocketServerFactory socketFactory = new DefaultWebSocketServerFactory();
        // Make it secure
        char[] passphrase = tempPassword.toCharArray();
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (FileInputStream fis = new FileInputStream(keystoreFile)) {
            keystore.load(fis, passphrase);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keystore, passphrase);
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keystore);
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            socketFactory = new DefaultSSLWebSocketServerFactory(ctx);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw e;
        }

But when I try to use this, I get the following error from OkHttp3: Transport exception caused by javax.net.ssl.SSLHandshakeException: connection closed. This is the full stack-trace: https://pastebin.com/raw/Y3RvqRrt



Solution 1:[1]

Yes, insecurely you can use https://square.github.io/okhttp/4.x/okhttp-tls/okhttp3.tls/-handshake-certificates/-builder/add-insecure-host/

See the answer here Websocket Secure error: Hostname not verified

But assuming you want it securely, you will need to define the trusted certificates in the client.

https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/CustomTrust.java

    HandshakeCertificates certificates = new HandshakeCertificates.Builder()
        .addTrustedCertificate(letsEncryptCertificateAuthority)
        .addTrustedCertificate(entrustRootCertificateAuthority)
        .addTrustedCertificate(comodoRsaCertificationAuthority)
        // Uncomment if standard certificates are also required.
        //.addPlatformTrustedCertificates()
        .build();

    client = new OkHttpClient.Builder()
            .sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager())
            .build();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yuri Schimke