Using a stream that is derived from a non-SSL connection or socket can result in an unsecured connection that is vulnerable to interception.

Use javax.net.ssl.HttpsURLConnection and javax.net.ssl.SSLSocket instead of the corresponding unsecured versions in java.net. If necessary, downcast from an HttpURLConnection to an HttpsURLConnection to enforce the use of SSL. In addition, when you construct a java.net.URL, ensure that you use the HTTPS protocol, to avoid exceptions when trying to make HTTPS connections to the URL.

The following example shows two ways of opening an output stream. When the stream is opened using httpcon, which is an HttpURLConnection, the connection does not use SSL, and therefore is vulnerable to attack. When the stream is opened using httpscon, the connection is a secured SSL connection.

  • SEI CERT Oracle Coding Standard for Java: SER03-J. Do not serialize unencrypted, sensitive data.
  • Java API Specification: Class HttpsURLConnection.
  • Java API Specification: Class SSLSocket.
  • OWASP: Transport Layer Protection Cheat Sheet.