Cryptography: The Basics
Cryptography sits underneath almost everything you’ll touch: stored passwords, signed cookies, tokens, HTTPS, encrypted files. You don’t need the maths to use it well, but you do need to know what each piece promises and what it doesn’t. In an assessment the algorithm is almost never what breaks: it’s how it’s used, like Base64 treated as encryption, an unsalted password hash or a reused nonce.
Concepts
Section titled “Concepts”What cryptography guarantees
Section titled “What cryptography guarantees”Before looking at algorithms, the useful question is which property you need. Each primitive gives some and not others:
| Property | Question it answers | What provides it |
|---|---|---|
| Confidentiality | Can someone who shouldn’t read it? | Encryption (symmetric or asymmetric) |
| Integrity | Has someone changed it on the way? | Hash (only if the hash itself is protected), HMAC, authenticated encryption |
| Authenticity | Does it come from who it claims? | HMAC (shared key), digital signature (private key) |
| Non-repudiation | Can the author deny signing it? | Only a digital signature: nobody else has their private key |
A classic mistake is using a primitive for something it doesn’t provide. Encrypting a message doesn’t stop it being modified: without authentication, whoever intercepts it can flip bits in the ciphertext and change the result without knowing the key.
Encoding, encrypting and hashing are not the same
Section titled “Encoding, encrypting and hashing are not the same”| Operation | Needs a key? | Reversible? | What it’s for | Examples |
|---|---|---|---|---|
| Encoding | No | Yes, by anyone | Carrying data in another format | Base64, hex, URL encoding |
| Encryption | Yes | Yes, with the key | Hiding the content | AES, ChaCha20, RSA |
| Hashing | No (except HMAC) | No | Fixed-size fingerprint of data | SHA-256, SHA-3 |
Worked example: an application stores the cookie auth=YWRtaW46YWRtaW4=. The trailing = and the alphabet (letters, digits, +, /) give away Base64. Decoding needs nothing:
echo -n 'YWRtaW46YWRtaW4=' | base64 -d# admin:admin <- username and password in clear, just reformattedBase64 exists so binary data can travel over text channels (email, HTTP headers, JSON). It has no key, so it protects nothing: anyone undoes it in a second.
Symmetric encryption
Section titled “Symmetric encryption”The same key encrypts and decrypts. It’s fast, and it’s what protects almost all data in practice. The standard is AES, a block cipher: it works on 128-bit (16-byte) blocks with 128, 192 or 256-bit keys. ChaCha20 is the usual stream alternative on mobile and in TLS.
The problem with symmetric crypto is key distribution: sender and receiver have to share the key without anyone else seeing it. Asymmetric crypto solves that (next section).
Modes of operation
Section titled “Modes of operation”A block cipher only knows how to encrypt 16 bytes. For a longer message you need a mode that says how to chain blocks, and that’s where many bugs live:
| Mode | How it works | Needs | Problem or advantage |
|---|---|---|---|
| ECB | Each block encrypted on its own | Nothing | Equal blocks give equal ciphertext: patterns show. Don’t use |
| CBC | Each block XORed with the previous ciphertext | Random, unpredictable IV | No authentication; vulnerable to padding oracle if errors leak |
| CTR | Turns the block cipher into a stream by encrypting a counter | Unique nonce | No authentication; nonce reuse is fatal |
| GCM | CTR + authentication tag | Unique nonce (96 bits) | Authenticated encryption: detects any modification |
The classic ECB example is the Linux penguin image encrypted with ECB: the outline is still visible, because areas of the same colour produce identical ciphertext blocks.
The IV or nonce isn’t secret, it travels with the message, but it must be unique for every encryption under the same key (and, in CBC, unpredictable). In CTR and GCM, reusing a nonce with the same key lets you XOR two ciphertexts and get the XOR of the two plaintexts, and in GCM it also lets you forge authentication. It’s one of the few mistakes that turns a solid algorithm into a useless one.
Asymmetric encryption
Section titled “Asymmetric encryption”Each party has a key pair: a public key anyone can see and a private key that never leaves its owner. What one does, only the other undoes:
- Encrypt with the public key → only the private-key owner can read it (confidentiality).
- Sign with the private key → anyone verifies with the public key that the owner signed it (authenticity and non-repudiation).
The two families you’ll see are RSA (keys of 2048 bits or more) and elliptic-curve cryptography (ECDSA and Ed25519 for signatures, ECDH and X25519 for key agreement), which gives the same security with much shorter keys.
Asymmetric crypto is slow and only handles small blocks. So in practice it’s combined: asymmetric crypto agrees on or delivers a symmetric session key, and symmetric crypto encrypts the data. That’s how TLS, SSH and PGP work. How you prove a public key really belongs to who it claims is covered in the TLS card.
Hash functions
Section titled “Hash functions”A hash turns any input into a fixed-size output. It must have three properties:
| Property | What it means |
|---|---|
| Preimage resistance | Given a hash, you can’t find an input that produces it |
| Second-preimage resistance | Given an input, you can’t find another with the same hash |
| Collision resistance | You can’t find any two inputs with the same hash |
Changing a single character changes the hash completely:
echo -n hola | sha256sum# b221d9dbb083a7f33428d7c2a3c3198ae925614d70210e28716ccaa7cd4ddb79 -echo -n Hola | sha256sum# e633f4fc79badea1dc5db970cf397c8248bac47cc3acf9915ba60b5d76b0e88f -MD5 and SHA-1 have practical collisions: you’ll still see them as checksums, but they’re no good where security matters (signatures, certificates). SHA-256 (SHA-2 family) and SHA-3 are current.
A bare hash only gives integrity if the hash reaches you over a channel you trust: if the attacker changes the file, they can recompute the hash too. For integrity and authenticity with a shared key there’s HMAC (RFC 2104), which mixes the key with the message safely. Building it by hand as sha256(key + message) isn’t equivalent: with SHA-256 that’s vulnerable to length extension, which lets you append data to the message and compute a valid hash without knowing the key.
Passwords: fast hash versus slow KDF
Section titled “Passwords: fast hash versus slow KDF”Passwords aren’t encrypted (if they can be decrypted, whoever steals the key has them all): a hash is stored instead. But SHA-256 is far too fast: a GPU computes billions per second and runs entire wordlists in minutes.
Two things are needed:
- Salt: a random value, different per user, stored next to the hash. Two users with the same password get different hashes and precomputed tables (rainbow tables) stop working. An unsalted hash of a common password is found by simply looking it up.
- A slow function (KDF): designed to take time on purpose and, in modern ones, to use memory, which is what slows GPUs down most. In current order of preference: Argon2id, scrypt, bcrypt and PBKDF2 (the last with many iterations if it’s all you have).
Hashes you’ll come across
Section titled “Hashes you’ll come across”In /etc/shadow, in databases or in Windows dumps, the format usually gives away the algorithm:
| Looks like | Algorithm | Where it shows up |
|---|---|---|
$1$salt$... |
MD5-crypt | Very old Linux, routers |
$5$salt$... |
SHA-256-crypt | Linux |
$6$salt$... |
SHA-512-crypt | Linux (common) |
$y$... |
yescrypt | Current Linux (Debian, Kali) |
$2a$ / $2b$ / $2y$ + cost |
bcrypt | Web apps (PHP, Node, Rails) |
$argon2id$v=19$m=... |
Argon2id | Modern apps |
| 32 hex | MD5 or NTLM | Context decides: NTLM in Windows dumps |
| 40 hex · 64 hex | SHA-1 · SHA-256 | Home-grown apps, almost always unsalted |
NTLM is MD4 over the password in UTF-16LE: unsalted and very fast, which is why it’s among the quickest to crack.
Randomness
Section titled “Randomness”Keys, IVs, nonces, salts and session tokens need cryptographically secure random numbers. The operating system’s generator (/dev/urandom on Linux, getrandom()) is; the random module of many languages isn’t: it becomes predictable once you observe enough outputs. In Python, use secrets for anything security-related and random only for simulations.
In practice
Section titled “In practice”Encrypt and decrypt a file with AES (OpenSSL 3.x):
openssl enc -aes-256-cbc -pbkdf2 -iter 600000 -salt -in notes.txt -out notes.enc# asks for a password; -pbkdf2 derives the key slowly and -salt adds a saltopenssl enc -d -aes-256-cbc -pbkdf2 -iter 600000 -in notes.enc -out notes.txtFile hash and HMAC:
openssl dgst -sha256 report.pdf# SHA2-256(report.pdf)= 9f2c… <- fingerprint to check integrityecho -n hola | openssl dgst -sha256 -hmac 'clave'# SHA2-256(stdin)= 67c0066d5104af2bd88decc45269ddb529a0097b8da4cfbbe58ec2a5f63ca50dCommon encodings:
echo -n hola | od -An -tx1# 68 6f 6c 61 <- hex: one byte, two characterspython3 -c "import urllib.parse; print(urllib.parse.quote(\"' OR 1=1--\"))"# %27%20OR%201%3D1-- <- URL encoding: just format, like Base64Generate an /etc/shadow-style password hash and secure random values:
openssl passwd -6 -salt XyZ123 hola# $6$XyZ123$9r6P15dY8y0V.sq2rncZvh… <- $6$ = SHA-512-crypt, XyZ123 = saltopenssl rand -hex 16# 3e1f… <- 16 random bytes in heximport hashlib, secrets
hashlib.sha256(b"hola").hexdigest() # 'b221d9db…' fast hash: not for passwordssecrets.token_hex(16) # 32-char hex token, fine for sessionssecrets.token_urlsafe(32) # 32 random bytes in URL-safe Base64Identifying an unknown hash: tools such as hashid or name-that-hash suggest candidates by length and format, and recent hashcat --identify does the same. They’re hints, not certainty: 32 hex characters could be MD5, NTLM or anything else 128 bits long.
Next offensive step
Section titled “Next offensive step”- Symmetric encryption and its flaws: ECB, nonce reuse and weak keys in practice.
- Attacks on hash functions: cracking, length extension and collisions.
- Padding oracle: decrypting CBC without the key when the app leaks errors.
- Hashcat: modes and attacks for cracking hashes in the lab.
Cheat sheet
Section titled “Cheat sheet”| Concept | What to remember |
|---|---|
| Base64, hex, URL | Format, not protection. Undone without a key. |
| Symmetric | One key to encrypt and decrypt. AES, 16-byte blocks. |
| ECB | Visible patterns. Never use it. |
| CBC | Random IV; no authentication. |
| GCM | Authenticated encryption; unique nonce or it breaks. |
| Asymmetric | Public encrypts or verifies; private decrypts or signs. |
| Hybrid | Asymmetric for the key, symmetric for the data. |
| MD5, SHA-1 | Practical collisions: not for security. |
| HMAC | Integrity + authenticity with a shared key. Not hash(key+msg). |
| Passwords | Salt + slow KDF: Argon2id, scrypt, bcrypt, PBKDF2. |
$6$ · $2y$ · $argon2id$ |
SHA-512-crypt · bcrypt · Argon2id. |
| NTLM | Unsalted MD4: quick to crack. |
| Random | secrets / /dev/urandom, never random. |
echo -n |
Without it you hash the newline too. |
Review questions
Section titled “Review questions”-
An app says it stores passwords “encrypted in Base64”. What’s the problem?
Answer
Base64 is an encoding: it has no key and anyone undoes it with
base64 -d. The passwords are effectively in clear. The right approach is a salted hash with a slow function such as Argon2id or bcrypt. -
Why does ECB leave an encrypted image’s outline visible while CBC doesn’t?
Answer
In ECB each block is encrypted separately, so equal plaintext blocks give equal ciphertext blocks and patterns survive. In CBC each block is mixed with the previous ciphertext (and the first one with a random IV), so equal blocks produce different outputs.
-
What happens if the same nonce is reused with the same key in AES-GCM?
Answer
The keystream repeats: XORing the two ciphertexts gives the XOR of the two plaintexts, and knowing or guessing one reveals the other. The authentication key can also be recovered, allowing forged messages that pass verification.
-
In asymmetric crypto, which key do you encrypt with so only the recipient can read it, and which do you sign with?
Answer
For confidentiality you encrypt with the recipient’s public key, and only their private key decrypts it. To sign you use your own private key, and anyone verifies the signature with the matching public key.
-
If SHA-256 can’t be reversed, why isn’t storing
sha256(password)enough?Answer
Because you don’t need to reverse it: you just try passwords and compare. SHA-256 is so fast that a GPU tries billions per second, and without a salt common passwords are found straight in precomputed tables. You need a per-user salt and a slow function.
-
You see
$2y$10$...in a database and a 32-character hex string in a Windows dump. What is each?Answer
$2y$10$is bcrypt with cost factor 10 (2^10 rounds), typical of PHP. The 32 hex in a Windows dump are, from context, NTLM hashes (unsalted MD4), much faster to crack. -
Why is
sha256(key + message)not a good substitute for HMAC?Answer
Because of length extension: with SHA-256 (a Merkle-Damgård construction), knowing the hash and the message length lets you append data and compute a valid hash for the extended message without knowing the key. HMAC is designed to prevent that.
-
A developer generates password-reset tokens with Python’s
random.randint. What would you tell them?Answer
That
randomisn’t cryptographically secure: its state can be reconstructed from enough outputs and the next tokens predicted. They should usesecrets.token_urlsafe()orsecrets.token_hex().