Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 79 ยท Network Security

Cryptography for Networking

Understand the cryptography behind secure networks: symmetric and asymmetric encryption, hashes, HMAC, Diffie-Hellman key exchange and digital signatures, with toy demos.

Every secure protocol you use, from HTTPS to Wi-Fi's WPA3 to a VPN, is built from a small set of cryptographic tools. You do not need to invent or even implement them (you should never do that for real systems), but you do need to know what each tool promises, what it does not, and how they combine. That knowledge lets you read a TLS handshake, choose settings sensibly and spot a design that cannot work.

This lesson covers five building blocks: symmetric encryption, asymmetric (public-key) cryptography, hash functions, message authentication codes and digital signatures, plus the Diffie-Hellman key exchange that lets two strangers agree on a secret in public. The code examples are deliberately small "toy" versions so you can see the mathematics working. They are for learning only; real systems use vetted libraries and much larger numbers. The goals they serve (confidentiality, integrity, authentication) were introduced in network security fundamentals.

The big picture

Tool Keys Provides Typical examples
Symmetric cipher one shared secret key confidentiality (fast, bulk data) AES-GCM, ChaCha20-Poly1305
Hash function none a fixed-size fingerprint, integrity checks SHA-256, SHA-3
MAC one shared secret key integrity and authenticity between two parties HMAC-SHA256, Poly1305
Key exchange each side has a private/public pair agree on a shared secret over an open channel Diffie-Hellman, X25519
Public-key encryption public key encrypts, private key decrypts confidentiality without a shared secret RSA, hybrid schemes
Digital signature private key signs, public key verifies authenticity, integrity, non-repudiation RSA, ECDSA, Ed25519

Hash functions and MACs

A cryptographic hash function turns any amount of data into a short fixed-size value (SHA-256 gives 32 bytes). It has three key properties:

  • Pre-image resistance: given a digest, you cannot find an input that produces it.
  • Second pre-image resistance: given one input, you cannot find a different input with the same digest.
  • Collision resistance: you cannot find any two inputs with the same digest.

A good hash also shows the avalanche effect: changing one bit of the input changes about half of the output bits. Use SHA-256 or SHA-3 today. MD5 and SHA-1 are broken for security uses because collisions can be produced on purpose.

A hash alone does not prove who made a message, because anybody can compute it. A message authentication code (MAC) mixes a secret key into the computation, so only someone who knows the key can create a valid tag. HMAC is the standard construction on top of a hash. The receiver recomputes the tag and compares; always compare tags with a constant-time function so timing does not leak information.

Hashes and MACs also appear in places you might not expect: file download checksums, Git commit IDs, the integrity check in each TLS record, and key derivation functions (KDFs) that turn one secret into several independent keys.

Python Hashes, avalanche and HMAC

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The MD5 algorithm, and why it is retired for security

MD5 (Message-Digest algorithm 5) was designed by Ronald Rivest in 1991 as a successor to MD4. It turns any input into a 128-bit digest, shown as 32 hexadecimal digits. It works in five steps:

  1. Pad the message: append a single 1 bit, then zeros, until the length is 64 bits short of a multiple of 512 bits.
  2. Append the length of the original message as a 64-bit number.
  3. Initialize the MD buffer: four 32-bit registers (A, B, C, D) start with fixed constants.
  4. Process each 512-bit block in four rounds of 16 operations each, mixing the block into the registers with bitwise functions, additions, rotations and a table of 64 constants derived from the sine function.
  5. Output the final A, B, C, D registers joined together (128 bits).

MD5 is fast and is still fine as a quick checksum against accidental corruption, but it is broken for security: researchers can create two different files with the same MD5 (a collision), and this has been used to forge certificates, so never use MD5 for signatures, certificates or password storage. Alternatives are SHA-256 and SHA-3 for general use, and slow, salted password hashes such as Argon2, bcrypt or scrypt for passwords. Other digests you may hear about are RIPEMD-160 (160-bit, used in some Bitcoin address calculations) and Whirlpool (512-bit, designed by Rijmen and Barreto), which are not broken but are used far less than SHA-2.

Python MD5 versus SHA-256: size and avalanche

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

About half the bits flip for a small change in every algorithm. The padding rule explains why a 55-byte message fits in one 64-byte block but a 56-byte message needs two.

Symmetric encryption

In symmetric (shared-key) encryption, both parties use the same secret key to encrypt and decrypt. It is fast, which is why it protects the bulk of traffic. Ciphers come in two families:

  • Block ciphers such as AES encrypt fixed-size blocks (16 bytes). A mode of operation describes how to handle long messages. The old ECB mode, which encrypts each block independently, leaks patterns and must not be used. Modern protocols use AEAD modes such as AES-GCM, which encrypt and authenticate in one step, so any change to the ciphertext is detected.
  • Stream ciphers such as ChaCha20 generate a pseudo-random keystream from the key and a nonce and XOR it with the data. ChaCha20-Poly1305 is the AEAD pairing popular on phones.

Key sizes of 128 or 256 bits are considered safe today; brute-forcing 128 bits is far beyond any computer.

The hard parts of symmetric cryptography are not the ciphers but how they are used:

  • The nonce (or IV) must never repeat for the same key. Reusing a nonce with a stream cipher lets an attacker XOR two ciphertexts, cancelling the keystream and revealing the relationship between the plaintexts. The demo below shows it.
  • The key must be shared secretly. That is the key distribution problem: two people who have never met cannot send a key over the network, because anyone watching would learn it. Public-key cryptography solves it.
Python A toy stream cipher and the nonce-reuse disaster

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Diffie-Hellman key exchange

Diffie-Hellman (DH) lets two parties create a shared secret by talking only over a public channel. The usual analogy is mixing paint: each side mixes a secret color into a public base color and sends the result. Mixing your own secret color into what you received gives both the same final color, but an observer cannot unmix the paint.

In numbers: the parties agree on public values, a large prime p and a base g. Alice picks a secret a and sends A = g^a mod p. Bob picks a secret b and sends B = g^b mod p. Alice computes B^a mod p and Bob computes A^b mod p. Both equal g^(ab) mod p. An eavesdropper sees p, g, A and B but would need to solve the discrete logarithm problem (find a from A) to get the secret, which is believed to be infeasible for large enough numbers. Modern systems use the same idea on elliptic curves (ECDH, for example X25519), which gives the same security with much smaller keys.

sequenceDiagram
    participant A as Alice (secret a)
    participant B as Bob (secret b)
    Note over A,B: public: prime p and base g
    A->>B: A = g^a mod p
    B->>A: B = g^b mod p
    Note over A: shared = B^a mod p
    Note over B: shared = A^b mod p

Both sides compute g^(ab) mod p. Only A and B ever cross the network.

Two important properties:

  • Forward secrecy. If each session uses fresh (ephemeral) DH values and then throws them away, recording the traffic today and stealing a server's long-term key tomorrow does not reveal past sessions. TLS 1.3 requires this.
  • No authentication. Plain DH does not tell you who you agreed a key with. An active attacker can run one exchange with Alice and another with Bob and sit in the middle (see the third part of the demo). Real protocols therefore sign the exchange with a long-term key, as explained in TLS and HTTPS.
Python Toy Diffie-Hellman and a man in the middle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Asymmetric (public-key) cryptography

In public-key cryptography each party has a key pair: a public key that can be shared with the world and a private key that never leaves its owner. The two are mathematically linked, but you cannot derive the private key from the public one.

  • Encryption: anyone can encrypt a message with Bob's public key, and only Bob's private key can decrypt it.
  • Signatures: Bob signs with his private key, and anyone can verify with his public key.

The oldest widely used system is RSA, based on the difficulty of factoring a product of two large primes. Pick primes p and q, publish n = p*q and an exponent e, and keep d (the modular inverse of e) secret. Encrypting is c = m^e mod n; decrypting is m = c^d mod n. Today RSA keys are at least 2048 bits, and elliptic-curve systems (ECDSA, Ed25519) give comparable security with 256-bit keys.

Public-key operations are slow, thousands of times slower than AES. So real protocols use a hybrid design: a public-key method sets up a fresh symmetric key, and a fast symmetric cipher encrypts the actual traffic.

flowchart LR
    K["Key exchange<br/>(ECDH) + signature"] --> S["Shared secret"]
    S --> D["Key derivation (KDF)"]
    D --> E["Symmetric keys<br/>(AES-GCM / ChaCha20)"]
    E --> T["Encrypted, authenticated traffic"]

Slow public-key math happens once per connection; fast symmetric crypto carries the data.

Note that "textbook" RSA, as shown below, is not safe as is. Real implementations add padding (OAEP for encryption, PSS for signatures) to defeat attacks, and a bad random number generator can destroy any system.

Digital signatures

A digital signature gives integrity, authenticity and non-repudiation. The signer hashes the message and transforms the hash with the private key. The verifier uses the signer's public key to check the result against their own hash of the message. If even one bit of the message changed, the check fails. And because only the private key holder could have created it, the signer cannot plausibly deny it.

This is exactly what the certificates in TLS contain: a certificate authority signs "this public key belongs to example.com", and your browser verifies the signature. Signatures also protect software updates, Git tags, DNS records (DNSSEC) and email (DKIM).

Python Toy RSA: keys, encryption and signatures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Practical rules

Do not write your own cryptography for real systems. Use well-reviewed libraries and high-level protocols (TLS, SSH, WireGuard, libsodium). Almost all real-world breaks come from misuse (reused nonces, weak randomness, missing authentication), not from the mathematics.

  • Use authenticated encryption (AES-GCM, ChaCha20-Poly1305). Encryption without authentication allows tampering.
  • Use a cryptographically secure random number generator for keys and nonces, never a seeded general-purpose one like the demos above use.
  • Store passwords with a deliberately slow, salted password hash (Argon2, scrypt, bcrypt), not a bare SHA-256.
  • Prefer ephemeral key exchange for forward secrecy.
  • Plan for the future: large quantum computers would break RSA and classic DH. Standards for post-quantum key exchange (such as ML-KEM) already exist and are being added to TLS, often combined with X25519 in a hybrid.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main difference between a plain hash and an HMAC?

    Anyone can compute a plain hash of a message. An HMAC needs the shared secret key, so a valid tag proves the message came from a key holder and was not altered.
  2. 2. Why do real protocols combine public-key and symmetric cryptography?

    This is the hybrid approach: a slow key exchange or signature once per connection, then fast AES or ChaCha20 for the traffic.
  3. 3. In Diffie-Hellman, what does an eavesdropper who sees p, g, A and B need to solve to find the shared secret?

    To recover a secret exponent from g^a mod p the attacker must compute a discrete logarithm, which is infeasible for properly sized groups.
  4. 4. What does plain, unauthenticated Diffie-Hellman NOT protect against?

    DH does not tell you who you are talking to. An active attacker can run separate exchanges with each side, which is why real protocols sign the exchange.
  5. 5. Which key signs a message, and which key verifies the signature?

    Only the owner has the private key, so only the owner can create the signature. Everyone can check it with the public key.

Summary

  • Hashes give fixed-size fingerprints; HMAC adds a secret key to authenticate messages. Use SHA-256/SHA-3, not MD5 or SHA-1.
  • Symmetric ciphers (AES-GCM, ChaCha20-Poly1305) are fast; use AEAD modes and never reuse a nonce with the same key.
  • Diffie-Hellman (and X25519) creates a shared secret in public; ephemeral keys give forward secrecy, but authentication must be added separately.
  • Public-key cryptography (RSA, elliptic curves) enables key exchange and digital signatures; real systems combine it with symmetric ciphers.
  • Never roll your own crypto: use TLS, SSH or well-reviewed libraries.

Next, see all these pieces assembled in one protocol: TLS and HTTPS.