SSL套接字php代码需要转换为Java

时间:2009-04-06 19:56:34

标签: java php ssl sockets

我有一个Pem文件,我使用这个PHP代码连接到c ++ SSL服务器,但现在我需要这个用Java编写的PHP代码

$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;
}

有关如何在Java中读取cert.pem文件然后建立SSL套接字的任何想法吗?

谢谢!

1 个答案:

答案 0 :(得分:6)

您的类路径中需要Bouncy Castle

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();

如果您运行openssl s_server -Verify cert.pem -cert cert.pem -key privkey.pem,则应显示:

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