Quiz 2

Cryptography Basics for Privacy

1772 words
9 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Cryptography Basics for Privacy ## 🎯 Learning Objectives - Distinguish between symmetric and asymmetric encryption - Explain how hash functions protect data integrity - Apply cryptographic concepts to privacy scenarios - Understand how TLS/SSL uses cryptography - Recognize the limitations of cryptography for priv...

Cryptography Basics for Privacy

🎯 Learning Objectives

  • Distinguish between symmetric and asymmetric encryption
  • Explain how hash functions protect data integrity
  • Apply cryptographic concepts to privacy scenarios
  • Understand how TLS/SSL uses cryptography
  • Recognize the limitations of cryptography for privacy

1. Why Cryptography Matters for Privacy

1.1 Intuition

Cryptography is the art of hiding information from everyone except the intended recipient. Think of it as a lockbox: anyone can put a message in (encryption), but only the person with the key can take it out (decryption). Without cryptography, all your online communication — messages, passwords, credit card numbers — would be visible to anyone intercepting the data. For privacy in online social media, cryptography provides four essential guarantees:
  • Confidentiality: Only the intended recipient can read the message
  • Integrity: The message hasn't been tampered with
  • Authentication: You know who sent the message
  • Non-repudiation: The sender can't deny sending it

2. Symmetric Encryption

2.1 Intuition

Symmetric encryption is like a shared secret handshake — both people know the same secret signal. If Alice and Bob both know the secret, Alice can send encrypted messages that only Bob can decrypt. The problem? They need to agree on the secret without anyone else hearing it.

2.2 How It Works

(Diagram) Algorithm: AES (Advanced Encryption Standard) — the most widely used symmetric cipher.
AlgorithmKey SizeBlock SizeSecurity Level
AES-128128 bits128 bitsSufficient for most uses
AES-256256 bits128 bitsMilitary-grade
DES56 bits64 bitsBroken (too small)
3DES112-168 bits64 bitsDeprecated

2.3 Python Example

python
from cryptography.fernet import Fernet
# Generate a key
key = Fernet.generate_key()
cipher = Fernet(key)
# Encrypt
message = b"Your medical records - confidential"
encrypted = cipher.encrypt(message)
print(f"Encrypted: {encrypted}")
# Decrypt
decrypted = cipher.decrypt(encrypted)
print(f"Decrypted: {decrypted}")
Tracing Table:
StepInputOutput
Original"Your medical records - confidential"
Encrypt with keyPlaintext + KeygAAAAAB...random_bytes...
Decrypt with same keyCiphertext + Key"Your medical records - confidential"
Decrypt with wrong keyCiphertext + WrongKeyError: InvalidToken

3. Asymmetric (Public-Key) Cryptography

3.1 Intuition

Asymmetric encryption solves the key-sharing problem. Instead of one secret, you have two keys: a public key (like your email address — anyone can know it) and a private key (like your email password — only you know it). Anyone can encrypt a message using your public key, but only you can decrypt it with your private key.

3.2 How It Works

(Diagram)
FeatureSymmetricAsymmetric
KeysOne shared keyPublic + Private pair
SpeedFast (1GB/s with AES-NI)Slow (1MB/s with RSA)
Key exchangeProblematic (need secure channel)Easy (public key is public)
Typical usageBulk data encryptionKey exchange, signatures

3.3 RSA Example

python
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
# Generate key pair
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048
)
public_key = private_key.public_key()
# Encrypt with public key
message = b"Secret social media data"
ciphertext = public_key.encrypt(
    message,
    padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                 algorithm=hashes.SHA256(), label=None)
)
print(f"Encrypted ({len(ciphertext)} bytes): {ciphertext[:50]}...")
# Decrypt with private key
plaintext = private_key.decrypt(
    ciphertext,
    padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                 algorithm=hashes.SHA256(), label=None)
)
print(f"Decrypted: {plaintext}")

4. Hash Functions

4.1 Intuition

A hash function is like a fingerprint for data. It takes any input (a tweet, a photo, a database) and produces a fixed-size "digest." If the data changes even slightly, the hash changes completely. Hashes are one-way — you can't recover the original data from the hash.

4.2 Properties

PropertyMeaningExample
DeterministicSame input → same hashSHA256("hello") is always the same
Fast to computeEven large files hash quicklyMillions of bytes per second
Preimage resistantCan't reverse hash to inputGiven hash, can't find original
Collision resistantDifferent inputs give different hashesExtremely unlikely to find two inputs with same hash
Avalanche effectSmall change → completely different hashChange one bit → 50% of output bits change

4.3 Applications for Privacy

ApplicationHow Hashing Helps
Password storageStore hash, not plaintext password
Data integrityVerify file hasn't been changed
AnonymizationHash identifiers (with salt)
Bloom filtersCheck membership without storing data

4.4 Hashing with Salt

python
import hashlib, os
def hash_identifier(identifier, salt=None):
    """Hash a user identifier with salt for privacy."""
    if salt is None:
        salt = os.urandom(16)  # Random salt
    # Combine salt + identifier
    salted = salt + identifier.encode()
    digest = hashlib.sha256(salted).hexdigest()
    return salt.hex() + ":" + digest
# Same identifier with different salts produces different hashes
email = "[email protected]"
print(hash_identifier(email))  # Different each time due to random salt

5. Digital Signatures

5.1 Intuition

A digital signature proves that a message came from a specific person and hasn't been altered. It's like signing a document with a pen, but cryptographically unforgeable. The sender signs with their private key; anyone can verify with the sender's public key.

5.2 Signing and Verification

(Diagram)

6. Cryptographic Limitations

6.1 What Crypto Does NOT Protect Against

ThreatWhy Crypto Doesn't Help
MetadataWho you're talking to, when, how often
Side channelsTiming, power consumption, electromagnetic leaks
Social engineeringTricking you into revealing the key
Endpoint compromiseIf attacker has your device, encryption is useless
Quantum computingFuture threat to RSA and ECC

6.2 End-to-End Encryption vs. Encryption in Transit

TypeData ProtectedExample
Encryption in transitWhile moving between devicesHTTPS (server has plaintext)
End-to-end encryptionFrom sender to recipient onlyWhatsApp (server can't read)

7. Common Pitfalls

Pitfall 1: Rolling Your Own Crypto

The mistake: Implementing encryption algorithms yourself instead of using well-tested libraries. Why students make it: The math seems simple enough, and using libraries doesn't feel like "real" implementation. How to catch it: If you're implementing AES or RSA from scratch, you're likely making security mistakes (timing attacks, padding oracle attacks, weak key generation). Correct approach: Always use established libraries (cryptography, PyCryptodome, libsodium). They're maintained by experts and have been audited.

Pitfall 2: Confusing Encoding with Encryption

The mistake: Base64 encoding or URL encoding data and calling it "encrypted." Why students make it: Encoded data looks unreadable (gibberish text). How to catch it: Encoding is reversible without a key — anyone can decode Base64. Encryption requires a key. Correct approach: Encoding ≠ encryption. Use proper encryption algorithms with keys.

Pitfall 3: Storing Passwords with Fast Hashes

The mistake: Using SHA-256 to hash passwords, which is too fast for password storage. Why students make it: SHA-256 is the most well-known hash function. How to catch it: Attackers can compute billions of SHA-256 hashes per second on GPU hardware. Correct approach: Use password-specific hash functions: bcrypt, scrypt, or Argon2. They're intentionally slow (configurable work factor).

8. Key Concepts Reference

ConceptDefinitionPrivacy Use
Symmetric encryptionSame key for encrypt and decryptBulk data protection
Asymmetric encryptionPublic/private key pairSecure key exchange
Hash functionOne-way deterministic digestIntegrity, password storage
Digital signaturePrivate-key signed hashAuthentication, non-repudiation
SaltRandom data added before hashingPrevents rainbow table attacks
AESAdvanced Encryption StandardIndustry standard encryption
RSARivest-Shamir-AdlemanPublic-key encryption
End-to-end encryptionOnly endpoints can decryptPrivate messaging

9. 📝 Practice Questions

Q1: Alice wants to send an encrypted message to Bob. Bob doesn't have a public key. Which type of encryption can they use and what's the problem?
Answer: They can use symmetric encryption, but they face the key exchange problem — how to securely share the symmetric key. If Alice generates a key and sends it over the internet, an attacker could intercept it. They need a pre-shared secret (meet in person) or asymmetric encryption to exchange the symmetric key (which requires Bob to have a key pair). Q2: Why is AES-256 preferred over AES-128 for highly sensitive data?
Answer: AES-256 uses a 256-bit key vs. 128-bit for AES-128. The key space difference is enormous: 2^256 vs 2^128 possibilities. While both are secure against brute force with current technology (2^128 is already infeasible), AES-256 provides security margin against future advances (quantum computing reduces brute force to 2^128 for AES-256, but 2^64 for AES-128 — still too large for quantum). Q3: A SHA-256 hash is 64 characters (256 bits). How many possible hash values exist?
Answer: 2^256 ≈ 1.16 × 10^77 possible values — more than the number of atoms in the observable universe (~10^80). This makes finding two inputs with the same hash (collision) computationally infeasible. Q4: What does it mean that a hash function is "preimage resistant"?
Answer: Preimage resistance means: given a hash value h, it's computationally infeasible to find any input x such that hash(x) = h. This is crucial for password storage — even if the hash database is leaked, attackers cannot determine the original passwords. Without preimage resistance, they could simply reverse the hashes to get passwords. Q5: Compare encryption in transit vs. end-to-end encryption for a messaging app.
Answer: Encryption in transit (HTTPS) protects data between your device and the server, but the server has the plaintext. The server operator can read your messages, comply with government data requests, or be hacked. End-to-end encryption (Signal, WhatsApp) ensures only the communicating users can read messages — even the server operator cannot decrypt them. E2EE provides stronger privacy guarantees but complicates features like server-side search or message recovery. Q6: Why is "salt" used when hashing passwords?
Answer: Salt prevents: (1) Rainbow table attacks — precomputed hash dictionaries won't work because each password has a unique salt. (2) Identical password detection — two users with password "password123" get different hashes due to different salts. (3) Parallel cracking — attacker must crack each hash separately instead of cracking all at once. Without salt, an attacker who steals the hash database can efficiently reverse common passwords. Q7: What is the "key exchange problem" and how does Diffie-Hellman solve it?
Answer: The key exchange problem: how do two parties agree on a shared secret (symmetric key) over an insecure channel? Diffie-Hellman solves this: Alice and Bob each generate private keys, compute public values, exchange them, and independently derive the same shared secret. An eavesdropper sees only the public values but cannot compute the shared secret (due to the discrete logarithm problem). This enables secure key agreement for symmetric encryption without pre-sharing a secret. Q8: A website stores passwords with SHA-256 (no salt). As a security consultant, what do you recommend?
Answer: (1) Immediately switch to a password hashing algorithm (bcrypt, scrypt, Argon2) with a configurable work factor. (2) Use a unique random salt per password. (3) Existing hashes should be re-hashed with the new algorithm on next login (or force password reset). (4) SHA-256 without salt is fast to compute (billions per second on GPU) and vulnerable to rainbow tables — attackers can crack most passwords quickly. The current passwords are at serious risk if the database is leaked.

10. 🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.