Introduction to Cryptography

Hash functions, symmetric vs asymmetric encryption, TLS, and common algorithms you'll encounter in security.

Medium 40m 3 tasks

Learning Objectives

  • Explain what a hash function does and why it's one-way
  • Describe the difference between symmetric and asymmetric encryption
  • Explain how TLS establishes an encrypted connection
  • Identify common algorithms: AES, RSA, SHA-256, bcrypt

Cryptography is the science of protecting information. It's the backbone of secure communication, authentication, and data integrity. You encounter it constantly in security work — from HTTPS to password storage to exploit development.

Why Cryptography Matters in Security

  • HTTPS — TLS protects web traffic from interception
  • Passwords — stored as hashes, not plaintext
  • Digital signatures — verify software hasn't been tampered with
  • VPNs — encrypt network tunnels
  • Ransomware — attackers use encryption as a weapon

Hashing

A hash function takes input of any size and produces a fixed-size output (the hash/digest). Good hash functions are:

  • Deterministic — same input always gives same output
  • One-way — you can't reverse a hash to get the input
  • Avalanche effect — tiny input change → completely different hash
  • Collision resistant — hard to find two inputs with same hash
SHA-256("hello")   = 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
SHA-256("Hello")   = 185f8db32921bd46d35de87787e3f207f73e4b5f4b16e73ab8cee36d4a30cb
SHA-256("hello!")  = ce06092fb948d9af91f70574af9bc34e2b2c04e3b85fea4bb41d11f0f11cedc

Security uses:
- Storing passwords (store hash, compare hash on login)
- File integrity verification (download file, check hash matches)
- Checksums in forensics (prove a file hasn't been modified)

Common Hash Algorithms

Algorithm Output Size Status
MD5 128 bits (32 hex chars) Broken — collision attacks exist
SHA-1 160 bits (40 hex chars) Deprecated — collision found 2017
SHA-256 256 bits (64 hex chars) Safe — current standard
SHA-3 Variable Safe — newer standard
bcrypt 60 chars Safe — designed for passwords (slow)

Password Hashing vs Encryption

  • Hashing is one-way. Passwords should be hashed, not encrypted.
  • Cracking hashed passwords means trying inputs until you find a match (brute force, dictionary, rainbow tables).
  • Salting adds random data before hashing to defeat rainbow tables.
Without salt:
  hash("password123") → 482c811da5d5b4bc6d497ffa98491e38

With salt:
  hash("xK9m" + "password123") → a9f3c2...  (unique per user)
  hash("pL4n" + "password123") → 77e1b9...  (different salt = different hash)

Symmetric Encryption

One key is used to both encrypt and decrypt.

Plaintext ──[Encrypt with Key]──► Ciphertext
Ciphertext ──[Decrypt with Key]──► Plaintext

Fast — used for bulk data encryption.

Problem: How do you securely share the key with the other party?

AES (Advanced Encryption Standard)

The gold standard for symmetric encryption.
- Block cipher: encrypts data in 128-bit blocks
- Key sizes: 128, 192, or 256 bits
- Used in: TLS, disk encryption, file encryption, VPNs


Asymmetric Encryption (Public Key Cryptography)

Two keys: a public key (share with everyone) and a private key (keep secret).

┌──────────────────────────────────────────────┐
│  Encrypted with PUBLIC key?                  │
│   Only the PRIVATE key can decrypt it       │
│    (used for: secure messages TO someone)    │
├──────────────────────────────────────────────┤
│  Signed with PRIVATE key?                    │
│   Anyone with the PUBLIC key can verify it  │
│    (used for: digital signatures)            │
└──────────────────────────────────────────────┘

Solves the key exchange problem: You can freely share your public key. Anyone can encrypt a message that only your private key can open.

RSA

The most common asymmetric algorithm.
- Key sizes: 2048 or 4096 bits (much larger than AES — asymmetric is slow)
- Used for: key exchange in TLS, digital signatures, SSH keys


How HTTPS Works (TLS Handshake)

HTTPS combines asymmetric encryption (for key exchange) and symmetric encryption (for bulk data):

Browser                         Server
   │                               │
   │──── ClientHello ─────────────►│  "I support TLS 1.3, here are my cipher suites"
   │                               │
   │◄─── ServerHello + Certificate─│  "Use AES-256, here's my public key cert"
   │                               │
   │  [Browser verifies cert       │
   │   against trusted CAs]        │
   │                               │
   │──── Key Exchange ────────────►│  Establish shared session key (asymmetric)
   │                               │
   │◄═══ Encrypted Data ══════════►│  All further data encrypted with session key (AES)

Digital Signatures

Signatures prove who sent a message and that it wasn't tampered with.

Alice signs with her PRIVATE key:
  document + hash(document) encrypted with private key

Bob verifies with Alice's PUBLIC key:
  decrypts the signature → gets the hash → recalculates hash of document
  if they match → document is authentic and untampered

Uses: Code signing (proving software is from a legitimate publisher), SSL certificates, Git commits, email (S/MIME, PGP).


PKI — Public Key Infrastructure

How do you trust a public key? Certificate Authorities (CAs) are trusted third parties that sign certificates, vouching that a public key belongs to who they claim.

Root CA (Mozilla/OS trusts these)
  └── Intermediate CA
        └── website certificate (signed by intermediate CA)

When you visit a website, your browser checks the certificate chain up to a trusted root CA. If anything is wrong (expired, wrong domain, untrusted CA), you get a security warning.

Attacks on PKI:
- Rogue CA compromise (real attack: DigiNotar 2011)
- Certificate mis-issuance
- SSL stripping (downgrade HTTPS → HTTP)


Key Takeaways

  • Hashing is one-way — used for passwords and integrity checks
  • Symmetric encryption (AES) is fast — one key for both operations
  • Asymmetric encryption (RSA) solves key exchange — public key encrypts, private key decrypts
  • TLS combines both: asymmetric for handshake, symmetric for data
  • PKI establishes trust through certificate chains
  • MD5 and SHA-1 are broken — use SHA-256 or better

A hash function takes input of any size and produces a fixed-size output (digest). It's a one-way function — you can't reverse it to get the input back.

PropertyMeaningSecurity implication
DeterministicSame input always → same hashLets you verify integrity without storing the file
One-way (preimage)Can't reverse hash → originalPasswords stored as hashes, not plaintext
Collision resistantHard to find two inputs with same hashPrevents forging document signatures
Avalanche effect1 bit change → completely different hashMD5('hello') vs MD5('hEllo') look nothing alike
Fixed outputSHA-256 always → 256 bits (64 hex chars)Easy to store and compare
# Hash a file sha256sum /etc/passwd md5sum /etc/passwd # Hash a string echo -n 'password' | sha256sum # 5e884898... (this is why 'password' is a bad password — everyone knows this hash) # Python import hashlib hashlib.sha256(b'hello').hexdigest() # '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
⚠ Security: MD5 and SHA-1 are broken for security use — collision attacks exist. Always use SHA-256 or SHA-3 for integrity checks. For passwords, use bcrypt, Argon2, or scrypt (slow by design).
✦ Answer the questions to complete this task

What makes a hash function 'one-way'?

Why is MD5 no longer safe for password hashing?

Encryption scrambles data so only authorised parties can read it. There are two fundamentally different approaches — each with distinct use cases.

🔑 Symmetric

One key encrypts and decrypts. Sender and receiver must share the secret key in advance.

  • Very fast — hardware accelerated
  • AES-256 is the gold standard
  • Key distribution problem: how to share the key securely?
✦ AES, ChaCha20, 3DES

🗝️ Asymmetric

Two mathematically linked keys: public (share freely) + private (keep secret). Encrypt with public, decrypt with private.

  • Slow — 100–1000× slower than symmetric
  • Solves key distribution problem
  • RSA-2048+ or ECC (ECDSA)
✦ RSA, ECDSA, Diffie-Hellman
TLS uses both: asymmetric to securely exchange a session key, then symmetric (AES) for the actual data — best of both worlds.
AlgorithmTypeKey sizeUse case
AES-256Symmetric256-bitDisk encryption, TLS data
RSAAsymmetric2048–4096-bitKey exchange, signatures
ECDSA / Ed25519Asymmetric256-bitSSH keys, TLS certificates
bcryptHashing (KDF)Password storage
SHA-256HashingFile integrity, HMAC
✦ Answer the questions to complete this task

Which encryption type uses a public key to encrypt and a private key to decrypt?

Why does TLS use symmetric encryption for the actual data transfer?

TLS (Transport Layer Security) provides authentication, confidentiality, and integrity for HTTPS connections. Every time you see 🔒 in a browser, TLS is running.

TLS Handshake
StepWho sendsWhat it does
ClientHelloBrowserOffers TLS versions and cipher suites it supports
ServerHello + CertServerPicks cipher, sends its X.509 certificate
Cert VerificationBrowserChecks cert chain against trusted CAs
Key ExchangeBrowserSends pre-master secret (RSA) or DH parameters
FinishedBothDerive symmetric session key; confirm everything
DataBothEncrypted with AES (or ChaCha20) session key
⚠ Security: SSL stripping attacks downgrade HTTPS to HTTP. Defence: HTTP Strict Transport Security (HSTS) header forces browsers to always use HTTPS. Certificate pinning prevents MITM with rogue CA certificates.
✦ Answer the questions to complete this task

What does a browser do after receiving the server's TLS certificate?

HSTS (HTTP Strict Transport Security) protects against:

💪 Exercises & Challenges

📝 MCQ Medium +25 XP

Cryptography Fundamentals Quiz

Test your understanding of hashing, encryption, and TLS.

Start →
🚩 Challenge Medium +25 XP

Identify the Hash Algorithm

Identify a hash algorithm from its output characteristics.

Start →