Wednesday, April 20, 2011

SSL socket php code needs to be converted to Java

I have a Pem file that I use with this php code to connect to a c++ SSL server, but now I need this php code written in Java

$ctx = stream_context_create();

stream_context_set_option($ctx, 'ssl', 'local_cert', 'cert.pem');

stream_context_set_option($ctx, 'ssl', 'passphrase', $pass);

$fp = stream_socket_client('ssl://serverURL', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);

if (!$fp) {

    print "Failed to connect $err $errstr\n";
    return;
}

Any ideas how to read in the cert.pem file in Java and then establish the SSL socket?

Thank you!

From stackoverflow
  • You will need Bouncy Castle in your classpath.

    PEMReader pr = new PEMReader(new FileReader("cert.pem"));
    X509Certificate cert = (X509Certificate) pr.readObject();
    PEMReader kr = new PEMReader(new FileReader("privkey.pem"),
            new PasswordFinder() {
        public char[] getPassword() {
            return "passphase".toCharArray();
        }
    });
    KeyPair key = (KeyPair) kr.readObject();
    KeyStore ksKeys = KeyStore.getInstance("JKS");
    ksKeys.load(null, "passphase".toCharArray());
    ksKeys.setCertificateEntry("MyCert", cert);
    ksKeys.setKeyEntry("Mykey", key.getPrivate(),
            "passphase".toCharArray(), new Certificate[]{cert});
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(
            KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ksKeys, "passphase".toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(
            TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ksKeys);
    
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    
    Socket socket = sslContext.getSocketFactory().createSocket(
            "localhost", 4433);
    BufferedReader in = new BufferedReader(new InputStreamReader(
            socket.getInputStream()));
    PrintWriter out = new PrintWriter(new OutputStreamWriter(
            socket.getOutputStream()));
    out.println("Hello World");
    System.out.println(in.readLine());
    out.close();
    in.close();
    

    If you run openssl s_server -Verify cert.pem -cert cert.pem -key privkey.pem, it should show:

    depth=0 /C=AU/ST=Some-State/O=Internet Widgits Pty Ltd
    verify error:num=18:self signed certificate
    verify return:1
    depth=0 /C=AU/ST=Some-State/O=Internet Widgits Pty Ltd
    verify return:1
    Hello World
    DONE
    shutting down SSL
    CONNECTION CLOSED
    ACCEPT
    

0 comments:

Post a Comment