# Cryptography for Developers — Encoding vs Hashing vs Encryption, RSA and Diffie–Hellman

Source: https://skills101.in/learn/web-security/web-security-cryptography-basics — Skills101 free tutorial (Web Security (OWASP Top 10)). Updated 2026-11-21.

**A04:2025 Cryptographic Failures** covers mistakes like storing data "encrypted" with Base64, using a fast hash for passwords, or generating reset tokens with a predictable random function. Most of these come from mixing up a few basic ideas. This lesson makes them clear, and works through the two famous public-key algorithms — RSA and Diffie–Hellman — with numbers small enough to check by hand. Both are common in university exams and interviews.

A rule before we start: **never invent your own cryptography.** Use well-tested libraries. The point of this lesson is to understand what those libraries do, so you choose and use them correctly.

## 1. Four tools that are often confused

| Tool | Purpose | Key needed? | Reversible? | Example |
|---|---|---|---|---|
| **Encoding** | represent data in another format | no | yes, by anyone | Base64, URL encoding |
| **Hashing** | fixed-size fingerprint of data | no | no (one-way) | SHA-256 |
| **Encryption** | keep data secret | yes | yes, with the key | AES, RSA |
| **Signature / MAC** | prove data was not changed, and who made it | yes | — (it is a check) | HMAC, RSA signatures |

```python
import base64, hashlib

text = b"marks=78"
print(base64.b64encode(text).decode())
print(base64.b64decode("bWFya3M9Nzg=").decode())
print(hashlib.sha256(text).hexdigest()[:16])
print(hashlib.sha256(b"marks=98").hexdigest()[:16])
```

```text
bWFya3M9Nzg=
marks=78
4c14e27ab40a6fde
6bcc2eb2d846341c
```

- Base64 hides nothing: anyone can decode it. It only makes binary data safe to send as text.
- A hash cannot be "decrypted". Changing one character (78 → 98) gives a completely different hash. Hashes are used for integrity checks and, with a slow salted algorithm, for passwords.
- **Encryption** is the only one of the four that keeps data secret.

## 2. Symmetric encryption: one shared key

In **symmetric** encryption the **same key** encrypts and decrypts — like one key that both locks and unlocks a cupboard.

- The standard algorithm is **AES** (Advanced Encryption Standard), with 128- or 256-bit keys.
- It is very fast, so it is used for bulk data: files, database fields, and all the traffic in an HTTPS connection.
- Use an **authenticated** mode such as **AES-GCM**. It encrypts and also detects any change to the ciphertext. Older modes like ECB leak patterns and must not be used.

The hard part is **key distribution**: how do two parties who have never met agree on a shared key over the internet, where anyone may be listening? Public-key cryptography solves this.

## 3. Asymmetric (public-key) encryption: RSA

In **asymmetric** cryptography each person has a **key pair**:

- a **public key**, which anyone may have, and
- a **private key**, which only the owner keeps.

What one key locks, only the other can unlock. **RSA** (named after Rivest, Shamir and Adleman) builds this from a simple fact: multiplying two large primes is easy, but splitting the product back into those primes is extremely hard.

### RSA with small numbers

1. Pick two primes: p = 61, q = 53.
2. n = p × q = 3233. This is part of both keys.
3. φ (phi) = (p − 1)(q − 1) = 60 × 52 = 3120.
4. Pick e = 17 (it must share no factor with 3120). Public key = (e, n) = (17, 3233).
5. Find d such that (e × d) mod φ = 1. Here d = 2753. Private key = (d, n).
6. Encrypt message m: c = m^e mod n. Decrypt: m = c^d mod n.

```python
# Toy RSA with tiny primes: for learning only, never for real data
p, q = 61, 53
n = p * q
phi = (p - 1) * (q - 1)
e = 17
d = pow(e, -1, phi)          # modular inverse: (e * d) % phi == 1
print("n =", n, " phi =", phi, " d =", d)

message = 65
cipher = pow(message, e, n)   # encrypt with the PUBLIC key (e, n)
plain = pow(cipher, d, n)     # decrypt with the PRIVATE key (d, n)
print("cipher =", cipher, " decrypted =", plain)

signature = pow(message, d, n)            # sign with the PRIVATE key
print("signature =", signature, " valid =", pow(signature, e, n) == message)
```

```text
n = 3233  phi = 3120  d = 2753
cipher = 2790  decrypted = 65
signature = 588  valid = True
```

![Toy RSA: the public key (e=17, n=3233) turns message 65 into ciphertext 2790, and the private key (d=2753, n=3233) turns 2790 back into 65](https://skills101.in/learn-img/web-security/rsa-toy.svg)

`pow(a, b, n)` computes a^b mod n efficiently, and `pow(e, -1, phi)` (Python 3.8+) finds the modular inverse. Anyone who knew p and q could compute d — which is why real RSA uses primes hundreds of digits long (keys of 2048 bits or more), so that n cannot be factored.

### Digital signatures

Run RSA the other way round. The owner computes a value with the **private** key, and anyone can check it with the **public** key. Only the private-key holder could have produced it, so it proves **who** signed and that the data was **not changed**. Real systems sign a **hash** of the message, not the message itself. Signatures protect software updates, HTTPS certificates and JWTs signed with RS256.

Compare with **HMAC** (used in the JWT lesson): HMAC uses one shared secret key, so both sides can create and check it. A signature separates the two powers: only one side can sign, everyone can verify.

## 4. Diffie–Hellman: agreeing on a key in public

**Diffie–Hellman** key exchange lets two people create the same secret number while an eavesdropper watches every message. It relies on the fact that computing g^a mod p is easy, but recovering a from the result is very hard for large numbers.

```python
# Toy Diffie-Hellman: public numbers p and g, secret numbers a and b
p, g = 23, 5
a, b = 6, 15                  # Asha's and Ravi's secrets (never sent)
A = pow(g, a, p)              # Asha sends A
B = pow(g, b, p)              # Ravi sends B
print("sent over the network:", A, B)
print("Asha computes:", pow(B, a, p))
print("Ravi computes:", pow(A, b, p))
```

```text
sent over the network: 8 19
Asha computes: 2
Ravi computes: 2
```

![Asha keeps secret a = 6 and sends A = 8; Ravi keeps secret b = 15 and sends B = 19; Asha computes 19 to the power 6 mod 23 = 2 and Ravi computes 8 to the power 15 mod 23 = 2, the same key, which was never sent](https://skills101.in/learn-img/web-security/diffie-hellman.svg)

Both get 2, because (g^b)^a = (g^a)^b = g^(ab) mod p. The eavesdropper sees 23, 5, 8 and 19 but not 6 or 15. Modern HTTPS uses an elliptic-curve version (ECDHE) with fresh secrets for every connection. This gives **forward secrecy**: stealing the server's long-term key later does not unlock old recorded traffic.

Plain Diffie–Hellman does not prove **who** is on the other side; an attacker in the middle could run two exchanges. HTTPS solves this by having the server **sign** its part with the key in its certificate.

## 5. How HTTPS combines everything

| Step | Tool used |
|---|---|
| Prove the server's identity | certificate + **signature** (RSA or ECDSA) |
| Agree on a session key | **Diffie–Hellman** (ECDHE) |
| Encrypt the actual traffic | **symmetric** encryption (AES-GCM or ChaCha20) |
| Detect tampering | authenticated encryption (the "GCM" part) |

Public-key operations are slow, so they are used only to set up the connection; fast symmetric encryption does the rest.

## 6. Randomness: use a secure generator

Keys, reset tokens, session ids and OTPs must be **unpredictable**. Python's `random` module is designed for simulations and games: it is **predictable**, and the same seed always gives the same numbers.

```python
import random, secrets

random.seed(42)
print([random.randint(0, 9) for _ in range(6)])
random.seed(42)
print([random.randint(0, 9) for _ in range(6)])
print(len(secrets.token_urlsafe(32)))
```

```text
[1, 0, 4, 3, 3, 2]
[1, 0, 4, 3, 3, 2]
43
```

Use the `secrets` module (Python), `SecureRandom` (Java) or `crypto.randomBytes` / `crypto.randomUUID` (Node.js) for anything security-related. `token_urlsafe(32)` uses 32 random bytes and produces a 43-character URL-safe string.

## 7. Choosing the right tool

| Task | Use |
|---|---|
| Store user passwords | slow salted hash: Argon2, bcrypt or PBKDF2 (not plain SHA-256, never encryption) |
| Store an Aadhaar or card number you must read later | encryption (AES-GCM) with keys kept outside the database |
| Check a downloaded file was not corrupted | SHA-256 checksum |
| Prove a webhook really came from the payment gateway | HMAC with the shared secret |
| Let anyone verify your app update | digital signature |
| Password-reset token | `secrets.token_urlsafe()` |

## Common mistakes

- Calling Base64 "encryption".
- Hashing passwords with fast SHA-256 or MD5, or encrypting them so they can be decrypted.
- Using `random` or `Math.random()` for tokens and OTPs.
- Writing your own algorithm, or using AES in ECB mode.
- Keeping the encryption key in the same database or repository as the encrypted data.
- Using textbook RSA without padding; real libraries add padding (OAEP for encryption, PSS for signatures).

## Quick recap

- Encoding = format (no secret); hashing = one-way fingerprint; encryption = secrecy with a key; signature/MAC = integrity and origin.
- Symmetric (AES-GCM): one key, fast. Asymmetric (RSA, ECC): public/private pair, slow, solves key exchange and signatures.
- RSA: n = pq, φ = (p−1)(q−1), ed ≡ 1 (mod φ); encrypt m^e mod n, decrypt c^d mod n.
- Diffie–Hellman: both compute g^(ab) mod p without sending a or b; HTTPS uses ECDHE for forward secrecy.
- Use the `secrets` module for tokens, and well-tested libraries for everything else.


Practice quiz and free certificate: https://skills101.in/learn/web-security/web-security-cryptography-basics