Socket and provides secure
sockets using protocols such as the "Secure
Sockets Layer" (SSL) or IETF "Transport Layer Security" (TLS) protocols.
Such sockets are normal stream sockets, but they add a layer of security protections over the underlying network transport protocol, such as TCP. Those protections include:
These kinds of protection are specified by a "cipher suite", which is a combination of cryptographic algorithms used by a given SSL connection. During the negotiation process, the two endpoints must agree on a ciphersuite that is available in both environments. If there is no such suite in common, no SSL connection can be established, and no data can be exchanged.
The cipher suite used is established by a negotiation process called "handshaking". The goal of this process is to create or rejoin a "session", which may protect many connections over time. After handshaking has completed, you can access session attributes by using the getSession method. The initial handshake on this connection can be initiated in one of three ways:
startHandshake which explicitly
begins handshakes, or
getSession tries to set up a session
if there is no currently valid session, and
an implicit handshake is done.
If handshaking fails for any reason, the SSLSocket
is closed, and no further communications can be done.
There are two groups of cipher suites which you will need to know about when managing cipher suites:
Implementation defaults require that only cipher suites which authenticate servers and provide confidentiality be enabled by default. Only if both sides explicitly agree to unauthenticated and/or non-private (unencrypted) communications will such a ciphersuite be selected.
When an SSLSocket is first created, no handshaking
is done so that applications may first set their communication
preferences: what cipher suites to use, whether the socket should be
in client or server mode, etc.
However, security is always provided by the time that application data
is sent over the connection.
You may register to receive event notification of handshake
completion. This involves
the use of two additional classes. HandshakeCompletedEvent
objects are passed to HandshakeCompletedListener instances,
which are registered by users of this API.
An SSLSocket is created by SSLSocketFactory,
or by accepting a connection from a
SSLServerSocket.
A SSL socket must choose to operate in the client or server mode. This will determine who begins the handshaking process, as well as which messages should be sent by each party. Each connection must have one client and one server, or handshaking will not progress properly. Once the initial handshaking has started, a socket can not switch between client and server modes, even when performing renegotiations.
The ApplicationProtocol String values returned by the methods
in this class are in the network byte representation sent by the peer.
The bytes could be directly compared, or converted to its Unicode
String format for comparison.
String networkString = sslSocket.getHandshakeApplicationProtocol();
byte[] bytes = networkString.getBytes(StandardCharsets.ISO_8859_1);
//
// Match using bytes:
//
// "http/1.1" (7-bit ASCII values same in UTF-8)
// MEETEI MAYEK LETTERS "HUK UN I" (Unicode 0xabcd->0xabcf)
//
String HTTP1_1 = "http/1.1";
byte[] HTTP1_1_BYTES = HTTP1_1.getBytes(StandardCharsets.UTF_8);
byte[] HUK_UN_I_BYTES = new byte[] {
(byte) 0xab, (byte) 0xcd,
(byte) 0xab, (byte) 0xce,
(byte) 0xab, (byte) 0xcf};
if ((Arrays.compare(bytes, HTTP1_1_BYTES) == 0 )
|| Arrays.compare(bytes, HUK_UN_I_BYTES) == 0) {
...
}
//
// Alternatively match using string.equals() if we know the ALPN value
// was encoded from a String using a certain character set,
// for example UTF-8. The ALPN value must first be properly
// decoded to a Unicode String before use.
//
String unicodeString = new String(bytes, StandardCharsets.UTF_8);
if (unicodeString.equals(HTTP1_1)
|| unicodeString.equals("\uabcd\uabce\uabcf")) {
...
}
API Note
When the connection is no longer needed, the client and server
applications should each close both sides of their respective connection.
This can be done either in one shot by calling Socket#close(),
or by closing each side individually using
Socket#shutdownOutput() / Socket#shutdownInput() which is
useful for protocol versions that can support half-closed connections.
Note that in some cases, closing the input stream may depend on the
peer's output stream being closed first. If the connection is not closed
in an orderly manner (for example Socket#shutdownInput() is called
before the peer's write closure notification has been received), exceptions
may be raised to indicate that an error has occurred.
Once an SSLSocket is closed, it is not reusable: a new
SSLSocket must be created.
java.net.Socket , SSLServerSocket, SSLSocketFactory
| Access | Constructor and Description |
|---|---|
| protected | |
| protected | |
| protected | |
| protected | SSLSocket(String
name of the host with which to connect, or
host, int null for the loopback address.number of the server's port port, InetAddress the client's address the socket is bound to, or
clientAddress, int null for the anyLocal address.the client's port the socket is bound to, or
clientPort)zero for a system selected free port.Used only by subclasses. |
| protected | SSLSocket(InetAddress
the server's host address, int its port port, InetAddress the client's address the socket is bound to, or
clientAddress, int null for the anyLocal address.the client's port the socket is bound to, or
clientPort)zero for a system selected free port.Used only by subclasses. |
| Modifier and Type | Method and Description |
|---|---|
| public abstract void | addHandshakeCompletedListener(HandshakeCompletedListener
the HandShake Completed event listener listener)Registers an event listener to receive notifications that an SSL handshake has completed on this connection. |
| public String | Returns: null if it has not yet been determined if application protocols might be used for this connection, an emptyString if application protocols values will not
be used, or a non-empty application protocol String
if a value was successfully negotiated.Returns the most recent application protocol value negotiated for this connection. |
| public abstract String[] | Returns: an array of cipher suite namesReturns the names of the SSL cipher suites which are currently enabled for use on this connection. |
| public abstract String[] | Returns: an array of protocolsReturns the names of the protocol versions which are currently enabled for use on this connection. |
| public abstract boolean | Returns: true indicates that sessions may be created; this is the default. false indicates that an existing session must be resumedReturns true if new SSL sessions may be established by this socket. |
| public String | Returns: null if it has not yet been determined if application protocols might be used for this handshake, an emptyString if application protocols values will not
be used, or a non-empty application protocol String
if a value was successfully negotiated.Returns the application protocol value negotiated on a SSL/TLS handshake currently in progress. |
| public BiFunction | Returns: the callback function, or null if none has been set.Retrieves the callback function that selects an application protocol value during a SSL/TLS/DTLS handshake. |
| public SSLSession | Returns: null if this instance is not currently handshaking, or if the current handshake has not progressed far enough to create a basic SSLSession. Otherwise, this method returns theSSLSession currently being negotiated.Returns the |
| public abstract boolean | Returns: true if client authentication is required, or false if no client authentication is desired.Returns true if the socket will require client authentication. |
| public abstract SSLSession | |
| public SSLParameters | Returns: the SSLParameters in effect for this SSLSocket.Returns the SSLParameters in effect for this SSLSocket. |
| public abstract String[] | Returns: an array of cipher suite namesReturns the names of the cipher suites which could be enabled for use on this connection. |
| public abstract String[] | Returns: an array of protocols supportedReturns the names of the protocols which could be enabled for use on an SSL connection. |
| public abstract boolean | Returns: true if the socket should do handshaking in "client" modeReturns true if the socket is set to use client mode when handshaking. |
| public abstract boolean | Returns: true if client authentication is requested, or false if no client authentication is desired.Returns true if the socket will request client authentication. |
| public abstract void | removeHandshakeCompletedListener(HandshakeCompletedListener
the HandShake Completed event listener listener)Removes a previously registered handshake completion listener. |
| public abstract void | setEnabledCipherSuites(String[]
Names of all the cipher suites to enable suites)Sets the cipher suites enabled for use on this connection. |
| public abstract void | setEnabledProtocols(String[]
Names of all the protocols to enable. protocols)Sets the protocol versions enabled for use on this connection. |
| public abstract void | setEnableSessionCreation(boolean
true indicates that sessions may be created; this
is the default. false indicates that an existing session
must be resumed flag)Controls whether new SSL sessions may be established by this socket. |
| public void | setHandshakeApplicationProtocolSelector(BiFunction<SSLSocket, List<String>, String>
the callback function, or null to de-register. selector)Registers a callback function that selects an application protocol value for a SSL/TLS/DTLS handshake. |
| public abstract void | setNeedClientAuth(boolean
set to true if client authentication is required,
or false if no client authentication is desired. need)Configures the socket to require client authentication. |
| public void | |
| public abstract void | setUseClientMode(boolean
true if the socket should start its handshaking
in "client" mode mode)Configures the socket to use client (or server) mode when handshaking. |
| public abstract void | setWantClientAuth(boolean
set to true if client authentication is requested,
or false if no client authentication is desired. want)Configures the socket to request client authentication. |
| public abstract void |
| SSLSocket | back to summary |
|---|---|
| protected SSLSocket() Used only by subclasses. Constructs an uninitialized, unconnected TCP socket. | |
| SSLSocket | back to summary |
|---|---|
| protected SSLSocket(String host, int port) throws IOException, UnknownHostException Used only by subclasses. Constructs a TCP connection to a named host at a specified port. This acts as the SSL client.
| |
| SSLSocket | back to summary |
|---|---|
| protected SSLSocket(InetAddress address, int port) throws IOException Used only by subclasses. Constructs a TCP connection to a server at a specified address and port. This acts as the SSL client.
| |
| SSLSocket | back to summary |
|---|---|
| protected SSLSocket(String host, int port, InetAddress clientAddress, int clientPort) throws IOException, UnknownHostException Used only by subclasses. Constructs an SSL connection to a named host at a specified port, binding the client side of the connection a given address and port. This acts as the SSL client.
| |
| SSLSocket | back to summary |
|---|---|
| protected SSLSocket(InetAddress address, int port, InetAddress clientAddress, int clientPort) throws IOException Used only by subclasses. Constructs an SSL connection to a server at a specified address and TCP port, binding the client side of the connection a given address and port. This acts as the SSL client.
| |
| addHandshakeCompletedListener | back to summary |
|---|---|
| public abstract void addHandshakeCompletedListener(HandshakeCompletedListener listener) Registers an event listener to receive notifications that an SSL handshake has completed on this connection.
| |
| getApplicationProtocol | back to summary |
|---|---|
| public String getApplicationProtocol() Returns the most recent application protocol value negotiated for this connection. If supported by the underlying SSL/TLS/DTLS implementation, application name negotiation mechanisms such as RFC 7301 , the Application-Layer Protocol Negotiation (ALPN), can negotiate application-level values between peers. Implementation Specification The implementation in this class throws
| |
| getEnabledCipherSuites | back to summary |
|---|---|
| public abstract String[] getEnabledCipherSuites() Returns the names of the SSL cipher suites which are currently enabled for use on this connection. When an SSLSocket is first created, all enabled cipher suites support a minimum quality of service. Thus, in some environments this value might be empty. Note that even if a suite is enabled, it may never be used. This can occur if the peer does not support it, or its use is restricted, or the requisite certificates (and private keys) for the suite are not available, or an anonymous suite is enabled but authentication is required. The returned array includes cipher suites from the list of standard cipher suite names in the JSSE Cipher Suite Names section of the Java Security Standard Algorithm Names Specification, and may also include other cipher suites that the provider supports.
| |
| getEnabledProtocols | back to summary |
|---|---|
| public abstract String[] getEnabledProtocols() Returns the names of the protocol versions which are currently enabled for use on this connection. Note that even if a protocol is enabled, it may never be used. This can occur if the peer does not support the protocol, or its use is restricted, or there are no enabled cipher suites supported by the protocol.
| |
| getEnableSessionCreation | back to summary |
|---|---|
| public abstract boolean getEnableSessionCreation() Returns true if new SSL sessions may be established by this socket.
| |
| getHandshakeApplicationProtocol | back to summary |
|---|---|
| public String getHandshakeApplicationProtocol() Returns the application protocol value negotiated on a SSL/TLS handshake currently in progress.
Like Implementation Specification The implementation in this class throws
| |
| getHandshakeApplicationProtocolSelector | back to summary |
|---|---|
| public BiFunction Retrieves the callback function that selects an application protocol
value during a SSL/TLS/DTLS handshake.
See Implementation Specification The implementation in this class throws
| |
| getHandshakeSession | back to summary |
|---|---|
| public SSLSession getHandshakeSession() Returns the
TLS protocols may negotiate parameters that are needed when using
an instance of this class, but before the
This method provides early access to the
Unlike
| |
| getNeedClientAuth | back to summary |
|---|---|
| public abstract boolean getNeedClientAuth() Returns true if the socket will require client authentication. This option is only useful to sockets in the server mode.
| |
| getSession | back to summary |
|---|---|
| public abstract SSLSession getSession() Returns the SSL Session in use by this connection. These can be long-lived, and frequently correspond to an entire login session for some user. The session specifies a particular cipher suite which is being actively used by all connections in that session, as well as the identities of the session's client and server. This method will initiate the initial handshake if necessary and then block until the handshake has been established. If an error occurs during the initial handshake, this method returns an invalid session object which reports an invalid cipher suite of "SSL_NULL_WITH_NULL_NULL".
| |
| getSSLParameters | back to summary |
|---|---|
| public SSLParameters getSSLParameters() Returns the SSLParameters in effect for this SSLSocket. The ciphersuites and protocols of the returned SSLParameters are always non-null.
| |
| getSupportedCipherSuites | back to summary |
|---|---|
| public abstract String[] getSupportedCipherSuites() Returns the names of the cipher suites which could be enabled for use on this connection. Normally, only a subset of these will actually be enabled by default, since this list may include cipher suites which do not meet quality of service requirements for those defaults. Such cipher suites might be useful in specialized applications. The returned array includes cipher suites from the list of standard cipher suite names in the JSSE Cipher Suite Names section of the Java Security Standard Algorithm Names Specification, and may also include other cipher suites that the provider supports.
| |
| getSupportedProtocols | back to summary |
|---|---|
| public abstract String[] getSupportedProtocols() Returns the names of the protocols which could be enabled for use on an SSL connection.
| |
| getUseClientMode | back to summary |
|---|---|
| public abstract boolean getUseClientMode() Returns true if the socket is set to use client mode when handshaking.
| |
| getWantClientAuth | back to summary |
|---|---|
| public abstract boolean getWantClientAuth() Returns true if the socket will request client authentication. This option is only useful for sockets in the server mode.
| |
| removeHandshakeCompletedListener | back to summary |
|---|---|
| public abstract void removeHandshakeCompletedListener(HandshakeCompletedListener listener) Removes a previously registered handshake completion listener.
| |
| setEnabledCipherSuites | back to summary |
|---|---|
| public abstract void setEnabledCipherSuites(String[] suites) Sets the cipher suites enabled for use on this connection.
Each cipher suite in the Note that the standard list of cipher suite names may be found in the JSSE Cipher Suite Names section of the Java Security Standard Algorithm Names Specification. Providers may support cipher suite names not found in this list or might not use the recommended name for a certain cipher suite.
See
| |
| setEnabledProtocols | back to summary |
|---|---|
| public abstract void setEnabledProtocols(String[] protocols) Sets the protocol versions enabled for use on this connection.
The protocols must have been listed by
| |
| setEnableSessionCreation | back to summary |
|---|---|
| public abstract void setEnableSessionCreation(boolean flag) Controls whether new SSL sessions may be established by this socket. If session creations are not allowed, and there are no existing sessions to resume, there will be no successful handshaking.
| |
| setHandshakeApplicationProtocolSelector | back to summary |
|---|---|
| public void setHandshakeApplicationProtocolSelector(BiFunction<SSLSocket, List<String>, String> selector) Registers a callback function that selects an application protocol
value for a SSL/TLS/DTLS handshake.
The function overrides any values supplied using
For example, the following call registers a callback function that examines the TLS handshake parameters and selects an application protocol name:
API Note This method should be called by TLS server applications before the TLS
handshake begins. Also, this Implementation Specification The implementation in this class throws
| |
| setNeedClientAuth | back to summary |
|---|---|
| public abstract void setNeedClientAuth(boolean need) Configures the socket to require client authentication. This option is only useful for sockets in the server mode. A socket's client authentication setting is one of the following:
Unlike
Calling this method overrides any previous setting made by
this method or
| |
| setSSLParameters | back to summary |
|---|---|
| public void setSSLParameters(SSLParameters params) Applies SSLParameters to this socket. This means:
| |
| setUseClientMode | back to summary |
|---|---|
| public abstract void setUseClientMode(boolean mode) Configures the socket to use client (or server) mode when handshaking. This method must be called before any handshaking occurs. Once handshaking has begun, the mode can not be reset for the life of this socket. Servers normally authenticate themselves, and clients are not required to do so.
| |
| setWantClientAuth | back to summary |
|---|---|
| public abstract void setWantClientAuth(boolean want) Configures the socket to request client authentication. This option is only useful for sockets in the server mode. A socket's client authentication setting is one of the following:
Unlike
Calling this method overrides any previous setting made by
this method or
| |
| startHandshake | back to summary |
|---|---|
| public abstract void startHandshake() throws IOException Starts handshaking on this Common reasons include a need to initiate a new protected session, create new encryption keys, or to change cipher suites. To force complete reauthentication, the current session should be invalidated before starting this handshake. The behavior of this method is protocol (and possibly implementation) dependent. For example, in TLSv1.3 calling this method after the connection has been established will force a key update. For prior TLS versions it will force a renegotiation (re-handshake). If data has already been sent on the connection, it continues to flow during this handshake. When the handshake completes, this will be signaled with an event.
This method is synchronous for the initial handshake on a connection
and returns when the negotiated handshake is complete. Some
protocols may not support multiple handshakes on an existing socket
and may throw an
| |