Cryptography for Networking: Ciphers, Key Exchange, Hashes, MACs and Post-Quantum Keys
The cryptographic building blocks that network security protocols combine: symmetric ciphers and AEAD, RSA, Diffie-Hellman and elliptic curves, ML-KEM and other post-quantum algorithms, key derivation and forward secrecy, randomness, nonces, hashes and MACs, run with OpenSSL in the lab.
kvi5hnuCode Sprout team member20 min readOn this page
Every protocol in the rest of Part 13 (IPsec, WireGuard, TLS, DNSSEC, DKIM) is built from the same small set of cryptographic tools. They differ in which tools they pick and how they combine them. This article covers the tools: what each one does, what it doesn't do, and how they fit together. The examples run with OpenSSL 3.5 in the course lab container, so every key, hash and error message below is real.
Cryptosystems: symmetric and public-key
A cipher turns readable plaintext into unreadable ciphertext under the control of a key, a string of bits. The same plaintext with a different key gives a completely different ciphertext. A cryptosystem is a cipher together with the rules for generating, distributing and using its keys.
- In a symmetric cryptosystem, the same secret key encrypts and decrypts. It's fast, but both sides need the key before they can talk, and getting it to them securely is the hard part.
- In an asymmetric or public-key cryptosystem, each party has a key pair. The public key can be given to anyone, and only the matching private key can undo what it does. Anyone can encrypt a message to you with your public key; only you can decrypt it. Used the other way round, you can sign with your private key, and anyone can verify with the public key. That gives authentication and nonrepudiation.
Public-key operations are thousands of times slower than symmetric ones per byte, so real protocols are hybrid:

A public-key step agrees on a fresh secret once per session, a key derivation function turns it into keys, and a fast symmetric cipher protects all the data.
Symmetric ciphers
Symmetric ciphers are either block ciphers, which transform fixed-size blocks (128 bits for AES), or stream ciphers, which generate a stream of pseudorandom bits to XOR with the data. (XOR, exclusive or, gives a 1 bit where the two input bits differ; XORing the same stream twice gives back the original.)
- DES (1977) used 56-bit keys, small enough to search exhaustively by the late 1990s. Triple DES (3DES) applied it three times. Both are now obsolete.
- AES (Advanced Encryption Standard; FIPS 197, 2001, a US Federal Information Processing Standard), originally called Rijndael, has 128-bit blocks and 128-, 192- or 256-bit keys. It's the default almost everywhere, and modern CPUs have instructions for it.
- ChaCha20 is a fast stream cipher designed for software, used where CPUs lack AES instructions (many phones and small devices).
Modes, and why encryption alone isn't enough
A block cipher handles one block; a mode says how to use it for a whole message:
- CBC (cipher block chaining) XORs each plaintext block with the previous ciphertext block before encrypting, starting with a random initialization vector (IV). It's inherently serial, and its padding has caused a long list of attacks in TLS.
- CTR (counter) encrypts a nonce plus a counter to produce a keystream, then XORs it with the plaintext. That turns a block cipher into a stream cipher, and every block can be processed in parallel.
Stream-cipher-like modes have a dangerous property: flipping a bit of the ciphertext flips the same bit of the plaintext. An attacker who knows the message format can change it without knowing the key:
AES-CTR, attacker flipped ciphertext bits, receiver decrypts: AMOUNT=9900 TO=ACCT-1234
AES-GCM ciphertext: 40 bytes = 24 plaintext + 16 tag
AES-GCM, same bit flips, receiver decrypts: rejected (InvalidTag)
The attacker knows the plaintext says 0100 at a known position and wants 9900. Ciphertext = plaintext ⊕ keystream, so XORing a ciphertext byte with (old ⊕ new) changes the decrypted byte from old to new. For the first byte, '0' is 0x30 and '9' is 0x39, so the attacker XORs in 0x30 ⊕ 0x39 = 0x09. For the second, '1' (0x31) ⊕ '9' (0x39) = 0x08. With plain AES-CTR, the attacker XORed 01 ⊕ 99 into those two ciphertext bytes this way, and the receiver decrypted AMOUNT=9900. That's the same attack as the router tampering in article 78, but against encrypted data. Encryption gives confidentiality, not integrity.
The fix is authenticated encryption with associated data (AEAD, RFC 5116). An AEAD cipher encrypts and computes an authentication tag in one operation, and decryption fails unless the tag checks. It can also authenticate associated data that isn't encrypted, such as a packet header. AES-GCM (Galois/Counter Mode) and ChaCha20-Poly1305 (RFC 8439) are the two AEADs used by TLS 1.3, QUIC, IPsec and WireGuard. AES-CCM (counter mode with CBC-MAC) is common in constrained devices. Above, the same bit flips against AES-GCM produced InvalidTag: the receiver rejected the message.
Measured on one core of the lab machine, both are very fast:
AES-128-GCM 8.41 GB/s (16 KB blocks, one core)
ChaCha20-Poly1305 2.38 GB/s (16 KB blocks, one core)
RSA
RSA (1977) bases its security on the difficulty of factoring a large number into its two prime factors. Key generation:
- Pick two large random primes
pandq, and compute the modulusn = p·q. - Compute
φ(n) = (p − 1)(q − 1), the number of integers belownthat share no factor with it. - Pick a public exponent
e(almost always 65,537), and compute the private exponentd = e⁻¹ mod φ(n).
The public key is (n, e); the private key is (n, d). Encryption is c = mᵉ mod n and decryption is m = cᵈ mod n. A signature runs it the other way: s = mᵈ mod n, which anyone can check with sᵉ mod n = m. With toy numbers:
n=3233 phi=3120 e=17 d=2753
encrypt m=65: c=m^e mod n=2790 decrypt c^d mod n=65
sign m=65: s=m^d mod n=588 verify s^e mod n=65
Here p = 61 and q = 53, so n = 61 × 53 = 3233 and φ(n) = 60 × 52 = 3120. The private exponent 2753 works because 17 × 2753 = 46,801 = 15 × 3120 + 1, so it is 1 more than a multiple of 3120. Encrypting m = 65 gives 65¹⁷ mod 3233 = 2790, and 2790²⁷⁵³ mod 3233 brings back 65.
Anyone who could factor 3233 into 61 × 53 could compute d. For a 2048-bit modulus, no known classical method can. Real RSA never encrypts or signs a raw message: it applies padding schemes (OAEP for encryption, PSS or PKCS #1 v1.5 for signatures; PKCS are the Public-Key Cryptography Standards) and signs a hash of the message. Here's a real 2048-bit signature, checked against the original and a modified message:
signature: 256 bytes
Verified OK
Verification failure
RSA patents expired in 2000, and RSA is still common for certificate signatures. But it's slow to sign, and key sizes must grow quickly for more security (3072 bits for a 128-bit security level).
Diffie-Hellman key agreement
Two parties often need a shared secret without having one to start with, and over a network Eve is listening to. Diffie-Hellman (1976; Merkle independently developed related ideas) solves this.
Both sides agree on public values: a large prime p and a generator g. The client picks a secret a and sends A = gᵃ mod p; the server picks a secret b and sends B = gᵇ mod p. Each then computes Bᵃ = Aᵇ = gᵃᵇ mod p. With toy numbers:
public: p=23 g=5 client sends A=g^a mod p=8 server sends B=g^b mod p=19
client computes B^a mod p = 2 server computes A^b mod p = 2
The secrets were a = 6 and b = 15. The client sends 5⁶ mod 23 = 15,625 mod 23 = 8, and the server sends 5¹⁵ mod 23 = 19. The client computes 19⁶ mod 23 = 2, and the server 8¹⁵ mod 23 = 2: the same value, without either secret crossing the network. Eve sees p, g, A = 8 and B = 19. To find the secret, Eve would have to recover a or b from them, the discrete logarithm problem, which is infeasible at real sizes.
But Diffie-Hellman alone doesn't tell either side who they agreed with:

Mallory can run one exchange with each side and relay everything, reading it in between. The defense is to authenticate the exchanged values, for example by signing them with a key the other side already trusts. That idea, the Station-to-Station protocol, is the core of TLS 1.3 and IKEv2 handshakes.
Elliptic curve cryptography
Elliptic curve cryptography (ECC) does the same kind of math in the group of points on an elliptic curve, where the discrete logarithm problem is much harder for its size. A 256-bit curve key gives about the same security as a 3072-bit RSA key. Smaller keys mean smaller messages and faster operations.
- ECDH and X25519 (RFC 7748) do Diffie-Hellman on curves. X25519 is the most used key exchange on the Internet.
- ECDSA (Elliptic Curve Digital Signature Algorithm; on the NIST curve P-256, among others; NIST is the US National Institute of Standards and Technology) and Ed25519 (RFC 8032) are signature algorithms.
A real X25519 exchange: each side's public key is 32 bytes, and both derive the same 32-byte secret (shown here by its SHA-256 hash, since the secret itself shouldn't be printed):
client public key: 32 bytes
client's secret: c91f73ac9c63c0e5… (SHA-256 of the 32-byte shared secret)
server's secret: c91f73ac9c63c0e5…
Patents slowed ECC's adoption for years, but X25519, ECDSA and Ed25519 are now standard in TLS, SSH, IPsec, WireGuard and DNSSEC.
Post-quantum cryptography
A large enough quantum computer running Shor's algorithm would factor RSA moduli and solve elliptic-curve discrete logarithms efficiently, breaking every algorithm above except the symmetric ones. Nobody has such a machine yet. But traffic recorded today can be decrypted later, if it's ever built (harvest now, decrypt later), so key exchange is being replaced first.
NIST published the first post-quantum standards in August 2024:
- ML-KEM (FIPS 203, from CRYSTALS-Kyber), a key encapsulation mechanism based on lattice problems. Instead of both sides contributing a value as in Diffie-Hellman, one side publishes an encapsulation key, the other uses it to generate a random secret and a ciphertext, and only the holder of the decapsulation key can recover the secret from the ciphertext.
- ML-DSA (FIPS 204, from CRYSTALS-Dilithium) and SLH-DSA (FIPS 205, from SPHINCS+), signature algorithms. NIST also selected HQC in 2025 as a backup KEM based on different mathematics.
A real ML-KEM-768 exchange in the lab:
encapsulation key (public): 1206 bytes DER
ciphertext sent back: 1088 bytes
shared secret: 32 bytes
decapsulated secret matches: yes
The trade-off is size. The encapsulation key is 1,184 bytes (the 1,206 bytes printed include a 22-byte DER wrapper; DER, Distinguished Encoding Rules, is the standard binary format for keys and certificates), and the ciphertext 1,088 bytes, against 32 bytes each for X25519. The secret is the same 32 bytes. ML-DSA-65 signatures are 3,309 bytes, against 64 for Ed25519.
Because the new algorithms are young, protocols deploy them as hybrids with an established algorithm, so that the result is secure if either part is. The TLS group X25519MLKEM768 concatenates an X25519 share and an ML-KEM-768 share. It was standardized in 2026 (RFC 10024), is the default in current browsers and in OpenSSL 3.5, and protects most human web traffic to large providers. That's why the ClientHello in article 78 was 1,570 bytes. Post-quantum signatures for certificates are further behind, because they make every handshake much larger.
How fast are they?
Measured on one core of the lab machine:

RSA-2048 sign 3,166 per second
RSA-2048 verify 126,424 per second
ECDSA P-256 sign 99,588 per second
ECDSA P-256 verify 32,937 per second
X25519 key agreement 43,082 per second
Ed25519 sign 65,874 per second
Ed25519 verify 26,916 per second
ML-KEM-768 encapsulate 67,885 per second
ML-KEM-768 decapsulate 45,018 per second
ML-DSA-65 sign 2,030 per second
ML-DSA-65 verify 11,830 per second
ML-KEM is about as fast as X25519, so the cost of post-quantum key exchange is bytes, not CPU. Signing is the expensive operation for RSA and ML-DSA, which matters for busy servers. RSA verification is very fast, which is one reason RSA certificates remain common.
Key derivation and forward secrecy
A key exchange produces one shared secret. A protocol needs several keys: one per direction, separate keys for handshake and data, sometimes IVs. A key derivation function (KDF) stretches one secret into as many independent keys as needed. HKDF (RFC 5869), built on HMAC (a hash-based MAC, explained below), is the standard choice: an extract step condenses the input into a pseudorandom key, and an expand step produces keys bound to a label:
client write key: 16c14487d5c7eea937311424cf2159db…
server write key: ece4c4911a4fe514ab81777ac34f3206…
The same secret and different labels give unrelated keys. TLS 1.3 derives all its keys this way.
Forward secrecy (often called perfect forward secrecy, PFS) means that compromising a long-term key, such as a server's certificate private key, doesn't expose past sessions. It comes from using ephemeral key exchange: a fresh Diffie-Hellman or KEM key pair for each session, discarded afterwards. Old TLS with RSA key transport (the client encrypted the session key to the server's long-term RSA key) didn't have it: anyone who later stole that key could decrypt every recorded session. TLS 1.3 removed RSA key transport for that reason. Rekeying during long sessions, as IPsec, TLS 1.3 and WireGuard do, limits how much data any one key protects.
Randomness
Keys, nonces and IVs must be unpredictable. Computers are deterministic, so they use pseudorandom number generators (PRNGs): algorithms that expand a small seed into a long sequence that looks random. Ordinary PRNGs, fine for games and simulations, are predictable once you see a few outputs. Here's the classic linear congruential generator:
observed outputs: [770110374, 32932327, 288612756]
attacker predicts next: 776623165 actual next: 776623165
Three outputs and the published constants are enough to predict the fourth exactly. Cryptography needs a cryptographically secure PRNG (CSPRNG), built from a pseudorandom function (PRF), whose output can't be told apart from true randomness or predicted without knowing its internal state, and which is seeded from real entropy (hardware noise, interrupt timing). On Linux, that's getrandom() and /dev/urandom. RFC 4086 covers randomness requirements for security. Bad randomness has broken real systems: duplicate RSA keys from embedded devices that generated them at boot before collecting enough entropy, and ECDSA keys leaked from reused signing nonces.
Nonces and salts
A nonce is a value used only once. In a challenge-response login, the server sends a fresh random nonce and the client must include it in its answer, so a recorded answer is useless later: the nonce proves freshness and defeats replay. AEAD ciphers also need a unique nonce per message under the same key; reusing a GCM nonce leaks plaintext and lets an attacker forge tags.
A salt is a random value stored alongside a password hash. It makes each user's hash different even for identical passwords, so an attacker can't precompute one table of hashes for common passwords and apply it to everyone. Early Unix systems used a 12-bit salt, 4,096 variations, which faster hardware made inadequate. Modern password storage uses long salts with deliberately slow functions such as bcrypt, scrypt or Argon2 (RFC 9106).
Cryptographic hash functions
Network protocols already use checksums and CRCs (cyclic redundancy checks, as in Ethernet frames) to catch accidental errors, but anyone can recompute those. A cryptographic hash function maps any input to a fixed-size digest (a fingerprint) and must resist three things:
- Preimage resistance: given a digest, you can't find an input that produces it.
- Second-preimage resistance: given one input, you can't find a different input with the same digest.
- Collision resistance: you can't find any two different inputs with the same digest.
A one-character change produces an unrelated digest:
msg.txt sha256 151c7a732195c749bd7c96191708884d6b07b905ec925f06e0322805004fd4ce
bad.txt sha256 494408f323c5494c9c78dc47ff792478659e7e06090525c7b34694dc87d1fdb0
msg.txt sha3-256 7922c7bb69d1c66d3b1cfba0a517e32bd9b56cb732d79691b070c5d79368cccb
bits that differ: 116 of 256
About half of the 256 bits changed, as they should.
- MD5 (128 bits) is broken: practical collisions were shown in 2004, and forged certificates based on them followed.
- SHA-1 (Secure Hash Algorithm 1, 160 bits) is broken for collisions: a real collision was published in 2017. It's no longer accepted for signatures.
- SHA-2 (SHA-224, -256, -384 and -512) is the current workhorse.
- SHA-3 (FIPS 202, 2015), from the Keccak design, uses a different internal structure (a sponge rather than Merkle-Damgård) as a hedge against attacks on SHA-2.
Message authentication codes
A message authentication code (MAC; sometimes called a MIC, message integrity code; unrelated to MAC addresses) is a keyed checksum. Only someone with the key can compute or check it, so a valid MAC proves the message is unmodified and came from a key holder. A secure MAC resists forgery: without the key, you can't produce a valid MAC for any new message.
HMAC (RFC 2104) builds a MAC from any hash: HMAC(K, M) = H((K ⊕ opad) ‖ H((K ⊕ ipad) ‖ M)), where ipad and opad are fixed pad bytes (0x36 and 0x5C). The nested structure matters: the naive H(K ‖ M) is broken for SHA-2, because an attacker can append data to a message and compute the new digest without the key (a length-extension attack). The same message with two keys that differ in one byte:
key A: D818F28323C1DB721740D264B765398869BE8CC60BD33F763C0B059D8B0A6A34
key B: 825504D9C75E3AA81F7A74572BD0B429ED8916DAFCFD3017FD481098526BD580
CMAC (RFC 4493 for AES) builds a MAC from a block cipher, and GMAC is GCM used for authentication only. In AEAD ciphers the tag plays the MAC's role, so no separate MAC is needed.
A MAC can't provide nonrepudiation: both sides have the key, so either could have produced it. Only signatures can.
Cipher suites
A protocol has to agree on the whole combination: key exchange, authentication, cipher and mode, MAC or AEAD, hash or PRF, and key sizes. That combination is a cipher suite (or cryptographic suite). TLS 1.2 suites named everything at once, as in TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: ephemeral elliptic-curve Diffie-Hellman (ECDHE) key exchange, RSA signatures, AES-128 in GCM mode, and SHA-256 for key derivation. TLS 1.3 negotiates the key exchange group and signature algorithm separately, so its suites name only the AEAD and hash: TLS_AES_128_GCM_SHA256, TLS_AES_256_GCM_SHA384 and TLS_CHACHA20_POLY1305_SHA256. IKEv2 negotiates each piece as a separate transform. A NULL cipher (RFC 2410) also exists for cases that need integrity but not confidentiality.
Common questions
Is AES-256 more secure than AES-128?
Both are far beyond brute force with classical computers. AES-256 adds a margin against quantum search (Grover's algorithm roughly halves the effective key length), which is why it's chosen for long-term secrets. AES-128 is still the common default because it's faster.
Why not just encrypt with RSA directly?
RSA can only encrypt a message smaller than its modulus, it's very slow, and it needs careful padding. RSA key transport also gives no forward secrecy. Protocols use public-key operations only to agree on keys and to sign.
If SHA-256 is fine, why does SHA-3 exist?
As insurance. SHA-2 shares its general design with SHA-1, which was broken. SHA-3's sponge construction is unrelated, so a breakthrough against one is unlikely to break the other. SHA-3 also resists length extension by design.
When will quantum computers break RSA?
Nobody knows. Estimates range from about a decade to never. Key exchange is moving first because of harvest-now-decrypt-later. NIST plans to deprecate RSA and elliptic-curve algorithms at the 112-bit security level after 2030 and disallow all of them after 2035.
What's the difference between a hash and a MAC?
Anyone can compute a hash, so it only detects changes if the hash itself arrives over a trusted path (for example, a checksum published on a website you trust). A MAC needs a key, so it protects even when the attacker can change both the message and the MAC.
Is a "nonce" the same as an IV?
Closely related. An IV is the starting value a mode needs. Some modes, like CBC, require it to be unpredictable; others, like GCM, only require it never to repeat under one key, which is what "nonce" emphasizes.
Summary
- Symmetric ciphers (AES, ChaCha20) are fast but need a shared key. Public-key systems use key pairs for encryption and signatures but are slow. Real protocols are hybrid.
- Encryption without authentication is malleable: flipping AES-CTR ciphertext bits changed
0100to9900. AEAD (AES-GCM, ChaCha20-Poly1305) rejected the same change. - RSA relies on factoring; Diffie-Hellman and ECC on discrete logarithms. Unauthenticated Diffie-Hellman is open to a man in the middle, so exchanged values must be signed or otherwise authenticated.
- ML-KEM (FIPS 203) is a post-quantum KEM about as fast as X25519 but with 1,184-byte keys and 1,088-byte ciphertexts. X25519MLKEM768 hybrids are now the default in TLS.
- HKDF derives many keys from one secret. Ephemeral key exchange gives forward secrecy.
- Cryptography needs a CSPRNG: an ordinary LCG was predicted from three outputs. Nonces prove freshness; salts defeat precomputed password tables.
- Hashes (SHA-2, SHA-3) give fingerprints; MD5 and SHA-1 are broken. MACs (HMAC, CMAC, GMAC) need a key and authenticate. Only signatures give nonrepudiation.
- A cipher suite names the combination a protocol uses.
Practice questions
1. Using the toy RSA key above (n = 3233, e = 17, d = 2753), what is the ciphertext for m = 42?
Answer
c = 42¹⁷ mod 3233 = 2557. Decrypting with 2557²⁷⁵³ mod 3233 gives 42 back. (Python: pow(42, 17, 3233).)
2. With p = 23 and g = 5, the client's secret is a = 4 and the server's is b = 9. What values do they exchange, and what is the shared secret?
Answer
A = 5⁴ mod 23 = 4, B = 5⁹ mod 23 = 11. The client computes 11⁴ mod 23 = 13 and the server 4⁹ mod 23 = 13. The shared secret is 13.
3. A protocol uses AES-CBC for encryption and appends SHA-256(message) for integrity. What's wrong?
Answer
An unkeyed hash gives no integrity against an attacker: Mallory can change the message and compute a new SHA-256 to match. It needs a MAC (with a key) or, better, an AEAD cipher. CBC with separate MACs has also had many subtle attacks, which is why modern protocols use AEAD.
4. A server's RSA private key is stolen. Which recorded sessions can the thief decrypt with TLS 1.2 using RSA key transport, and with TLS 1.3?
Answer
With RSA key transport, every recorded session that used that key, because each session key was encrypted to it. With TLS 1.3, none: session keys came from ephemeral (EC)DHE or ML-KEM exchanges, and the RSA key only signed the handshake. The thief can impersonate the server in future, though, until the certificate is revoked or expires.
5. Why do hybrid post-quantum key exchanges combine X25519 with ML-KEM instead of using ML-KEM alone?
Answer
ML-KEM is new, and if a flaw is found in its mathematics or in an implementation, X25519 still protects the session. If quantum computers break X25519, ML-KEM still protects it. The combined secret is secure as long as either component is. The cost is about 32 extra bytes on top of ML-KEM's 1,184-byte key share.
6. An AES-GCM implementation accidentally uses the same nonce for two messages under one key. What can an attacker do?
Answer
XORing the two ciphertexts gives the XOR of the two plaintexts, which often reveals both. Worse, the attacker can recover the GHASH authentication key (GHASH is the keyed hash inside GCM that computes the tag) and forge valid tags for messages of their choice. Nonce uniqueness is essential for GCM, which is why protocols derive nonces from sequence numbers.
Previous: Network Security Principles and the Threats to Network Communication
Next: Certificates and PKI: X.509, Certificate Authorities, Validation, Revocation and Transparency

More in TCP/IP Course
Quiz: TCP/IP Delicate Details
Twenty-five questions on the details that catch out experienced engineers: sequence numbers for SYN and FIN, TIME_WAIT versus tcp_fin_timeout, Karn's algorithm, socket buffer doubling, even and odd ephemeral ports, IPv6 checksums and fragmentation, negative DNS caching, and capture filter traps.
Quiz: TCP/IP Interview Questions
Thirty-three networking questions of the kind asked in developer, SRE and network engineering interviews: what happens when you load a URL, TCP versus UDP, handshakes, closing and TIME_WAIT, subnetting, NAT, DNS, MTU problems, congestion, TLS and QUIC, and debugging slow or failing connections.
Quiz: TCP/IP Course Final Exam (All Parts)
The final exam for the TCP/IP course: thirty questions across all fourteen parts, from packets and addressing through Ethernet, ARP, IP, DHCP, NAT, ICMP, UDP, DNS, TCP connections, reliability, congestion control, security, QUIC and troubleshooting.
Quiz: Modern Transports and Troubleshooting (TCP/IP Part 14)
Review modern transports and troubleshooting: QUIC packets, handshakes, 0-RTT, streams and connection migration, HTTP/3, Multipath TCP, SCTP multihoming, and a layered method for diagnosing real network faults.
Discussion
Sign in to ask a question or share what you learned.