00:00

HTTP vs HTTPS: Differences, TLS Handshake and How HTTPS Works

Last updated: 14 min read

HTTP (HyperText Transfer Protocol) is the language browsers and servers use to exchange web pages and API data. HTTPS is the same protocol wrapped inside an encrypted, verified connection created by TLS (Transport Layer Security). The difference decides whether anyone on the network can read or change what you send, including passwords, card numbers and session cookies.

This tutorial explains how HTTP works, why it is unsafe on its own, what HTTPS adds, how the TLS handshake and certificates work, and how to enable HTTPS in a Spring Boot application. It ends with a side-by-side comparison, common mistakes and best practices.

1. What Is HTTP?

HTTP is a request-response protocol. A client, usually a browser or a mobile app, sends a request. The server sends back a response. Each request names a method (what to do) and a path (what to do it to), and both sides add headers with extra information.

Here is a real HTTP exchange, exactly as it travels over the network:

HTTP request
POST /login HTTP/1.1
Host: shop.example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 38

username=priya&password=MySecret123
HTTP response
HTTP/1.1 302 Found
Location: /account
Set-Cookie: SESSION=4f9a1c77e2b04d0c; Path=/; HttpOnly

Notice that everything is readable text: the username, the password and the session cookie. HTTP itself has no encryption. It was designed in the early 1990s for sharing public documents, when security was not a priority.

  • Default port: 80.
  • Stateless: each request stands on its own. Cookies and tokens are used to remember who the user is.
  • Versions: HTTP/1.1, HTTP/2 (binary framing and multiplexing) and HTTP/3 (runs over the QUIC transport instead of TCP).

2. Why Plain HTTP Is Not Safe

Between your browser and a server, data passes through many machines: your Wi-Fi router, your internet provider, several network carriers, and maybe a hotel or café network. With plain HTTP, any of them can see and modify the traffic. This creates three dangers:

  • Eavesdropping: someone on the same public Wi-Fi can capture logins and cookies with free tools.
  • Tampering: a network in the middle can inject advertisements or malicious scripts into the page, or change a bank account number in a form.
  • Impersonation: an attacker can redirect you to a fake server, and HTTP gives you no way to prove you reached the real one.
An attacker reading HTTP traffic but not HTTPS traffic Top row: a browser sends the text password=MySecret123 to a server over HTTP, and an attacker on the same Wi-Fi can read and change it. Bottom row: the same request is sent over HTTPS, the attacker only sees scrambled bytes. HTTP · PLAIN TEXT Browser Server password=MySecret123 Attacker on Wi-Fi can read and change it HTTPS · ENCRYPTED WITH TLS Browser Server 7f#Qz!9@kP2vR$e8wLm0 Attacker on Wi-Fi sees only scrambled bytes
Figure 1: With HTTP, anyone on the path can read and change the data. With HTTPS, they only see encrypted bytes.

Because of these risks, modern browsers label HTTP pages as "Not secure", block some features such as camera access and geolocation on them, and search engines prefer HTTPS pages.

3. What Is HTTPS?

HTTPS stands for HTTP Secure. It is not a different language: the requests, methods, headers and status codes are exactly the same. The difference is how they travel. Before any HTTP data is sent, the browser and server set up a secure TLS connection, and all HTTP messages then travel inside it.

A simple way to picture it: HTTP is a postcard that anyone handling it can read. HTTPS is the same letter placed in a locked box. Only the receiver has the key, and the box shows any sign of tampering.

  • Default port: 443.
  • URL scheme: https://
  • Security layer: TLS, usually version 1.2 or 1.3. The older name "SSL" is still used informally, but all SSL versions are outdated and insecure.

4. What HTTPS Protects

TLS gives HTTPS three guarantees. It helps to remember them, because each one defends against one of the dangers above:

GuaranteeWhat it meansStops
Confidentiality (encryption)Data is scrambled so only the browser and the server can read it.Eavesdropping
IntegrityEvery message carries a cryptographic check. Any change made in transit is detected and the connection is dropped.Tampering and injected content
AuthenticationThe server proves its identity with a certificate signed by a trusted authority.Fake servers and impersonation

What HTTPS does not hide: the IP addresses of both sides, roughly how much data is sent, and usually the domain name you are visiting. It also does not make a website trustworthy. A phishing site can have a perfectly valid certificate for its own fake domain.

5. How TLS Encryption Works

TLS combines two kinds of cryptography, each used for what it does best:

  • Asymmetric (public-key) cryptography uses a key pair: a public key everyone can see and a private key only the owner holds. It is slow, but it solves a hard problem: two parties who have never met can agree on a secret over a public network, and the server can prove it owns its certificate.
  • Symmetric cryptography uses one shared secret key for both encryption and decryption. Algorithms such as AES-GCM and ChaCha20-Poly1305 are extremely fast and are used to encrypt all the actual page data.

So TLS uses the slow method briefly during the handshake to agree on a fresh shared key, then switches to the fast method for the rest of the connection. Modern TLS uses ephemeral key exchange (ECDHE), which creates new keys for every connection. This gives forward secrecy: even if the server's private key is stolen years later, old recorded traffic still cannot be decrypted.

6. The TLS Handshake Step by Step

The handshake is the short conversation at the start of each HTTPS connection. With TLS 1.3 it needs only one round trip between browser and server:

The TLS 1.3 handshake A sequence diagram between a client and a server. The client sends ClientHello with its key share. The server replies with ServerHello, its key share, its certificate and a Finished message. The client checks the certificate and sends Finished. Then both sides exchange encrypted HTTP requests and responses. Client Server 1. ClientHello TLS versions, cipher suites, key share, server name 2. ServerHello + Certificate + Finished server key share, certificate chain, signature proving key ownership 3. Verify certificate, derive keys 4. Finished 5. Encrypted HTTP requests and responses
Figure 2: The TLS 1.3 handshake takes one round trip. After it, every HTTP request and response is encrypted with keys only the two sides know.
  1. ClientHello: the browser lists the TLS versions and cipher suites it supports, sends its half of the key exchange, and names the website it wants (the Server Name Indication, or SNI, so one server can host many sites).
  2. ServerHello and certificate: the server picks the settings, sends its half of the key exchange, its certificate, and a signature made with its private key that proves it really owns that certificate.
  3. Verification and key derivation: the browser checks that the certificate is valid, unexpired, issued for this domain and signed by a trusted authority. Both sides now independently calculate the same session keys from the two key shares.
  4. Finished: each side sends a short encrypted message that confirms the whole handshake was not tampered with.
  5. Application data: from now on, HTTP requests and responses travel encrypted with the session keys.

TLS 1.2 needed two round trips. TLS 1.3 needs one, and when a browser reconnects to a site it visited recently, session resumption can skip most of the work.

7. SSL/TLS Certificates and Certificate Authorities

A TLS certificate is a digital document that links a domain name, such as www.shop.com, to a public key. It is issued and digitally signed by a Certificate Authority (CA), an organisation that browsers and operating systems have agreed to trust.

Browsers do not trust each website certificate directly. They follow a chain of trust:

The certificate chain of trust Three boxes from left to right: a root certificate authority stored in the operating system or browser, an intermediate certificate authority signed by the root, and the website certificate for www.shop.com signed by the intermediate. Arrows labelled signs connect them. Root CA built into OS / browser Intermediate CA signed by the root www.shop.com signed by intermediate signs signs browser verifies from the website back to a trusted root The server sends its own certificate plus the intermediate; the root is already on the device
Figure 3: The browser checks each signature back to a root certificate it already trusts. If any link is broken, it shows a security warning.

Certificates come in three validation levels:

  • Domain Validated (DV): proves you control the domain. Issued automatically in minutes, often free through services such as Let's Encrypt using the ACME protocol.
  • Organisation Validated (OV): the CA also checks that the organisation exists.
  • Extended Validation (EV): stricter checks of the organisation's legal identity. Browsers no longer show it very differently, so it has become less common.

Certificates expire, and validity periods have been getting shorter over time, which is why automatic renewal is now standard practice.

8. HTTP vs HTTPS: Comparison Table

AspectHTTPHTTPS
Full formHyperText Transfer ProtocolHyperText Transfer Protocol Secure
URL schemehttp://https://
Default port80443
EncryptionNone, data is plain textEncrypted with TLS
Data integrityChanges in transit go unnoticedAny change is detected
Server identityNot verifiedVerified with a CA-signed certificate
Certificate neededNoYes
Browser label"Not secure" warningPadlock or neutral secure indicator
HTTP/2 and HTTP/3 in browsersNot supportedSupported
Modern browser featuresMany APIs blocked (service workers, geolocation, camera)Fully available
SEODisadvantagedPreferred by search engines
Suitable forLocal development and closed test networks onlyEvery public website and API

9. Is HTTPS Slower Than HTTP?

Years ago, HTTPS had a noticeable cost. Today, the difference is very small and often HTTPS is faster in practice:

  • The handshake is short. TLS 1.3 adds one round trip for a new connection, and resumed connections can be even quicker.
  • Encryption is cheap. Modern CPUs have built-in instructions for AES, so encrypting data uses very little processing power.
  • HTTP/2 and HTTP/3 need HTTPS. Browsers only use these faster protocols over encrypted connections. Their multiplexing, header compression and faster connection setup usually outweigh the TLS cost.
  • Connections are reused. The handshake happens once, then many requests share the same connection.

In system design, TLS is commonly terminated at a load balancer, reverse proxy or CDN edge close to the user. This keeps the handshake short and moves the work away from application servers.

10. Enabling HTTPS in Spring Boot

For local testing, you can create a self-signed certificate with the JDK's keytool. In production, you would use a certificate from a CA instead.

Terminal
keytool -genkeypair -alias javabytechie -keyalg RSA -keysize 2048 \
        -storetype PKCS12 -keystore keystore.p12 -validity 365 \
        -dname "CN=localhost"

Copy keystore.p12 into src/main/resources and tell Spring Boot to use it:

application.properties
server.port=8443
server.ssl.enabled=true
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-type=PKCS12
server.ssl.key-store-password=${KEYSTORE_PASSWORD}
server.ssl.key-alias=javabytechie

Since Spring Boot 3.1, you can also use SSL bundles, which accept the PEM files (.crt and .key) that most CAs and Let's Encrypt provide:

application.yml
spring:
  ssl:
    bundle:
      pem:
        web:
          keystore:
            certificate: "file:/etc/certs/fullchain.pem"
            private-key: "file:/etc/certs/privkey.pem"
server:
  port: 8443
  ssl:
    bundle: web

Start the application and open https://localhost:8443. With a self-signed certificate the browser will warn you, because no trusted CA signed it. That warning is the authentication guarantee doing its job.

To tell browsers they must always use HTTPS for your site, Spring Security can send the Strict-Transport-Security header (Spring Security sends it by default on HTTPS requests, and this shows how to tune it):

SecurityConfig.java
package com.javabytechie.https;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
            .headers(headers -> headers
                .httpStrictTransportSecurity(hsts -> hsts
                    .includeSubDomains(true)
                    .maxAgeInSeconds(31_536_000)));   // one year
        return http.build();
    }
}

11. Making HTTPS Calls from Java

Java's HttpClient handles TLS automatically. It verifies the server's certificate against the JDK's trusted CA list and checks that the host name matches. You can even inspect which TLS version and cipher were agreed:

HttpsClientDemo.java
package com.javabytechie.https;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class HttpsClientDemo {

    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder(URI.create("https://www.example.com/"))
                .GET()
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status   : " + response.statusCode());
        System.out.println("Version  : " + response.version());
        response.sslSession().ifPresent(session -> {
            System.out.println("Protocol : " + session.getProtocol());
            System.out.println("Cipher   : " + session.getCipherSuite());
        });
    }
}
Output
Status   : 200
Version  : HTTP_2
Protocol : TLSv1.3
Cipher   : TLS_AES_256_GCM_SHA384

The exact version and cipher depend on the server. If the certificate is expired, self-signed or issued for a different host name, the call fails with an SSLHandshakeException. The correct fix is to install a valid certificate on the server, or, for an internal CA, add that CA to a trust store your application uses. Never "fix" it by writing a TrustManager that accepts every certificate, because that silently removes the protection HTTPS provides.

12. Redirects and HSTS

Even when your site supports HTTPS, a user may type shop.com without the scheme, and the browser's first request may go over plain HTTP. Two tools close this gap:

  • Permanent redirect: the server answers every HTTP request with 301 Moved Permanently pointing to the HTTPS URL. This is usually done at the load balancer or reverse proxy.
  • HSTS (HTTP Strict Transport Security): the response header Strict-Transport-Security: max-age=31536000; includeSubDomains tells the browser to use HTTPS for this domain for a year, without ever trying HTTP first. Sites can also ask to be added to browsers' built-in HSTS preload list, so even the very first visit is protected.
nginx: redirect all HTTP to HTTPS
server {
    listen 80;
    server_name shop.com www.shop.com;
    return 301 https://$host$request_uri;
}

13. Moving a Website from HTTP to HTTPS

  1. Get a certificate covering every domain and subdomain you serve, and set up automatic renewal.
  2. Enable HTTPS on the load balancer, reverse proxy or application server, using TLS 1.2 and 1.3 only.
  3. Fix mixed content: update links to images, scripts and stylesheets so they all use https://. Browsers block or warn about HTTP resources on HTTPS pages.
  4. Redirect HTTP to HTTPS with permanent 301 redirects.
  5. Mark cookies as Secure so they are never sent over plain HTTP.
  6. Turn on HSTS, starting with a short max-age and increasing it once everything works.
  7. Update external references: canonical URLs, sitemaps, API clients and webhooks.
  8. Monitor certificate expiry dates and TLS errors.

14. Common Mistakes to Avoid

  • Encrypting only the login page. If the rest of the site uses HTTP, the session cookie can be stolen right after login. Use HTTPS everywhere.
  • Disabling certificate checks in code. Trust-all managers and host name verifiers that always return true are a common source of serious vulnerabilities.
  • Letting certificates expire. An expired certificate takes a site offline for most users. Automate renewal and set alerts.
  • Mixed content. Loading a single script over HTTP on an HTTPS page lets an attacker modify that script and take over the page.
  • Supporting old protocols. SSL 3.0, TLS 1.0 and TLS 1.1 have known weaknesses and should be disabled.
  • Committing private keys or keystore passwords to Git. Store them in a secrets manager or environment variables.

15. Best Practices

  • Serve every page, API and asset over HTTPS, including internal admin tools.
  • Allow only TLS 1.2 and TLS 1.3 with modern cipher suites that provide forward secrecy.
  • Automate certificate issuing and renewal with ACME, or use your cloud provider's managed certificates.
  • Redirect HTTP to HTTPS and enable HSTS once the migration is stable.
  • Set Secure, HttpOnly and SameSite on session cookies.
  • Terminate TLS close to users (CDN or load balancer), and encrypt internal traffic too when the network is shared or untrusted, for example with mutual TLS between microservices.
  • Test your configuration regularly with an online TLS scanner and fix any warnings.

16. Summary

  • HTTP sends data as readable text on port 80, so anyone on the network path can read or modify it.
  • HTTPS is HTTP inside a TLS connection on port 443, providing confidentiality, integrity and server authentication.
  • The TLS handshake uses public-key cryptography to agree on session keys, then fast symmetric encryption protects the data. TLS 1.3 needs only one round trip.
  • Certificates issued by trusted Certificate Authorities prove a server owns its domain, verified through a chain of trust.
  • HTTPS is no longer slow, it enables HTTP/2 and HTTP/3, and it is required for every public website and API.

Treat HTTPS as the default for everything you build, and treat plain HTTP as a local-development convenience only. Open the FAQ tab for answers to common questions about HTTP and HTTPS.