在Java Websocket客户端中信任所有证书

4

首先,我知道信任所有证书可能存在潜在风险,但出于某些测试目的,我必须实现此功能。

如何强制客户端信任所有证书?我正在使用 javax.websocket 实现。

我所做的就是简单地连接到 ws,例如:

WebSocketContainer client = ContainerProvider.getWebSocketContainer();

try {
    session = client.connectToServer(ClientImpl.class, URI.create(uri));
} catch (DeploymentException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (Exception e) {
    e.printStackTrace();
}
1个回答

4

我曾经遇到过同样的问题。虽然没有找到解决方案,但我成功地使用了自签名证书。

以下是所有步骤:

  1. 从浏览器中下载您想要连接的服务器证书(在Google Chrome中,单击页面URL旁边的锁定图标)
  2. 使用以下命令创建密钥库(请记住输入的密码)

keytool -import -alias localhost -file certificate_path -keystore your_new_keystore

我建议您使用ClientManager而不是WebSocketContainer。这允许您覆盖主机名验证。

我的代码

System.getProperties().put("javax.net.debug", "all"); //usefull to understand problems

System.getProperties().put(SSLContextConfigurator.KEY_STORE_FILE, your_new_keystore_path);

System.getProperties().put(SSLContextConfigurator.TRUST_STORE_FILE, your_new_keystore_path);

System.getProperties().put(SSLContextConfigurator.KEY_STORE_PASSWORD, the_password_you_entered);

System.getProperties().put(SSLContextConfigurator.TRUST_STORE_PASSWORD, the_password_you_enterede);   

ClientManager client = ClientManager.createClient();

SslEngineConfigurator sslEngineConfigurator = new SslEngineConfigurator(new SslContextConfigurator());

sslEngineConfigurator.setHostVerificationEnabled(false); //skip host verification

client.getProperties().put(ClientProperties.SSL_ENGINE_CONFIGURATOR, sslEngineConfigurator);

client.connectToServer(you_class_with_ws_methods, your_ws_uri);

you_class_with_ws_methods可以与WebSocketContainer一起使用。
有用的资源:

https://tyrus.java.net/documentation/1.10/user-guide.html#d0e1128 https://blogs.oracle.com/PavelBucek/entry/securing_websocket_applications_on_glassfish


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接