gpt4 book ai didi

java - 是否可以将普通套接字更改为 SSLSocket?

转载 作者:搜寻专家 更新时间:2023-10-30 21:41:48 25 4
gpt4 key购买 nike

有一个普通的套接字服务器监听端口12345

ServerSocket s = new ServerSocket(12345);

我想知道的是,有可能:

  1. 如果客户端发送http请求,服务器直接处理请求,
  2. 如果客户端发送一个https 请求,服务器将客户端套接字更改为SSLSocket?

谢谢

最佳答案

Is it possible to change plain socket to SSLSocket?

是的,是的。在服务器端,以下工作:

ServerSocketFactory ssf = ServerSocketFactory.getDefault();
ServerSocket serverSocket = ssf.createServerSocket(12345);

// I've initialised an sslContext with a keystore, as you normally would.
Socket socket = serverSocket.accept();
SSLSocketFactory sslSf = sslContext.getSocketFactory();
// The host name doesn't really matter, since we're turning it into a server socket
// (No need to match the host name to the certificate on this side).
SSLSocket sslSocket = (SSLSocket) sslSf.createSocket(socket, null,
socket.getPort(), false);
sslSocket.setUseClientMode(false);

// Use the sslSocket InputStream/OutputStream as usual.

SSLSocketFactory.createSocket(Socket, ...) 将默认将现有的 Socket 转换为客户端模式 SSLSocket。由于握手仅在您开始使用 I/O 流进行读/写时才开始,因此仍然是使用 setUseClientMode(false) 更改模式的时候了。

关于问题的其余部分:

What I want to know is that it is possible that:

  • If the client send a http request, the server handle the request directly,
  • If the client send a https request, the server change client socket to SSLSocket?

再次强调,是的,这是可能的。它有时被称为“端口统一”,它是 implemented in Grizzly因此 Glassfish .

之所以有效,是因为 HTTP 和 TLS(HTTPS 在其上工作)都是客户端应该首先对话的协议(protocol)。因此,服务器可以检测客户端最初发送的是 TLS ClientHello 消息(在这种情况下它应该尝试继续 TLS 握手)还是普通的 HTTP 请求(例如 GET/HTTP/1.1...).

我怀疑使用 SSLEngine 进行端口统一“更容易”,否则,可能很难在普通套接字上实现预读,您仍然可以通过 SSLSocketFactory.createSocket(Socket, ...)

请注意,尽管如此,这仍然很不寻常。

关于java - 是否可以将普通套接字更改为 SSLSocket?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6559859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com