当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《SSL套接字php代码需要转换为Java》经验,为你挑选了1个好方法。

我有一个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> H Marcelo Mo..:

您将需要在类路径中使用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

推荐阅读
手机用户2502851955
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有