Skip to main content
Cryptography Basics
CHAPTER 12

Cryptography in Web Applications

Updated: May 15, 2026
20 min read

# CHAPTER 12

Cryptography in Web Applications

1. Introduction

The HTTP protocol is "stateless." When you navigate from a website's homepage to your account profile, the server immediately forgets who you are. To stay logged in, the server must give your browser a digital token, which your browser hands back with every single click. But how do we prevent users from forging these tokens to access someone else's account? The answer is applied cryptography. In this chapter, we will explore how web applications utilize encryption, hashing, and digital signatures to secure session cookies, implement JSON Web Tokens (JWTs), and protect sensitive data at rest.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the stateless nature of HTTP and the necessity of Sessions.
  • Differentiate between Stateful Sessions and Stateless JWTs.
  • Explain the cryptographic structure of a JSON Web Token (JWT).
  • Understand how to secure browser Cookies using the Secure and HttpOnly flags.
  • Identify common cryptographic flaws in web application architecture.

3. Beginner-Friendly Explanation

Imagine going to a highly secure amusement park.
  • You pay at the front gate (Login with Password).
  • The gate attendant cannot follow you around all day to tell the ride operators you paid.
  • The Cookie (Stateful): The attendant gives you a complex, random number stamp on your hand (e.g., 8f7b2c). The park keeps a master ledger. At every ride, they check your hand, look up 8f7b2c in the ledger, and confirm you paid.
  • The JWT (Stateless): The attendant gives you a printed pass that explicitly says "Alice paid for all rides." To stop you from printing your own fake pass, the attendant stamps it with an unforgeable cryptographic Wax Seal (Digital Signature). The ride operator doesn't need a ledger; they just verify the Wax Seal.

4. Securing Session Cookies

When using stateful sessions, the server sends the browser a Session ID stored in a Cookie. If a hacker steals this cookie, they can hijack your session and impersonate you without needing your password. Cryptographic and Browser Defenses:
  1. 1. Cryptographically Secure Pseudo-Random Number Generator (CSPRNG): The Session ID must be generated using high-quality randomness. If the ID is predictable (e.g., user1, user2), a hacker can simply guess the next valid session.
  1. 2. The Secure Flag: Instructs the browser to *only* send the cookie over an encrypted HTTPS connection, never over plaintext HTTP.
  1. 3. The HttpOnly Flag: Instructs the browser to hide the cookie from JavaScript. This mathematically defeats Cross-Site Scripting (XSS) attacks trying to steal the cookie.

5. JSON Web Tokens (JWT)

Modern APIs and Microservices often use JWTs instead of traditional cookies. A JWT is a stateless, digitally signed token. A JWT has three parts, separated by periods: Header.Payload.Signature
  1. 1. Header: Defines the algorithm used (e.g., HS256 for HMAC + SHA-256).
  1. 2. Payload: The actual data (e.g., {"user_id": 42, "role": "admin"}). *Note: The payload is merely Base64 encoded, NOT encrypted! Anyone can read it.*
  1. 3. Signature: The cryptographic magic. The server hashes the Header and Payload, and encrypts the hash using a Secret Key known only to the server.

If a hacker modifies the payload from "role": "user" to "role": "admin", the cryptographic Signature will break, and the server will reject the token immediately.

6. Encryption Data at Rest

Web applications collect sensitive data (Credit Cards, Social Security Numbers). Hashing is great for passwords, but useless for credit cards because the application needs to read the credit card later to charge it. This data must be Encrypted at Rest using Symmetric Encryption (AES-256).
  • The Challenge: Where do you safely store the AES decryption key? If you store the key in the exact same database as the encrypted credit cards, a hacker who steals the database gets both. The key must be stored in a completely isolated, hardened system (like a Key Management Service or a Hardware Security Module).

7. Mini Project: Inspect a JWT Structure

Let's see how transparent (yet secure) a JWT actually is.

Step-by-Step Walkthrough:

  1. 1. Find a JWT: If you look at the local storage of modern web apps, you'll often see a long string starting with eyJ...
  1. 2. Decode it: Go to a safe, public tool like jwt.io.
  1. 3. Paste the Token: Paste a sample JWT into the tool.
  1. 4. Analyze the Payload: You will instantly see the decoded payload in plaintext. You can see the user's ID, their role, and the token's expiration date.
  1. 5. Analyze the Security: Notice that while you can easily read the data, you cannot *change* the data. If you edit the payload on jwt.io, the "Signature Verified" indicator will turn red, proving the cryptographic integrity is broken.

8. Real-World Scenarios

A startup builds a new API. To keep things simple, they design their own authentication tokens. They create a token by combining the username and the date: Alice2024-10-27. They encode this in Base64 and send it to the browser. A malicious user decodes their own token, realizes the pattern, changes the name to Admin2024-10-27, re-encodes it, and sends it back to the server. Because the startup failed to implement a Cryptographic Signature (like an HMAC or a proper JWT), the server blindly trusts the forged token, resulting in a total application compromise.

9. Best Practices

  • Do NOT Store Sensitive Data in a JWT Payload: Because the payload of a standard JWT is merely encoded, not encrypted, anyone who intercepts the token can read the contents. Never put a user's password, SSN, or private email address inside the JWT payload.
When handling financial or healthcare data within a web application, regulatory frameworks (like PCI-DSS for credit cards) explicitly mandate the use of strong encryption algorithms for data at rest, and strict protocols for key rotation and access control. Using deprecated cryptography (like DES) in these applications can lead to massive compliance fines.

11. Exercises

  1. 1. Explain why setting the HttpOnly flag on a session cookie prevents session hijacking via Cross-Site Scripting (XSS).
  1. 2. If a JWT is not encrypted, how does it prevent a user from elevating their privileges to "admin"?

12. FAQs

Q: Can I invalidate (logout) a JWT easily? A: No, and this is a major drawback of JWTs. Because they are stateless, the server doesn't keep a list of active tokens. A JWT is valid until its built-in expiration time runs out. If a JWT is stolen, the attacker can use it until it expires. Web architectures often mitigate this by giving JWTs a very short lifespan (e.g., 15 minutes).

13. Interview Questions

  • Q: Detail the structural components of a JSON Web Token (JWT). How is the signature generated, and how does the server verify its authenticity upon receipt?
  • Q: A developer intends to store a user's credit card number in a database and plans to use SHA-256 to secure it. Explain why this is architecturally incorrect and propose the proper cryptographic solution.

14. Summary

In Chapter 12, we applied cryptographic primitives to secure the stateless HTTP protocol. We explored how Session Cookies maintain identity and how setting the Secure and HttpOnly flags hardens them against attack. We dissected JSON Web Tokens (JWTs), illustrating how Digital Signatures provide unforgeable, stateless authentication. Finally, we emphasized that while hashing protects passwords, protecting retrievable sensitive data requires robust Symmetric Encryption and disciplined Key Management.

15. Next Chapter Recommendation

Web applications live on servers, and today, those servers live in the cloud. How do cloud providers manage encryption keys at a massive scale? Proceed to Chapter 13: Cryptography in Cloud Computing.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·