HTTP vs HTTPS: Differences, TLS Handshake and How HTTPS Works
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:
POST /login HTTP/1.1
Host: shop.example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 35
username=priya&password=MySecret123
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.
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:
| Guarantee | What it means | Stops |
|---|---|---|
| Confidentiality (encryption) | Data is scrambled so only the browser and the server can read it. | Eavesdropping |
| Integrity | Every message carries a cryptographic check. Any change made in transit is detected and the connection is dropped. | Tampering and injected content |
| Authentication | The 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:
- 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).
- 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.
- 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.
- Finished: each side sends a short encrypted message that confirms the whole handshake was not tampered with.
- 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:
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
| Aspect | HTTP | HTTPS |
|---|---|---|
| Full form | HyperText Transfer Protocol | HyperText Transfer Protocol Secure |
| URL scheme | http:// | https:// |
| Default port | 80 | 443 |
| Encryption | None, data is plain text | Encrypted with TLS |
| Data integrity | Changes in transit go unnoticed | Any change is detected |
| Server identity | Not verified | Verified with a CA-signed certificate |
| Certificate needed | No | Yes |
| Browser label | "Not secure" warning | Padlock or neutral secure indicator |
| HTTP/2 and HTTP/3 in browsers | Not supported | Supported |
| Modern browser features | Many APIs blocked (service workers, geolocation, camera) | Fully available |
| SEO | Disadvantaged | Preferred by search engines |
| Suitable for | Local development and closed test networks only | Every 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.
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:
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:
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):
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:
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());
});
}
}
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 Permanentlypointing 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; includeSubDomainstells 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.
server {
listen 80;
server_name shop.com www.shop.com;
return 301 https://$host$request_uri;
}
13. Moving a Website from HTTP to HTTPS
- Get a certificate covering every domain and subdomain you serve, and set up automatic renewal.
- Enable HTTPS on the load balancer, reverse proxy or application server, using TLS 1.2 and 1.3 only.
- 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. - Redirect HTTP to HTTPS with permanent 301 redirects.
- Mark cookies as
Secureso they are never sent over plain HTTP. - Turn on HSTS, starting with a short
max-ageand increasing it once everything works. - Update external references: canonical URLs, sitemaps, API clients and webhooks.
- 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,HttpOnlyandSameSiteon 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 Interview Questions tab for interview questions and answers about HTTP and HTTPS.
HTTP vs HTTPS: Interview Questions and Answers
The questions on this topic that come up most often in system design interviews for senior engineers, tech leads and architects. Each answer covers the reasoning, trade-offs and real-world examples that interviewers look for.
Q1. What does HTTPS actually protect, and what does it not protect?
HTTPS is HTTP over TLS. It provides confidentiality (traffic is encrypted), integrity (tampering is detected) and server authentication (the certificate proves you are talking to the real domain). It does not hide which IP and, usually, which hostname you are connecting to (SNI, unless Encrypted Client Hello is used), it does not protect data once it reaches the server, and it does not prove that the site is trustworthy, only that it controls the domain.
Q2. Walk through a TLS 1.3 handshake at a high level.
- The client sends ClientHello with supported cipher suites and a key share (Diffie-Hellman public value).
- The server replies with ServerHello and its own key share; both sides derive the same session keys.
- The server sends its certificate and a signature proving it holds the private key, then Finished, all already encrypted.
- The client verifies the certificate chain and hostname, sends Finished, and application data flows.
TLS 1.3 needs one round trip (1-RTT) instead of two in TLS 1.2, and supports 0-RTT resumption for repeat visits, with replay risk, so 0-RTT should only carry idempotent requests.
Q3. What is forward secrecy and why does it matter?
With ephemeral Diffie-Hellman key exchange, each session gets new keys that are never derived from the server's long-term private key. If that private key is stolen later, previously recorded traffic still cannot be decrypted. TLS 1.3 makes forward secrecy mandatory by removing static RSA key exchange.
Q4. How does certificate validation work, and what goes wrong in production?
The client checks that the certificate chains to a trusted root CA through intermediates, that the hostname matches, and that it is within its validity period and not revoked. Common production problems: expired certificates (automate renewal with ACME / Let's Encrypt or a cloud certificate manager, and alert on expiry), missing intermediate certificates on the server, hostname mismatches behind load balancers, and clients with outdated trust stores.
Q5. Where should TLS be terminated in a large system?
Usually at the edge (CDN or load balancer) for central certificate management and to offload CPU. Inside the network, zero-trust designs re-encrypt traffic or use mutual TLS between services, often through a service mesh, so that a compromised internal host cannot read or forge traffic. Terminating at the edge and using plain HTTP internally is a deliberate, risk-accepted choice, not a default.
Q6. What is HSTS, and why is redirecting HTTP to HTTPS not enough?
A redirect still lets the first request go over plain HTTP, where an attacker on the network can intercept it and keep the user on HTTP (SSL stripping). The Strict-Transport-Security header tells browsers to use HTTPS only for that domain for a set time, and HSTS preloading builds it into browsers so even the first visit is protected. Once enabled, every subdomain covered must support HTTPS.
Q7. Does HTTPS make a site slower?
Much less than people think. TLS 1.3 adds one round trip for new connections and none for resumed ones, symmetric encryption is very cheap on modern CPUs with AES instructions, and HTTPS is required for HTTP/2 in browsers and for HTTP/3, which bring larger speed gains. Connection reuse and keep-alive remove most of the remaining handshake cost.