CoolFace
Apppublic

Deeps-2005/java-ssl-scanner

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
NoAnonymousTrustManager.java42 linesDownload Raw Back to sample
1import javax.net.ssl.*;
2import java.security.SecureRandom;
3import java.io.IOException;
4
5public class NoAnonymousTrustManager {
6    public static void main(String[] args) throws Exception {
7        System.out.println("--- Testing SSLContext Initialization without Anonymous TrustManager ---");
8
9        // Initialize SecureRandom using getInstanceStrong() for cryptographically strong random numbers
10        SecureRandom secureRandom = SecureRandom.getInstanceStrong();
11        System.out.println("SecureRandom initialized with getInstanceStrong().");
12
13        // Initialize SSLContext using null for KeyManager and TrustManager arrays.
14        // Passing null means that the default KeyManager and TrustManager will be used.
15        // The default TrustManager typically trusts certificates in the JVM's 'cacerts' truststore.
16        SSLContext sslContext = SSLContext.getInstance("TLSv1.3"); // Or TLSv1.2 for broader compatibility
17        sslContext.init(null, null, secureRandom); // KeyManagers: null, TrustManagers: null, SecureRandom: secureRandom
18        System.out.println("SSLContext initialized using default TrustManager (passing null).");
19
20        // Simulate a secure connection attempt
21        try {
22            SSLSocketFactory factory = sslContext.getSocketFactory();
23            // This will use the default TrustManager from the SSLContext
24            SSLSocket socket = (SSLSocket) factory.createSocket("www.google.com", 443);
25            socket.setEnabledProtocols(new String[]{"TLSv1.2", "TLSv1.3"});
26            socket.setEnabledCipherSuites(new String[]{
27                "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
28                "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"
29            });
30            socket.startHandshake(); // Initiate the handshake to trigger validation
31            System.out.println("Successfully performed secure handshake with www.google.com using default TrustManager.");
32            socket.close();
33        } catch (SSLHandshakeException e) {
34            System.err.println("SSL Handshake failed (might be expected if certificate validation fails for your environment/proxies): " + e.getMessage());
35        } catch (IOException e) {
36            System.err.println("IOException during connection: " + e.getMessage());
37        }
38
39        System.out.println("Test case complete: No anonymous TrustManager detected by analyzer.");
40    }
41}
42