Crypto 101 (2024-02-26) - jlxip's blog
Revised and corrected on 2026-09-23. Original version here.
1. Introduction
Ogres, onions, cakes, and operating systems all have layers. When learning a layered subject, you start at the top and work your way down. For cryptography, there are four layers:
- Classes: groups of algorithms that serve a similar purpose
- Mechanisms: the actual algorithms within those groups
- The computational problems and assumptions on which their security relies
- The maths behind it all
In order to understand cryptography and use it correctly, you start at the top. It is not until you understand it fully that you can go down the stack. Designing a cryptosystem requires fully understanding the first two layers.
I've been studying cryptography for many years on my own, and I worked in the crypto department of a cybersecurity firm from mid-2023 to early 2025. Many cybersecurity professionals outside of this field have a very limited understanding of the subject, so my motivation behind this is to give all these people a good starting point. This post also aims to raise awareness among readers (that's you) and highlight the importance of studying the subject to avoid committing crypto-oopsies; they are surprisingly common.
This post will cover the different classes of cryptographic algorithms. It will cover applied cryptography and useful things to know. No modular exponentiation, Caesar's cipher, or Fermat's little theorem. Once you understand these classes, you can start learning the rest.
2. The Basics
A channel is a means of data transmission. A secure channel (SC) is a channel that is resistant to spying and tampering. There are three desirable properties that we may want an SC to have. In most situations, all of them are sought after. These are:
- Confidentiality: guarantees that nobody who intercepts the messages can read them. A channel that offers only confidentiality is called a confidential channel.
- Integrity: guarantees that unauthorized changes to a message can be detected. A channel with integrity protection.
- Authenticity: guarantees that the message was really sent by the claimed sender. Authentic channel.
Authenticity is the property of being genuine; authentication is the process of verifying a claimed identity or origin. Do not confuse these with authorization, which determines what a party is allowed to do. Message authenticity implies integrity, but integrity alone does not identify the sender!
Most of the time, an SC has two ends: Alice and Bob. Secure channels can be engineered to have more parties (think of encrypted group chats), but these mechanisms are very specific, can often be avoided, and will not be covered in this post.
There are two superclasses of key-based cryptographic mechanisms: symmetric and asymmetric. They refer to whether both parties use the same secret key (symmetric) or different, mathematically related public and private keys (asymmetric).
A cryptographic primitive is a basic algorithm used as a building block for other cryptographic mechanisms. A cryptographic construction is a mechanism that uses one or more cryptographic primitives, and may perform additional calculations to achieve its purpose. This line is somewhat fuzzy, but it helps in understanding how each algorithm works.
For each algorithm class, examples will be given, including old broken mechanisms and modern not-yet-broken ones. A person who dares to do crypto is cursed to stay up to date, as new attacks are discovered on a regular basis: assume that by the time you read this, all these algorithms have been broken and seek updated information. Good sources of information are governments' cryptographic mechanism recommendations, published by their corresponding agencies:
- The USA has NIST's, balanced
- Europe has SOG-IS', too conservative, in my opinion
- Germany has BSI's, very comprehensive
- Spain has CCN's, more interesting than the others
Governments recommend standardized algorithms. They are studied and clearly defined. Outside of the standards, you're on your own: some may be good (XChaCha20) and some may be completely trivial to break. I would advise staying away from non-standard mechanisms unless you know what you're doing and don't intend to pass any certifications.
Knowing which algorithms and parameterizations are secure is not enough. Anyone who uses crypto must know about what I've begun calling "cryptocohesion": the correct ways of combining the algorithms in order to build a secure cryptosystem. While there are general practices that are good to follow, such as not using the same key in a cipher and a MAC, most require specific knowledge of each algorithm.
3. Symmetric Mechanisms
Symmetric mechanisms transform data. They may have any number of inputs and outputs. They reshape the data directly, in a non-interactive fashion from start to finish.
3.1. Symmetric Cipher
A symmetric key is a short sequence of bits used as if it were a physical key. A symmetric cipher encrypts or decrypts bytes using a shared secret key; thus, it offers confidentiality. Security comes from the difficulty of:
- Recovering information about the plaintext without the key
- Guessing the key
Inputs:
- The message, also called "plaintext"
- The key
- Depending on the algorithm, a nonce (a number only used once) or IV (initialization vector). Their requirements depend on the construction: some algorithms require a unique nonce for each message under the same key, so counters can work; others require an unpredictable IV. Do note: random generation does not guarantee uniqueness
Output: the encrypted message, also called "ciphertext".
Symmetric ciphers can be classified into two groups, depending on how they process the message:
- Stream ciphers will produce a stream of seemingly random bits that are combined (XORed) with the message, bit by bit. Examples are RC4 (broken) and ChaCha20 (not).
- Block ciphers encrypt fixed-length blocks using a key. Examples include DES (broken) and AES (not). To encrypt longer messages, block ciphers are used with a "mode of operation". Examples are ECB (insecure) and CBC (needs authentication; please don't use it on its own and keep reading).
3.2. Hash
A cryptographic hash function transforms a message of arbitrary length into a fixed-length digest, often between 256 and 512 bits. They are one-way functions. They can be used to check integrity against a trusted digest. Security comes from the difficulty of:
- Finding an input that produces a given output (preimage)
- Finding another input with the same hash as a given message (second preimage)
- Finding any two inputs that produce the same output (collision)
Inputs:
- The message
- Some hash functions support a "customization string" or "personalization string". This separates different uses of the function; for instance, a secure application "CryptoChat" might set it to "CryptoChat/v1/key_fingerprint" when computing the fingerprint of a public key. The same message then produces different digests in different contexts
Output: the hashed data, also known as a "digest".
Examples are MD5 (broken) and SHA-3 (not).
3.3. XOF
Extendable-output functions (XOFs) are variable-length hash functions. The output can be extended to any desired length. Usually, a 1024-bit output is the first 1024 bits of a 1025-bit output for the same input.
Inputs:
- The message
- The length of the output
- Possibly, additional data
Output: the variable-sized digest.
Examples are SHAKE256 and cSHAKE256 (both good).
3.4. MAC
A MAC, or Message Authentication Code, is like a signed hash, called an "authentication tag". Therefore, they offer authenticity and integrity. The tag is computed from a message and a shared secret key. For verification, it's common to calculate the tag again and compare it with the received one. Unlike a digital signature, anyone who can verify the MAC using the shared key can also generate it.
Inputs:
- The message
- A symmetric key
- Possibly, additional data
Output: the tag.
Examples are KMAC (good) and CBC-MAC (dangerous).
3.5. AEAD
AE means Authenticated Encryption: encryption that provides confidentiality, integrity, and authenticity. Many constructions combine a symmetric cipher and a MAC. AEAD, or Authenticated Encryption with Associated Data, also protects the integrity and authenticity of additional data without encrypting it.
AEAD is the pinnacle of general-purpose symmetric encryption, and it's what everyone uses (or should be using). It provides the three properties for messages under a shared secret key, but remember: the channel is no more secure than that key and the way it was established and protected. The protocol must still bind the key to the intended parties, follow the algorithm's nonce requirements, and prevent replayed messages from being accepted. Choosing an established AEAD guarantees safe cryptocohesion.
Inputs:
- The plaintext
- A symmetric key
- A nonce
- Additional data
Outputs:
- The ciphertext
- The authentication tag
Some interfaces return the ciphertext and authentication tag together; others return them separately. Always follow the format specified by the algorithm or protocol. Authenticated decryption either returns the plaintext or reports a verification failure; unverified plaintext must never be used!
Good examples are ChaCha20-Poly1305 and AES-GCM. Any combination of cipher and MAC you come up with is very likely insecure.
3.6. KDF
Key Derivation Functions (KDFs) derive one or more keys from an input. These generated keys, also called DKM (derived keying material), can then be used in other algorithms. While KDFs do not directly offer any of the mentioned cryptoproperties, they are central to modern cryptosystems, because a key should not be used for two different purposes. Do note that a KDF does not create entropy that was missing from its input. Security comes from the difficulty of:
- Recovering the secret input from the derived keys
- Predicting one derived key from another
Some KDFs are designed for passwords. These are intentionally slow KDFs used for deriving keys from user-chosen passwords, which often have little entropy. Their computational and/or memory demands slow down brute-force attacks.
Inputs:
- The master key, passphrase, or shared secret used as input, depending on the type of KDF
- A salt or nonce, used to produce different keys
- Often, context information to separate different uses of the derived keys
Output: the derived keying material.
Examples include HKDF (good), Argon2 (great, passphrase-oriented), and any trivial hash of concatenations you come up with (very likely insecure).
3.7. KW
KW stands for Key Wrapping. A KW algorithm is a cryptographic construction that symmetrically encapsulates keys. These algorithms are used for protecting keys in untrusted storage, or for transmitting them over the wire. In the latter case, if a random key is acceptable, KEMs are much better (explained later). KWs offer confidentiality and integrity.
Inputs:
- The key to be protected
- Another key to protect the first, called a "key-encryption key" (KEK)
Output: the encrypted key.
Examples are AES-KW (good) and TKW (bad).
4. Asymmetric Mechanisms
Asymmetric mechanisms have two keys: a public key and a private key. This is called a "keypair". The two keys are mathematically related. Security often comes from the difficulty of recovering the private key from the public key.
4.1. Asymmetric Encryption
In an asymmetric encryption scheme, the public key is used to encrypt a message, and the private key is used to decrypt it. Therefore, this offers confidentiality. Direct asymmetric encryption handles only short messages, so the few cryptosystems that do this typically use it to protect a symmetric key; the actual messages are encrypted symmetrically. The preferred method is to use a KEM or an authenticated key exchange.
Inputs for encryption:
- The message
- The public key of the recipient
- Fresh randomness, generally supplied internally
The output is the ciphertext.
Inputs for decryption:
- The ciphertext
- The private key
The output is the plaintext.
Examples are ElGamal (requires care) and RSA-OAEP (ok, but dangerous if not used correctly).
4.2. Digital Signatures
In a digital signature algorithm, the private key signs a message and the public key verifies it. This offers message authenticity and integrity. Digital signatures are used everywhere and there are many algorithms for signing.
Inputs for signing:
- The message
- The private key
- Possibly fresh randomness, depending on the algorithm and generally supplied internally
The output is the signature, kind of like a MAC.
Inputs for verification:
- The message
- Its signature
- The public key
The output is binary: pass or fail.
Examples are Ed25519 (good, but not post-quantum) and DSA (obsolete for new signatures). For post-quantum security, keep reading.
4.3. KEX
KEX is short for Key Exchange, one of the most important classes of modern cryptography. A Diffie-Hellman-style key exchange generates a shared secret from two keypairs. Alice has her private key (a) and Bob's public key (B). Bob has his private key (b) and Alice's public key (A). Combining 'a' and 'B' gives the exact same result as combining 'A' and 'b'. Both parties, with completely different numbers, reach the same result.
The tricky point is authenticating the public keys and the exchange: otherwise, an active attacker can impersonate either party. The raw shared secret must not be used directly as an encryption key; instead, actual keys must be derived with a KDF.
A Diffie-Hellman key exchange is called "ephemeral" when fresh, temporary keypairs are generated for a session. An authenticated ephemeral exchange provides another cryptographic property: PFS, or Perfect Forward Secrecy. PFS guarantees that a later compromise of long-term authentication keys does not reveal the keys of past sessions, provided the temporary private keys and session secrets have been erased when no longer needed. The protection comes from using and discarding independent secrets, not just from never sending the session key. Unfortunately, it cannot protect against a future break of the underlying algorithms.
Inputs:
- My private key
- The other party's public key (hopefully authenticated)
Output: the shared secret.
Examples are X25519 (good) and finite-field Diffie-Hellman (also secure, but requires larger keys for comparable security).
Give KEX a try in the real world!4.4. KEM
KEM is short for Key Encapsulation Mechanism. It establishes a shared secret using asymmetric cryptography. The sender uses the recipient's public key to generate both a shared secret and an encapsulation. Only the encapsulation is sent; the recipient uses their private key to recover the same secret. Unlike general-purpose asymmetric encryption, the sender does not supply an arbitrary message or a previously chosen symmetric key.
Inputs for encapsulation:
- The other party's public key
- Fresh randomness, generally supplied internally
Outputs:
- The shared secret, kept locally and used to derive keys
- The encapsulation, also called the KEM ciphertext, sent to the recipient
For decapsulation, the recipient supplies the encapsulation and their private key. The output is the shared secret.
Examples are DHKEM using X25519 (classical) and ML-KEM (post-quantum).
5. RNG
RNG is short for Random Number Generator. In cryptography, we use CSPRNGs, or Cryptographically Secure Pseudorandom Number Generators. When properly seeded, these algorithms can produce large quantities of data that is computationally indistinguishable from truly random data, sometimes terabytes of it. Security comes from the difficulty of:
- Recovering the seed from the output
- Predicting an unseen output bit significantly better than chance
At best, a cryptosystem can only be as secure as the randomness used to generate its keys. If this random data was not generated correctly, then security collapses. As an example, AES-256 offers at most 256 bits of classical security, and a 256-bit key generated from a low-entropy seed will not provide that strength.
Choosing a decent CSPRNG is important, but more so is gathering good entropy for a good seed. This task is very difficult. Deterministic computation alone cannot create entropy. Flipping a coin is often "random enough", since predicting its outcome is difficult. Many CPUs include hardware entropy sources (TRNGs), although it is hard to confirm whether they are compromised. It is always wise to mix entropy sources into a pool.
Randomness can also be gathered from external physical events. Computers can do this with time measurements: measuring unpredictable timing variations (jitter) between clocks can provide entropy. Mixing the extremely accurate CPU clock with the slow and imprecise human brain also provides entropy. The duration, speed, and acceleration of mouse movements and the time between keypresses can be sources of entropy, though these measurements are not necessarily independent. All this individual entropy is thrown into the pool, from which the CSPRNG is seeded. Modern operating systems provide this kind of infrastructure.
Estimating entropy accurately is difficult and most cryptographic certifications are very picky about what they allow.
Do not use /dev/random and /dev/urandom. I recommend reseeding with fresh entropy per key generation. Use an NPTRNG that meets NTG.1. People who know more about this than I do have recommended CPU Jitter to me.
Fun entropy
Examples of RNGs are HMAC_DRBG (great CSPRNG), Mersenne Twister (PRNG, not a CSPRNG, must never be used for crypto), and Dual_EC_DRBG (intentionally broken and introduced into NIST's SP800-90 standard by the NSA in 2006).
6. Additional Notes
6.1. Side Channels
Even if your algorithm choice is top-notch, your parameters are well chosen, your implementation is free of bugs, and your operating system is 100% secure, you're not safe.
Each time a CPU accesses memory or performs a jump in the code, it leaves a footprint. This footprint may be in the form of very minor timing differences or power consumption fluctuations. Accurately measuring these phenomena can reveal keys.
Good cryptographic implementations consider this and use constant-time code: branches, memory access patterns, and the timing of individual operations must not depend on secret data. For example, a lookup table indexed by a secret can leak information.
However, time is not the only side channel. Electromagnetic emissions and power consumption must also be considered. Mitigating these leaks may require software and hardware countermeasures. A sensitive enough antenna near a chip can pick up its emissions. With enough samples, statistical analysis may reveal secrets. A good principle for mitigating side-channel attacks is limiting the number of samples that can be gathered under the same key; for instance, by regularly changing the keys.
6.2. Post-Quantum Cryptography
The increasing capabilities of quantum computers have raised questions about the long-term security of our cryptography. A lot of effort is now being put into developing and deploying quantum-resistant crypto. In August 2024, NIST published its first three post-quantum cryptography standards: ML-KEM, ML-DSA and SLH-DSA.
This is an awkward situation. We do not trust our current RSA and elliptic-curve algorithms against sufficiently powerful quantum computers, but the PQ replacements have a shorter track record. This is why we do "hybridization": a mix of a classical mechanism and a PQ one. Recommended for hybrid key establishment: CatKDF. In a correctly constructed hybrid key establishment scheme, the shared secret remains secure as long as at least one component remains secure, provided everything else (authentication and such) is secure too, of course.
6.3. Secure Channel Genesis
An authenticated channel cannot be constructed from an unauthenticated channel alone if an active attacker is present. Some pre-established trust or an independent way to authenticate the other party is needed.
The best option for Alice to get Bob's public key is a piece of paper. Since this is often impractical, having an intermediary, Chloe, is the second best choice. Chloe will give her public key to Alice on a piece of paper. Later on, Chloe can sign a statement binding Bob's identity to his public key and send it over an insecure channel to Alice. Since Alice trusts Chloe's public key, if she also trusts that Chloe is not a bad person and has checked Bob's identity correctly, then she can verify the signature and authenticate Bob's public key. Note how trust in Chloe's key has allowed Alice to authenticate Bob's public key. Alternatively, Alice and Bob could start with a shared symmetric key, called a PSK, or pre-shared key.
In the end, one must have a trusted starting point. Your browser can authenticate HTTPS websites because it already trusts the public keys of many intermediaries, called certificate authorities (CAs). These public keys are distributed with your operating system or browser. Here's a question that may trouble some: do you trust them?