What is Cryptography
Cryptography is the science of securing information by transforming it into an unreadable format that can only be decoded by authorized parties. It's the foundation of modern cybersecurity, protecting everything from your online banking to military communications. As a penetration tester, you'll encounter cryptography constantly—both as a security control to bypass and a tool for protecting your own communications.
What You'll Learn
- Fundamental cryptographic concepts and terminology
- Symmetric vs. asymmetric encryption
- Hashing and its security applications
- Digital signatures and certificates
- Common cryptographic algorithms
- How cryptography is used (and misused) in real-world systems
Why Cryptography Matters in Cybersecurity
For Defenders:
- Protecting data at rest: Encrypting stored files and databases
- Securing data in transit: HTTPS, VPNs, secure email
- Authentication: Verifying identities with password hashes
- Integrity: Ensuring data hasn't been tampered with
For Penetration Testers:
- Password cracking: Understanding hash types to crack them
- SSL/TLS attacks: Identifying weak cipher suites and configurations
- Finding encryption weaknesses: ECB mode, weak keys, poor implementations
- Cryptanalysis: Breaking weak or improperly implemented crypto
⚠️ Golden Rule: Never roll your own crypto! Use well-established, peer-reviewed algorithms and libraries. Cryptography is extremely difficult to implement correctly.
Core Cryptographic Concepts
Plaintext vs. Ciphertext
- Plaintext: Original, readable message ("Hello World")
- Ciphertext: Encrypted, unreadable message ("8F4dKp9x...")
- Encryption: Converting plaintext → ciphertext
- Decryption: Converting ciphertext → plaintext
The CIA Triad in Cryptography
Confidentiality: Only authorized parties can read the data
- Achieved through: Encryption
Integrity: Data hasn't been altered
- Achieved through: Hashing, MACs (Message Authentication Codes)
Authentication: Verify the identity of parties
- Achieved through: Digital signatures, certificates
Note: This CIA triad is different from the intelligence agency!
Keys and Algorithms
Algorithm: The mathematical method for encryption (e.g., AES, RSA) Key: The secret value that determines the specific encryption
Analogy: The algorithm is like the design of a lock, the key is what actually opens it.
Plaintext + Algorithm + Key = Ciphertext
Kerckhoffs's Principle
"A cryptosystem should be secure even if everything about the system, except the key, is public knowledge."
Translation: Security must rely on the secrecy of the key, NOT the secrecy of the algorithm. This is why open-source cryptography (like AES) is trusted—experts worldwide can analyze it for weaknesses.
Symmetric Encryption
Concept: Same key used for both encryption and decryption
How It Works:
Alice Bob
| |
| 1. Share secret key (K) |
|----------------------------->|
| |
| 2. Encrypt with K |
| Plaintext → Ciphertext |
|----------------------------->|
| |
| 3. Decrypt with K |
| Ciphertext → Plaintext |
Advantages:
✅ Fast: Much faster than asymmetric encryption ✅ Efficient: Good for large amounts of data ✅ Simple: Straightforward concept
Disadvantages:
❌ Key distribution problem: How do you securely share the key? ❌ Key management: Need a unique key for each pair of communicators ❌ No non-repudiation: Can't prove who encrypted the message
Common Symmetric Algorithms:
AES (Advanced Encryption Standard) 🥇
- Status: Current gold standard
- Key sizes: 128, 192, or 256 bits
- Speed: Very fast
- Security: Unbroken (when used correctly)
- Use cases: Wi-Fi (WPA2/WPA3), disk encryption, VPNs
# Encrypt file with AES-256
openssl enc -aes-256-cbc -salt -in file.txt -out file.txt.enc
# Decrypt file
openssl enc -aes-256-cbc -d -in file.txt.enc -out file.txt
DES (Data Encryption Standard)
- Status: ⚠️ OBSOLETE - Do not use!
- Key size: 56 bits (too small)
- Why deprecated: Can be brute-forced quickly
- Historical note: Dominated 1970s-1990s
3DES (Triple DES)
- Status: Legacy - avoid for new systems
- Concept: Apply DES three times
- Key size: Effectively 112 or 168 bits
- Problem: Slow, constrained by small block size, and better alternatives exist
ChaCha20
- Status: Modern alternative to AES
- Speed: Excellent on mobile/ARM processors
- Security: Strong
- Use case: Used in TLS, WireGuard VPN
Asymmetric Encryption (Public Key Cryptography)
Concept: Uses a pair of mathematically related keys—public and private
Key Pair:
- Public key: Can be shared with everyone
- Private key: Must be kept secret
How It Works:
Encryption (for confidentiality):
Alice wants to send Bob a secret message:
1. Bob shares his public key with Alice
2. Alice encrypts message with Bob's public key
3. Only Bob's private key can decrypt it
4. Bob decrypts with his private key
Digital Signatures (for authentication):
Alice wants to prove a message is from her:
1. Alice creates a hash of the message
2. Alice encrypts hash with her private key (= signature)
3. Anyone with Alice's public key can verify it's from Alice
Advantages:
✅ No key distribution problem: Public keys can be shared openly ✅ Non-repudiation: Digital signatures prove who sent the message ✅ Key management: Only need one key pair per person
Disadvantages:
❌ Slow: 100-1000x slower than symmetric encryption ❌ Size: Encrypted data is larger ❌ Complexity: More complex to implement
Common Asymmetric Algorithms:
RSA (Rivest-Shamir-Adleman) 🥇
- Status: Most widely used
- Key sizes: 2048, 3072, 4096 bits (2048 is a baseline; prefer 3072+ for longer-lived systems)
- Based on: Factoring large prime numbers
- Use cases: SSL/TLS certificates, SSH keys, PGP/GPG
# Generate RSA key pair
ssh-keygen -t rsa -b 4096 -C "[email protected]"
# Public key: ~/.ssh/id_rsa.pub (share this)
# Private key: ~/.ssh/id_rsa (keep secret!)
ECC (Elliptic Curve Cryptography)
- Status: Modern, increasingly popular
- Key sizes: 256 bits (equivalent to 3072-bit RSA)
- Advantages: Smaller keys, faster, same security
- Algorithms: ECDSA, ECDH
- Use cases: Mobile devices, IoT, modern TLS
Diffie-Hellman (DH/DHE/ECDHE)
- Purpose: Key exchange (not encryption)
- Concept: Two parties agree on a shared secret over an insecure channel
- Use case: Establishing symmetric keys for TLS sessions
Hybrid Encryption (Best of Both Worlds)
Real-world systems combine symmetric and asymmetric encryption:
How HTTPS Works:
- Asymmetric: Exchange keys securely (RSA/ECDHE)
- Symmetric: Encrypt actual data with agreed key (AES)
Why? Asymmetric encryption establishes trust and exchanges keys; symmetric encryption handles the bulk data transfer efficiently.
Hashing
Concept: One-way function that produces a fixed-size output (hash) from any input
Key Properties:
- Deterministic: Same input always produces same hash
- Fixed size: Hash is always same length (e.g., SHA-256 = 256 bits)
- One-way: Cannot reverse hash to get original input
- Avalanche effect: Tiny change in input drastically changes hash
- Collision resistant: Nearly impossible to find two inputs with same hash
Hash Example:
echo -n "password" | sha256sum
# Output: 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8
echo -n "Password" | sha256sum # Capital P
# Output: e7cf3ef4f17c3999a94f2c6f612e8a888e5b1026878e4e19398b23bd38ec221a
# Completely different!
Common Hashing Algorithms:
MD5 (Message Digest 5)
- Status: ⚠️ BROKEN - Do not use for security!
- Hash size: 128 bits
- Problem: Collisions can be easily generated
- Still okay for: Checksums (non-security purposes)
SHA-1 (Secure Hash Algorithm 1)
- Status: ⚠️ DEPRECATED - Collision attacks exist
- Hash size: 160 bits
- Problem: Google demonstrated collisions in 2017
- Being phased out: No longer trusted for certificates
SHA-256 (SHA-2 family) 🥇
- Status: Current standard
- Hash size: 256 bits
- Security: No known vulnerabilities
- Use cases: Bitcoin, certificates, file integrity
# Hash a file
sha256sum file.txt
# Verify file integrity
sha256sum -c checksums.txt
SHA-3
- Status: Modern SHA-3 family standardised in 2015
- Hash size: Variable (224, 256, 384, 512 bits)
- Different design: Keccak algorithm
- Use case: Future-proofing, some specialized applications
bcrypt / scrypt / Argon2 🥇
- Purpose: Specifically for password hashing
- Feature: Intentionally slow (adjustable work factor)
- Why: Resists brute-force and rainbow table attacks
- Best practice: Use these for storing passwords, NOT regular hashes
# Example: Password hashing with bcrypt
import bcrypt
password = b"SuperSecret123"
salt = bcrypt.gensalt()
hashed = bcrypt.hashpw(password, salt)
# Verify password
if bcrypt.checkpw(password, hashed):
print("Password matches!")
Use Cases for Hashing:
- Password storage: Store hash, not plaintext
- File integrity: Verify files haven't been tampered with
- Digital signatures: Hash message before signing
- Blockchain: Bitcoin uses SHA-256 extensively
- Certificates: Fingerprints are hashes of certificates
Salting and Peppering
Salting
Problem: Identical passwords produce identical hashes
User1: password → 5e884898...
User2: password → 5e884898... (same hash!)
Solution: Add random salt before hashing
User1: password + "xK9$2m" → hash1
User2: password + "pL4#7q" → hash2 (different!)
Salt properties:
- Unique for each password
- Stored alongside the hash (not secret)
- Prevents rainbow table attacks
Peppering
- Global secret added to all passwords
- NOT stored in database (stored in code or config)
- Adds extra protection if database is compromised
Digital Signatures and Certificates
Digital Signatures
Purpose: Prove authenticity and integrity
Process:
- Hash the document
- Encrypt hash with private key (= signature)
- Attach signature to document
- Recipient decrypts signature with public key
- Recalculate hash and compare
Use cases: Software updates, contracts, code signing
Digital Certificates
Purpose: Bind public key to an identity
Components:
- Subject (who owns the certificate)
- Public key
- Issuer (who signed it - Certificate Authority)
- Validity period
- Digital signature from CA
Example: When you visit https://google.com:
- Google sends its certificate
- Your browser verifies CA signature
- Browser trusts certificate
- Secure connection established
# View certificate details
openssl s_client -connect google.com:443 -showcerts
# Check certificate expiration
echo | openssl s_client -connect google.com:443 2>/dev/null | openssl x509 -noout -dates
Common Cryptographic Vulnerabilities
1. Weak Algorithms
- Using MD5, DES, RC4
- Fix: Use AES-256, SHA-256, RSA-2048+
2. ECB Mode (Electronic Codebook)
Same plaintext block → Same ciphertext block
- Creates patterns, leaks information
- Fix: Use CBC, GCM, or CTR modes
3. Hard-coded Keys
# ❌ BAD
SECRET_KEY = "MyPassword123"
- Fix: Use environment variables, key management systems
4. Insufficient Key Length
- 512-bit RSA, 40-bit symmetric keys
- Fix: 2048-bit RSA minimum, 128-bit symmetric minimum
5. No IV (Initialization Vector) or Predictable IV
- Makes encryption deterministic
- Fix: Generate random IV for each encryption
6. Improper Certificate Validation
- Not checking certificate validity or hostname
- Fix: Enable proper SSL/TLS verification
Penetration Testing Considerations
As a Pentester, Look For:
- Weak ciphers in SSL/TLS:
nmap --script ssl-enum-ciphers -p 443 target.com
- Password hashes:
- Unsalted hashes
- MD5/SHA-1 instead of bcrypt
- Accessible hash files
- Exposed keys:
- In source code repositories
- In config files
- In environment variables (logs)
- Encryption key reuse
- Same key/IV for multiple messages
- Custom crypto implementations:
- Almost always vulnerable
- Look for homegrown algorithms
Try It Yourself
Beginner Exercises:
- Hash exploration:
echo -n "test" | md5sum
echo -n "test" | sha1sum
echo -n "test" | sha256sum
# Notice the different lengths
- Encryption practice:
# Encrypt a file
echo "Secret message" > secret.txt
openssl enc -aes-256-cbc -salt -in secret.txt -out secret.enc
# Enter a password when prompted
# Decrypt it
openssl enc -aes-256-cbc -d -in secret.enc -out decrypted.txt
cat decrypted.txt
- Generate SSH keys:
ssh-keygen -t ed25519 -C "[email protected]"
# Ed25519 is modern, secure, and fast
- Hash a password with salt (Python):
import hashlib
import os
password = "MyPassword123"
salt = os.urandom(32) # 32 random bytes
# Combine password and salt, then hash
hashed = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
print(f"Salt: {salt.hex()}")
print(f"Hash: {hashed.hex()}")
Resources
Interactive Learning:
- CryptoHack - Learn crypto through challenges
- CryptoPals - Practical cryptography challenges
Application Security:
- Password Storage Security - Why passwords must be hashed with salts and slow KDFs to resist offline cracking
- Data Protection and Encryption Training - Encryption at rest, in transit, and the practical choices developers actually make
Books:
- "The Code Book" by Simon Singh - History of cryptography (beginner-friendly)
- "Serious Cryptography" by Jean-Philippe Aumasson - Modern practical crypto
- "Applied Cryptography" by Bruce Schneier - Comprehensive reference
Tools:
- CyberChef - Encode/decode/encrypt/decrypt tool
- Hash Analyzer - Identify hash types
- john, hashcat - Password cracking tools
Videos:
- Computerphile YouTube channel - Excellent crypto explanations
- "Cryptography 101" by Khan Academy
Next Steps
- Practice with OpenSSL: Experiment with encryption and hashing
- Next lesson: Learn about steganography—hiding data in plain sight
- Understand certificates: Inspect HTTPS certificates in your browser
- CTF challenges: Try crypto challenges on picoCTF or HackTheBox
Remember: Cryptography is deep and complex. Focus on understanding when to use what, and always use established libraries—never implement crypto yourself!
"There are two types of cryptography in this world: cryptography that will stop your kid sister from reading your files, and cryptography that will stop major governments from reading your files." - Bruce Schneier