Cryptography Basics
Cryptography is the science of securing communication and data through mathematical techniques. It provides the foundation for confidentiality, integrity, authentication, and non-repudiation in modern cybersecurity.
Table of Contents
- Symmetric Encryption
- Asymmetric Encryption
- Hashing
- Digital Certificates and PKI
- TLS/SSL
- OSCP Exam Relevance
- Practical Examples
- Lab Exercises
- Key Tools
- Exam Tips
- Cross-References
1. Symmetric Encryption
Symmetric encryption uses the same key for both encryption and decryption. The security of the entire system rests on keeping this shared secret key confidential.
1.1 How Symmetric Encryption Works
┌─────────────┐ Key: K ┌─────────────┐
│ Plaintext │ ────E(K)───► │ Ciphertext │
│ "Hello" │ │ "x7#mK9..." │
└─────────────┘ └─────────────┘
┌─────────────┐ Key: K ┌─────────────┐
│ Ciphertext │ ────D(K)───► │ Plaintext │
│ "x7#mK9..." │ │ "Hello" │
└─────────────┘ └─────────────┘
Key characteristics:
- Speed: Extremely fast (suitable for bulk data encryption)
- Key distribution: The challenge of securely sharing the key
- Key management: N(N-1)/2 keys needed for N parties communicating pairwise
1.2 AES (Advanced Encryption Standard)
AES is the most widely deployed symmetric encryption algorithm, standardized by NIST in 2001 (FIPS 197). It replaced DES and is based on the Rijndael cipher.
AES Key Sizes and Parameters
| Key Size | Block Size | Rounds | Key Schedule Words | Security Level |
|---|---|---|---|---|
| 128-bit | 128-bit | 10 | 44 | ~2^128 |
| 192-bit | 128-bit | 12 | 52 | ~2^192 |
| 256-bit | 128-bit | 14 | 60 | ~2^256 |
AES Internal Structure
AES Encryption Rounds (128-bit key example):
Round 0: AddRoundKey
Round 1: SubBytes → ShiftRows → MixColumns → AddRoundKey
Round 2: SubBytes → ShiftRows → MixColumns → AddRoundKey
...
Round 9: SubBytes → ShiftRows → MixColumns → AddRoundKey
Round 10: SubBytes → ShiftRows → AddRoundKey (no MixColumns)
Four core operations:
| Operation | Description | Purpose |
|---|---|---|
| SubBytes | Non-linear byte substitution using S-Box | Confusion |
| ShiftRows | Cyclic shift of rows in the state matrix | Diffusion |
| MixColumns | Linear mixing of columns using GF(2^8) arithmetic | Diffusion |
| AddRoundKey | XOR state with round key | Key mixing |
AES Modes of Operation
AES is a block cipher (128-bit blocks). Modes of operation define how to encrypt data longer than one block and provide different security properties.
ECB Mode (Electronic Codebook) - INSECURE
Plaintext blocks: [P1] [P2] [P1] [P3]
│ │ │ │
Key K │ │ │ │
▼ ▼ ▼ ▼
Ciphertext: [C1] [C2] [C1] [C3]
↑ ↑
Identical plaintext
→ Identical ciphertext!
Why ECB is insecure:
- Identical plaintext blocks produce identical ciphertext blocks
- Reveals patterns in the data
- No diffusion between blocks
- An attacker can detect repeated structures
Famous visual example - The Penguin:
Original image (ECB encrypted with AES):
░░▒▒██ ░░▒▒██
░░▒▒██░░ ░░▒▒██░░
░▒▒██░░▒▒░▒▒██░░▒▒
░▒▒██░░▒▒░▒▒██░░▒▒
░░▒▒██░░ ░░▒▒██░░
░░▒▒██ ░░▒▒██
The penguin shape is STILL VISIBLE!
Pattern preservation makes ECB trivially breakable.
NEVER use ECB mode in production. It fails to provide semantic security.
CBC Mode (Cipher Block Chaining)
Plaintext: [P1] [P2] [P3] [P4]
│ │ │ │
▼ │ │ │
XOR ▼ │ │
[IV] ──►[C1] │ │
│ ▼ │
└──►XOR │
[C2] │
│ ▼
└──►XOR
[C3]
How CBC works:
- XOR plaintext block with previous ciphertext block (or IV for first block)
- Encrypt the result with AES
- Output becomes the input XOR for the next block
Security properties:
- ✅ Identical plaintext blocks produce different ciphertext
- ✅ Provides semantic security
- ⚠️ Requires a unique, random IV per encryption
- ⚠️ Vulnerable to padding oracle attacks if not implemented correctly
- ⚠️ Not parallelizable for encryption (only decryption)
CBC Padding:
- PKCS#7 padding is most common
- If block is 16 bytes, pad with 0x10 (16 bytes of value 16)
- If block needs 1 byte, pad with 0x01
CTR Mode (Counter Mode)
Key K, Nonce N:
AES(K, N||0) → S0 ──XOR──► [C1] ◄── [P1]
AES(K, N||1) → S1 ──XOR──► [C2] ◄── [P2]
AES(K, N||2) → S2 ──XOR──► [C3] ◄── [P3]
AES(K, N||3) → S3 ──XOR──► [C4] ◄── [P4]
How CTR works:
- Encrypt a counter value (nonce + counter) to produce a keystream block
- XOR keystream with plaintext to produce ciphertext
- Increment counter for next block
Security properties:
- ✅ Turns block cipher into a stream cipher
- ✅ Fully parallelizable (both encryption and decryption)
- ✅ No padding needed
- ✅ Random access to any block
- ⚠️ NEVER reuse a nonce with the same key (catastrophic key stream reuse)
- ⚠️ No built-in authentication (use with HMAC or switch to GCM)
GCM Mode (Galois/Counter Mode) - RECOMMENDED
GCM combines:
┌─────────────────────────────────────────────┐
│ CTR Mode Encryption + GHASH Authentication │
│ │
│ Input: Key, Nonce, Plaintext, AAD │
│ Output: Ciphertext + 128-bit Auth Tag │
└─────────────────────────────────────────────┘
How GCM works:
- Generate keystream using CTR mode (same as above)
- XOR keystream with plaintext → ciphertext
- Compute GHMAC authentication tag over ciphertext + AAD (Additional Authenticated Data)
- Output: ciphertext + authentication tag
Security properties:
- ✅ Authenticated Encryption (AEAD) - provides both confidentiality AND integrity
- ✅ High performance (hardware accelerated on modern CPUs)
- ✅ Supports AAD for authenticating associated data
- ✅ Fully parallelizable
- ⚠️ Nonce must be unique (nonce reuse breaks authentication completely)
GCM is the recommended mode for most applications.
AES Performance Comparison
| Mode | Confidentiality | Integrity | Parallel Encrypt | Parallel Decrypt | Speed |
|---|---|---|---|---|---|
| ECB | ✅ (weak) | ❌ | ✅ | ✅ | Fast |
| CBC | ✅ | ❌ | ❌ | ✅ | Medium |
| CTR | ✅ | ❌ | ✅ | ✅ | Fast |
| GCM | ✅ | ✅ | ✅ | ✅ | Fast |
1.3 ChaCha20-Poly1305
ChaCha20 is a stream cipher designed by Daniel J. Bernstein in 2008. Combined with Poly1305 for authentication, it forms an AEAD construction.
ChaCha20 Internal Structure
ChaCha20 Quarter Round:
a ──┐
├──► a += b; d ^= a; d <<<< 16
b ──┘
c ──┐
├──► c += d; b ^= c; b <<<< 12
d ──┘
a ──┐
├──► a += b; d ^= a; d <<<< 8
b ──┘
c ──┐
├──► c += d; b ^= c; b <<<< 7
d ──┘
ChaCha20 parameters:
- Key size: 256 bits
- Nonce: 96 bits (or 64 bits in some variants)
- Block size: 512 bits (64 bytes output per block)
- Rounds: 20 (10 double-rounds)
ChaCha20-Poly1305 Construction
┌──────────────────────────────────────────┐
│ ChaCha20-Poly1305 AEAD │
│ │
│ 1. Generate Poly1305 key from ChaCha20 │
│ 2. Encrypt plaintext with ChaCha20 │
│ 3. Compute Poly1305 MAC over: │
│ - Padded plaintext │
│ - Padded ciphertext │
│ - Lengths of both │
│ 4. Output: ciphertext + 128-bit tag │
└──────────────────────────────────────────┘
Why ChaCha20-Poly1305?
- ✅ No hardware acceleration needed (excellent software performance)
- ✅ Faster than AES-GCM on devices without AES-NI
- ✅ Used in TLS 1.3, SSH, and Linux kernel
- ✅ Resistant to timing attacks
- ✅ Simpler implementation than AES-GCM
1.4 3DES (Triple DES) - DEPRECATED
3DES applies DES three times with either two or three keys:
3DES (EDE mode): C = E_K1(D_K2(E_K3(P)))
Keying options:
├── Option 1: K1 ≠ K2 ≠ K3 (168-bit effective security)
├── Option 2: K1 = K3 ≠ K2 (112-bit effective security)
└── Option 3: K1 = K2 = K3 (equivalent to single DES - INSECURE)
Why 3DES is deprecated:
- ⚠️ Sweet32 attack (2016): Birthday attack on 64-bit block size
- ⚠️ Extremely slow compared to AES
- ⚠️ 64-bit block size is fundamentally limited
- ⚠️ NIST deprecated 3DES for encryption in 2017 (SP 800-131A Rev 2)
- ⚠️ PCI DSS mandated removal by 2018
Sweet32 Attack Details:
- Requires ~2^24.1 encrypted blocks (~78 GB of traffic)
- Recovers plaintext bytes one at a time
- Affects any 64-bit block cipher in CBC mode
- Successfully exploited against 3DES banking systems
1.5 Block Cipher vs Stream Cipher
| Property | Block Cipher | Stream Cipher |
|---|---|---|
| Input | Fixed-size blocks (e.g., 128 bits) | Bit/byte stream |
| Examples | AES, DES, 3DES, ChaCha20 (as block) | RC4, ChaCha20 (as stream) |
| Padding | Required for non-multiple block sizes | Not required |
| Error propagation | One bit error corrupts entire block | One bit error corrupts one bit |
| Random access | Possible (decrypt any block independently) | Possible (seek to position) |
| Speed | Fast with hardware acceleration | Fast in software |
| Security | Well-analyzed, standardized | RC4 broken; ChaCha20 secure |
Converting block cipher to stream cipher:
- CTR mode turns any block cipher into a stream cipher
- OFB (Output Feedback) mode also achieves this
- CCM mode combines CTR with CBC-MAC for authenticated encryption
2. Asymmetric Encryption
Asymmetric (public-key) cryptography uses a key pair: a public key for encryption and a private key for decryption. This solves the key distribution problem of symmetric cryptography.
2.1 RSA (Rivest-Shamir-Adleman)
RSA is the most widely deployed public-key algorithm, invented in 1977.
RSA Key Generation
Step 1: Choose two large prime numbers p and q
p ≈ 2^(n/2), q ≈ 2^(n/2) where n = key size in bits
Step 2: Compute n = p × q
n is the modulus, shared in both keys
Step 3: Compute φ(n) = (p-1) × (q-1)
Euler's totient function
Step 4: Choose e such that 1 < e < φ(n) and gcd(e, φ(n)) = 1
e is the public exponent (commonly 65537 = 0x10001)
Step 5: Compute d such that d × e ≡ 1 (mod φ(n))
d is the private exponent (modular multiplicative inverse)
Public Key: (e, n)
Private Key: (d, n) [also keep p, q for CRT optimization]
RSA Encryption and Decryption
Encryption:
Ciphertext C = M^e mod n
where M is the plaintext message (M < n)
Decryption:
Plaintext M = C^d mod n
Why it works:
M^ed ≡ M (mod n) [by Euler's theorem, since ed ≡ 1 (mod φ(n))]
RSA Key Sizes
| Key Size (bits) | Security Level | Status | Minimum Recommended |
|---|---|---|---|
| 512 | Broken | ❌ DO NOT USE | - |
| 768 | Broken (2009) | ❌ DO NOT USE | - |
| 1024 | ~80 bits | ⚠️ Deprecated | - |
| 2048 | ~112 bits | ✅ Current minimum | Yes |
| 3072 | ~128 bits | ✅ Recommended | - |
| 4096 | ~152 bits | ✅ High security | - |
NIST recommendations:
- RSA 2048-bit: Secure through 2030
- RSA 3072-bit: Secure through 2033
- RSA 7680-bit: Secure through 2039+
RSA Optimizations
Chinese Remainder Theorem (CRT) Speedup:
Instead of: M = C^d mod n
Compute:
dp = d mod (p-1)
dq = d mod (q-1)
qinv = q^(-1) mod p
mp = C^dp mod p
mq = C^dq mod q
h = qinv × (mp - mq) mod p
M = mq + h × q
Result: ~4x faster decryption
Why e = 65537?
- Small enough for fast encryption/verification
- Large enough to avoid low-exponent attacks
- Prime number (2^16 + 1, a Fermat prime)
- Only 17 bits, efficient for modular exponentiation
RSA Vulnerabilities
| Attack | Description | Prevention |
|---|---|---|
| Small e attack | e=3 with same message to multiple recipients (broadcast attack) | Use e=65537, proper padding |
| Padding oracle | PKCS#1 v1.5 padding allows chosen-ciphertext attacks (Bleichenbacher) | Use OAEP padding |
| Common factor | Two keys share a prime (poor RNG) | GCD attack on moduli |
| Timing attack | Side-channel via CRT computation timing | Constant-time implementation |
| Key recovery | Factoring n reveals p and q | Use adequate key size |
2.2 ECC (Elliptic Curve Cryptography)
ECC provides equivalent security to RSA with much smaller key sizes, making it ideal for constrained environments.
Why ECC?
| Security Level | RSA Key Size | ECC Key Size | Speed Advantage |
|---|---|---|---|
| 80 bits | 1024 | 160 | ~10x |
| 112 bits | 2048 | 224 | ~5-10x |
| 128 bits | 3072 | 256 | ~10-20x |
| 192 bits | 7680 | 384 | ~20-50x |
| 256 bits | 15360 | 512 | ~50-100x |
ECC advantages:
- Smaller keys → less storage, bandwidth, and computation
- Faster key generation
- Ideal for mobile devices, IoT, and constrained environments
- No known sub-exponential attacks (security based on discrete log problem)
ECC Mathematics (Simplified)
Elliptic Curve Equation (Weierstrass form):
y² = x³ + ax + b (over a finite field)
Point Addition:
Given points P and Q on the curve:
- Draw a line through P and Q
- The line intersects the curve at a third point R'
- Reflect R' across the x-axis to get R = P + Q
Scalar Multiplication:
k × P = P + P + P + ... + P (k times)
Easy to compute forward, hard to reverse (ECDLP)
Common ECC Curves
| Curve | Field Size | Security Level | Usage |
|---|---|---|---|
| secp256r1 (P-256, prime256v1) | 256-bit | ~128 bits | TLS, Windows, NIST standard |
| secp384r1 (P-384) | 384-bit | ~192 bits | High-security applications |
| secp521r1 (P-521) | 521-bit | ~256 bits | Maximum security |
| Curve25519 | 255-bit | ~128 bits | SSH, Signal, TLS 1.3 |
| Ed25519 | 255-bit | ~128 bits | Digital signatures |
| Ed448 | 448-bit | ~224 bits | High-security signatures |
Ed25519 - Modern Signature Scheme
Ed25519 advantages:
├── Deterministic signatures (no random nonce needed)
├── Constant-time implementation (resistant to timing attacks)
├── Compact signatures (64 bytes)
├── Compact public keys (32 bytes)
├── Fast verification
└── Used in: SSH ed25519 keys, TLS, Bitcoin (Cash), Signal
Ed25519 vs ECDSA:
- ECDSA requires a cryptographically secure random nonce per signature
- A reused or predictable nonce in ECDSA leaks the private key
- Ed25519 derives the nonce deterministically from the message and private key
- This eliminates the entire class of nonce-related attacks
2.3 Diffie-Hellman Key Exchange
Diffie-Hellman (DH) allows two parties to establish a shared secret over an insecure channel.
Classic DH Key Exchange
Public parameters (known to all):
- Large prime p
- Generator g (primitive root mod p)
┌─────────────────┐ ┌─────────────────┐
│ Alice │ │ Bob │
│ │ │ │
│ 1. Choose a (private) │ │ 1. Choose b (private)
│ │ │ │
│ 2. Compute A = g^a mod p │ 2. Compute B = g^b mod p
│ │ │ │
│ ──────── A ──────────────► │ │
│ │ │ │
│ │◄──────── B ──────── │
│ │ │ │
│ 3. Compute S = B^a mod p │ 3. Compute S = A^b mod p
│ │ │ │
│ S = (g^b)^a = g^(ab) mod p │ S = (g^a)^b = g^(ab) mod p
│ │ │ │
│ Both have the same secret S!│ │
└─────────────────┘ └─────────────────┘
Why it works:
- Both compute g^(ab) mod p
- An eavesdropper sees p, g, A, B but cannot compute g^(ab) efficiently
- This is the Computational Diffie-Hellman Problem
ECDH (Elliptic Curve Diffie-Hellman)
Same concept as DH, but using elliptic curve point multiplication:
Alice: a (private) → A = a × G (public)
Bob: b (private) → B = b × G (public)
Shared secret: S = a × B = a × (b × G) = b × (a × G) = b × A
ECDH is the standard for modern TLS key exchange.
DH Key Sizes
| Key Size (bits) | Security Level | Status |
|---|---|---|
| 768 | Broken | ❌ |
| 1024 | ~80 bits | ⚠️ Deprecated |
| 2048 | ~112 bits | ✅ Minimum |
| 3072 | ~128 bits | ✅ Recommended |
Logjam Attack (2015):
- Exploited widespread use of 1024-bit DH
- Precomputation attack against common DH primes
- Downgraded connections to export-grade 512-bit DH
- Mitigation: Use 2048-bit DH or ECDH, disable DH key exchange downgrade
2.4 Digital Signatures
Digital signatures provide authentication, integrity, and non-repudiation.
How Digital Signatures Work
Signing Process:
┌──────────────────────────────────────────┐
│ 1. Compute hash of message: H = Hash(M) │
│ 2. Encrypt hash with private key: │
│ Signature S = Sign(H, PrivateKey) │
│ 3. Send (M, S) to recipient │
└──────────────────────────────────────────┘
Verification Process:
┌──────────────────────────────────────────┐
│ 1. Receive (M, S) │
│ 2. Decrypt signature with public key: │
│ H' = Verify(S, PublicKey) │
│ 3. Compute hash of received message: │
│ H = Hash(M) │
│ 4. Compare: H == H' ? │
│ ✅ Match → Signature valid │
│ ❌ No match → Signature invalid │
└──────────────────────────────────────────┘
Signature Schemes
| Scheme | Algorithm | Key Size | Signature Size | Status |
|---|---|---|---|---|
| RSA-PSS | RSA with OAEP padding | 2048+ bits | Same as key | ✅ Recommended |
| ECDSA | Elliptic Curve DSA | 256 bits | 64 bytes | ✅ Widely used |
| EdDSA (Ed25519) | Edwards-curve DSA | 256 bits | 64 bytes | ✅ Modern, recommended |
| DSA | Digital Signature Algorithm | 2048+ bits | 40 bytes | ⚠️ Legacy |
Why we sign hashes, not messages:
- Hashing reduces message to fixed size
- Much faster to sign a 32-byte hash than a multi-GB file
- Mathematically required for most signature schemes
- Provides integrity (any change to message changes hash)
3. Hashing
Cryptographic hash functions map arbitrary-length input to a fixed-length output with specific security properties.
3.1 Properties of Cryptographic Hash Functions
| Property | Description |
|---|---|
| Deterministic | Same input always produces same output |
| Pre-image resistant | Given H, hard to find M such that Hash(M) = H |
| Second pre-image resistant | Given M1, hard to find M2 ≠ M1 such that Hash(M1) = Hash(M2) |
| Collision resistant | Hard to find any M1 ≠ M2 such that Hash(M1) = Hash(M2) |
| Avalanche effect | Small input change produces drastically different output |
| Fixed output size | Always produces output of same length regardless of input |
3.2 MD5 - BROKEN
MD5 (Message Digest 5):
├── Output: 128 bits (32 hex characters)
├── Designed by: Ron Rivest (1991)
├── Status: CRYPTOGRAPHICALLY BROKEN
└── Example: d41d8cd98f00b204e9800998ecf8427e (empty string)
Why MD5 is Broken
Collision attacks:
- 2004: Wang et al. demonstrated practical collision attacks
- 2007: First collision attack in the wild (MD5collide tool)
- 2008: First forged SSL certificate using MD5 collision (VUEN vulnerability)
- 2012: Flame malware used MD5 collision to sign malicious code with Microsoft’s key
Collision example:
Two different files with the same MD5 hash:
File 1: [binary data A...]
MD5: 7a87c0e1b4f8e2d3c5a6b9f0e1d2c3b4
File 2: [binary data B...] ← Different content!
MD5: 7a87c0e1b4f8e2d3c5a6b9f0e1d2c3b4 ← Same hash!
Time to generate: ~seconds on modern hardware
MD5 should NEVER be used for:
- Digital signatures
- Certificate validation
- Password hashing
- Any security-critical application
MD5 is still acceptable for:
- Non-security checksums (detecting accidental corruption)
- Deduplication (if collision resistance is not required)
3.3 SHA-1 - DEPRECATED
SHA-1 (Secure Hash Algorithm 1):
├── Output: 160 bits (40 hex characters)
├── Designed by: NSA (1995)
├── Status: DEPRECATED, collision attacks demonstrated
└── Example: da39a3ee5e6b4b0d3255bfef95601890afd80709 (empty string)
SHAttered Attack (2017)
Google and CWI Amsterdam demonstrated the first practical SHA-1 collision:
Attack details:
├── Two different PDF files with identical SHA-1 hash
├── Computational cost: ~2^63.1 SHA-1 computations
├── Cost: ~$110,000 in cloud computing
├── Result: Forged SSL certificate possible
└── Impact: All major browsers and OS vendors deprecated SHA-1
SHA-1 deprecation timeline:
- 2017: SHAttered attack demonstrated
- 2017: Google Chrome stopped trusting SHA-1 certificates
- 2018: All major browsers blocked SHA-1 certificates
- 2019: NIST officially deprecated SHA-1
- 2021: Git added SHA-1 collision detection
3.4 SHA-2 Family - CURRENT STANDARD
SHA-2 is a family of hash functions designed by the NSA and published in 2001.
| Algorithm | Output Size | Block Size | Word Size | Security Level |
|---|---|---|---|---|
| SHA-224 | 224 bits | 512 bits | 32 bits | ~112 bits |
| SHA-256 | 256 bits | 512 bits | 32 bits | ~128 bits |
| SHA-384 | 384 bits | 1024 bits | 64 bits | ~192 bits |
| SHA-512 | 512 bits | 1024 bits | 64 bits | ~256 bits |
SHA-256 example:
Input: "The quick brown fox jumps over the lazy dog"
Output: d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592
Input: "The quick brown fox jumps over the lazy cog" (changed 'd' to 'c')
Output: ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c
Note the complete output change from a single character difference (avalanche effect).
SHA-2 is considered secure and is the current standard for:
- TLS/SSL certificates
- Bitcoin and cryptocurrency
- Digital signatures
- Password hashing (as a building block)
- HMAC construction
3.5 SHA-3 (Keccak)
SHA-3 is based on the Keccak algorithm, selected by NIST in 2012 after a public competition.
Keccak Sponge Construction
Traditional hash (SHA-2): Merkle-Damgård construction
Input → [Compression] → [Compression] → ... → Output
SHA-3 (Keccak): Sponge construction
Input → ┌─────────────────┐
│ Absorption │ State: 1600 bits
│ Phase │ Capacity: 2×security bits
└────────┬────────┘
│
┌────────▼────────┐
│ Squeezing │
│ Phase │ Output: variable length
└─────────────────┘
SHA-3 variants:
| Algorithm | Output Size | Capacity | Security Level |
|---|---|---|---|
| SHA3-224 | 224 bits | 448 bits | ~112 bits |
| SHA3-256 | 256 bits | 512 bits | ~128 bits |
| SHA3-384 | 384 bits | 768 bits | ~192 bits |
| SHA3-512 | 512 bits | 1024 bits | ~256 bits |
Why SHA-3 exists:
- Different internal structure than SHA-2 (defense in depth)
- Resistant to length extension attacks (unlike SHA-2)
- Variable output length natively supported
- Simpler design, easier to analyze
3.6 Password Hashing
NEVER store passwords as plain text or with fast hashes (MD5, SHA-256). Password hashing requires specialized algorithms designed to be slow and memory-intensive.
Why Slow Hashing Matters
Fast hash (SHA-256):
├── Speed: ~10 billion hashes/second (GPU)
├── Attack: Try 10 billion passwords per second
└── Result: 8-character alphanumeric password cracked in minutes
Slow hash (bcrypt, cost 12):
├── Speed: ~10,000 hashes/second (GPU)
├── Attack: Try 10,000 passwords per second
└── Result: Same password takes years to crack
The goal: Make brute force attacks computationally infeasible.
bcrypt
bcrypt parameters:
├── Algorithm: Based on Blowfish cipher
├── Cost factor: 4-31 (doubling work each level)
├── Recommended cost: 12-14 (adjust based on hardware)
├── Salt: 128-bit random salt (embedded in output)
├── Output: 24 bytes (184 bits)
└── Format: $2a$<cost>$<22-char-salt><31-char-hash>
Example:
$2a$12$WpznMDVI609YzfPgd2d6Yekm1TEXcV0QfByQmeHnBFlAp/zwBQCLq
Breaking down the example:
├── $2a$ → bcrypt version
├── 12 → cost factor (2^12 = 4096 iterations)
├── WpznMDVI609YzfPgd2d6Ye → 22-char base64 salt
└── km1TEXcV0QfByQmeHnBFlAp/zwBQCLq → 31-char base64 hash
bcrypt advantages:
- ✅ Built-in salt (no salt management needed)
- ✅ Adjustable cost factor
- ✅ Resistant to GPU attacks (to some extent)
- ✅ Widely supported
bcrypt limitations:
- ⚠️ 72-byte input limit (truncation)
- ⚠️ Not memory-hard (vulnerable to ASIC attacks)
scrypt
scrypt parameters:
├── N: CPU/memory cost parameter (power of 2)
├── r: Block size parameter
├── p: Parallelization parameter
├── Salt: Random salt (16+ bytes recommended)
├── Output: Variable length key
└── Key feature: Memory-hard (requires large memory allocation)
Recommended parameters (2024):
├── N = 2^14 (16384) or higher
├── r = 8
├── p = 1
└── Salt = 16 bytes
scrypt advantages:
- ✅ Memory-hard (resistant to GPU/ASIC attacks)
- ✅ No input length limit
- ✅ Parallelizable
Argon2 - RECOMMENDED
Argon2 won the Password Hashing Competition (PHC) in 2015 and is the current recommended password hashing algorithm.
Argon2 variants:
├── Argon2d: Fastest, most resistant to GPU attacks
│ ⚠️ Vulnerable to side-channel attacks
├── Argon2i: Slower, resistant to side-channel attacks
│ ⚠️ Less resistant to GPU attacks
└── Argon2id: (Recommended) Hybrid approach
├── First half: Argon2i (side-channel resistant)
└── Second half: Argon2d (GPU resistant)
Argon2 parameters:
├── Memory: 64 MB - 1 GB (more is better)
├── Iterations: 3+ (more is better)
├── Parallelism: 1-4 (number of threads)
├── Salt: 16 bytes minimum
└── Output: 32 bytes (256 bits) recommended
Recommended parameters (general purpose):
├── Memory: 64 MB
├── Iterations: 3
├── Parallelism: 4
└── Variant: Argon2id
Argon2 advantages:
- ✅ Memory-hard (resistant to GPU/ASIC attacks)
- ✅ Configurable memory, time, and parallelism
- ✅ Resistant to side-channel attacks (Argon2i/Argon2id)
- ✅ Modern, well-analyzed, widely adopted
- ✅ Default in many modern systems
Password Hashing Algorithm Comparison
| Algorithm | Memory-Hard | GPU-Resistant | Side-Channel Safe | Recommended |
|---|---|---|---|---|
| MD5 | ❌ | ❌ | N/A | ❌ NEVER |
| SHA-256 | ❌ | ❌ | N/A | ❌ NEVER |
| bcrypt | ❌ | ⚠️ Partial | ✅ | ✅ Good |
| scrypt | ✅ | ✅ | ✅ | ✅ Good |
| Argon2id | ✅ | ✅ | ✅ | ✅ Best |
3.7 Hash Cracking Techniques
Rainbow Tables
Concept:
├── Precomputed chain of hash → password → hash → password...
├── Trade storage for computation time
├── Effective against unsalted hashes
└── Useless against properly salted hashes
Example chain:
P1 → Hash(P1) → Reduction → P2 → Hash(P2) → Reduction → P3 → Hash(P3)
Store only: (P1, Hash(P3))
To crack H:
1. Apply reduction to H → P'
2. Hash(P') → H'
3. Check if H' matches any stored endpoint
4. If yes, replay the chain from the stored start
Why salt defeats rainbow tables:
- Each password gets a unique salt
- Attacker needs separate rainbow table for each salt
- Storage requirements become infeasible
Dictionary Attacks
Process:
├── 1. Obtain hash to crack
├── 2. Load wordlist (common passwords, breached databases)
├── 3. For each word in wordlist:
│ a. Apply common mutations (leet speak, capitalization, numbers)
│ b. Hash the candidate password
│ c. Compare with target hash
├── 4. If match found → password cracked
└── 5. If no match → try larger wordlist or brute force
Common wordlists:
├── rockyou.txt (14 million passwords from 2009 breach)
├── rockyou-forensics.txt (expanded version)
├── SecLists (comprehensive collection)
├── crackstation.net (2.3 billion unique passwords)
└── custom wordlists from engagement context
Brute Force Attacks
Search space calculation:
Charset | Size | 8 chars | 10 chars | 12 chars
-----------------|---------|---------------|---------------|-------------
Lowercase | 26 | 2.1 × 10^11 | 1.4 × 10^14 | 9.5 × 10^16
Lower+Upper | 52 | 5.3 × 10^13 | 1.4 × 10^17 | 3.9 × 10^19
Alphanumeric | 62 | 2.2 × 10^14 | 8.4 × 10^17 | 3.2 × 10^21
All printable | 95 | 6.3 × 10^15 | 6.3 × 10^19 | 6.3 × 10^23
At 10 billion hashes/sec (GPU):
├── 8 lowercase: ~21 seconds
├── 8 mixed case: ~1.7 years
├── 10 lowercase: ~4.5 years
├── 10 mixed case: ~4,400 years
└── 12+ any charset: effectively impossible
Rule-Based Attacks (Masks)
Common password patterns and mask attacks:
Pattern: Word + Number
Mask: ?l?l?l?l?l?l?l?l?d?d
Example: password12, summer2024
Pattern: Capitalized word + Number + Symbol
Mask: ?u?l?l?l?l?l?l?d?d?s
Example: Password12!, Summer2024!
Pattern: Leet speak substitutions
Rules: a→@, e→3, i→1, o→0, s→$, t→7
Example: p@ssw0rd, s3cur1ty
hashcat mask examples:
├── ?l?l?l?l?l?l?l?l → 8 lowercase letters
├── ?u?l?l?l?l?l?l?d?d → Capital + 6 lowercase + 2 digits
├── ?a?a?a?a?a?a?a?a → 8 alphanumeric
└── ?l?l?l?l?l?l?l?l?d?d?s?s → 8 lowercase + 2 digits + 2 symbols
4. Digital Certificates and PKI
4.1 X.509 Certificate Structure
X.509 Certificate (simplified ASN.1 structure):
Certificate ::= SEQUENCE {
tbsCertificate TBSCertificate, -- To Be Signed
signatureAlgorithm AlgorithmIdentifier,
signatureValue BIT STRING
}
TBSCertificate ::= SEQUENCE {
version [0] EXPLICIT Version DEFAULT v1,
serialNumber CertificateSerialNumber,
signature AlgorithmIdentifier,
issuer Name, -- Issuing CA
validity Validity,
notBefore Time,
notAfter Time,
subject Name, -- Certificate owner
subjectPublicKeyInfo SubjectPublicKeyInfo,
algorithm AlgorithmIdentifier,
subjectPublicKey BIT STRING,
issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
extensions [3] EXPLICIT Extensions OPTIONAL
}
Common Extensions:
├── Basic Constraints (CA:TRUE/FALSE)
├── Key Usage (digitalSignature, keyEncipherment, etc.)
├── Extended Key Usage (serverAuth, clientAuth, codeSigning)
├── Subject Alternative Name (DNS, IP, email)
├── Authority Key Identifier
├── Subject Key Identifier
├── CRL Distribution Points
└── Authority Information Access (OCSP)
4.2 Certificate Chain of Trust
Trust Chain:
┌─────────────────────────────────┐
│ Root CA (Self-Signed) │
│ ───────────────────────────── │
│ • Trusted by OS/browser │
│ • Stored in trust store │
│ • Never directly issues certs │
│ • Offline for security │
└──────────────┬──────────────────┘
│ signs
┌──────────────▼──────────────────┐
│ Intermediate CA │
│ ───────────────────────────── │
│ • Signed by Root CA │
│ • Issues certificates to │
│ sub-intermediates or end │
│ entities │
│ • May have multiple levels │
└──────────────┬──────────────────┘
│ signs
┌──────────────▼──────────────────┐
│ Leaf/End-Entity Certificate │
│ ───────────────────────────── │
│ • Signed by Intermediate CA │
│ • Used by servers, clients, │
│ code signing, email │
│ • Contains public key │
│ • Bound to a subject (DNS, IP) │
└─────────────────────────────────┘
Verification:
1. Verify leaf cert signature with intermediate's public key
2. Verify intermediate cert signature with root's public key
3. Root cert is self-signed and trusted by the system
4. Check validity dates, revocation status, and extensions
4.3 CA Hierarchy
Example: Let's Encrypt Hierarchy
ISRG Root X1 (Self-Signed, trusted by systems)
│
├── R3 (Intermediate, issues leaf certs)
│ │
│ └── *.example.com (Leaf certificate)
│
└── E1 (Intermediate, cross-signed)
│
└── *.another.com (Leaf certificate)
Example: Enterprise PKI
Enterprise Root CA (Internal, not publicly trusted)
│
├── Web Server CA (Intermediate)
│ │
│ ├── webserver1.corp.com
│ └── webserver2.corp.com
│
├── Code Signing CA (Intermediate)
│ │
│ └── Developer Workstation Cert
│
└── Email CA (Intermediate)
│
└── user@corp.com S/MIME Cert
4.4 CRL vs OCSP
Certificate revocation is critical when a private key is compromised or a certificate is issued in error.
CRL (Certificate Revocation List)
How CRL works:
├── CA publishes a list of revoked certificate serial numbers
├── List is signed by the CA
├── Clients download and cache the list
└── Check if certificate's serial number is in the list
CRL limitations:
├── ⚠️ Can be very large (millions of entries)
├── ⚠️ Download latency (list may be megabytes)
├── ⚠️ Stale data (list updated periodically, not real-time)
├── ⚠️ Privacy concerns (reveals which certs you're checking)
└── ⚠️ Many clients don't check CRLs by default
OCSP (Online Certificate Status Protocol)
How OCSP works:
├── Client sends query to OCSP responder: "Is cert X valid?"
├── Responder checks with CA and returns: good / revoked / unknown
├── Response is signed by the CA or delegated responder
└── Client validates the response signature
OCSP advantages:
├── ✅ Real-time revocation checking
├── ✅ Small response (single certificate status)
└── ✅ More efficient than downloading full CRL
OCSP limitations:
├── ⚠️ Privacy: Responder knows which sites you visit
├── ⚠️ Availability: If responder is down, connection may fail
└── ⚠️ Latency: Additional round-trip required
OCSP Stapling (improvement):
├── Server periodically queries OCSP responder
├── Server "staples" the signed response to TLS handshake
├── Client verifies the stapled response
├── ✅ Preserves privacy (CA doesn't see which clients connect)
├── ✅ Faster (no additional round-trip)
└── ✅ More reliable (works even if OCSP responder is down)
4.5 Self-Signed Certificates
Self-Signed Certificate:
├── Issuer = Subject (the certificate signs itself)
├── Not signed by any CA
├── Not trusted by default by browsers/OS
└── Uses cases:
├── Internal/testing environments
├── Development servers
├── Root CA certificates (by definition self-signed)
└── IoT devices with certificate pinning
Security considerations:
├── ⚠️ No chain of trust to a trusted root
├── ⚠️ Browsers show security warnings
├── ⚠️ Vulnerable to MITM if client accepts any self-signed cert
└── ✅ Acceptable in controlled internal environments
4.6 Certificate Pinning
Certificate Pinning (HPKP - deprecated, but concept remains):
Concept:
├── Application "pins" a specific certificate or public key
├── Even if a trusted CA issues a fraudulent cert, it will be rejected
├── Used by high-value targets (Google, Facebook, etc.)
Implementation:
├── Pin the public key hash (SHA-256) in the application
├── On connection, verify the server's cert matches the pinned key
├── Optionally include backup pins for key rotation
Modern approaches:
├── Public Key Pinping (Expect-CT header)
├── Certificate Transparency monitoring
└── Application-level pinning (mobile apps)
⚠️ HPKP was deprecated (2018) due to self-DOS risks:
If a pinned key is lost and no backup exists, the site becomes
inaccessible until the pin expires.
5. TLS/SSL
5.1 TLS Handshake (TLS 1.2) - Step by Step
Complete TLS 1.2 Handshake:
Client Server
│ │
│─── ClientHello ──────────────►│
│ • TLS version (1.2) │
│ • Random (32 bytes) │
│ • Session ID │
│ • Cipher suites │
│ • Compression methods │
│ • Extensions (SNI, etc.) │
│ │
│◄─── ServerHello ─────────────│
│ • TLS version (1.2) │
│ • Random (32 bytes) │
│ • Session ID │
│ • Selected cipher suite │
│ • Selected compression │
│ │
│◄─── Certificate ─────────────│
│ • Server certificate │
│ • Intermediate certs │
│ (no root - client has it)│
│ │
│◄─── ServerKeyExchange ───────│ (if needed)
│ • DH/ECDH parameters │
│ • Signature of parameters│
│ │
│◄─── CertificateRequest ──────│ (if client auth needed)
│ │
│◄─── ServerHelloDone ─────────│
│ │
│─── Certificate ──────────────►│ (if client auth)
│ • Client certificate │
│ │
│─── ClientKeyExchange ────────►│
│ • DH/ECDH public value │
│ (or pre-master secret │
│ encrypted with server's │
│ public key) │
│ │
│─── CertificateVerify ────────►│ (if client auth)
│ • Signature of handshake │
│ │
│─── ChangeCipherSpec ─────────►│
│ │
│─── Finished ─────────────────►│
│ • MAC of all handshake │
│ messages so far │
│ │
│ │ ← Both sides now compute:
│ │ Pre-master secret → Master secret
│ │ → Session keys
│ │
│◄─── ChangeCipherSpec ────────│
│ │
│◄─── Finished ────────────────│
│ • MAC of all handshake │
│ messages so far │
│ │
│═══ Encrypted Application Data ═════│
│ │
Key Derivation in TLS 1.2
Pre-master secret generation methods):
├── RSA: Client generates random, encrypts with server's public key
├── DH: Both sides compute shared secret from DH exchange
└── ECDH: Both sides compute shared secret from ECDH exchange
Master secret derivation:
master_secret = PRF(pre_master_secret, "master secret",
client_random + server_random)
Where PRF uses both HMAC-SHA256 and HMAC-MD5 (combined)
Session keys derivation:
key_block = PRF(master_secret, "key expansion",
server_random + client_random)
key_block contains:
├── Client MAC key
├── Server MAC key
├── Client write key (encryption)
├── Server write key (encryption)
├── Client write IV
└── Server write IV
5.2 TLS 1.3 - Major Improvements
TLS 1.3 Handshake (1-RTT):
Client Server
│ │
│─── ClientHello ──────────────►│
│ • TLS 1.3 │
│ • KeyShare (client's ECDH │
│ public key) │
│ • PSK (if resuming) │
│ │
│◄─── ServerHello ─────────────│
│ • TLS 1.3 │
│ • KeyShare (server's ECDH│
│ public key) │
│ • Selected PSK (if any) │
│ │
│◄─── [Encrypted] ─────────────│
│ • Certificate │
│ • CertificateVerify │
│ • Finished │
│ │
│─── [Encrypted] ──────────────►│
│ • Finished │
│ │
│═══ Encrypted Application Data ═════│
TLS 1.3 0-RTT (early data):
Client Server
│ │
│─── ClientHello + Early Data ──►│
│ • PSK + application data │
│ │
│◄─── ServerHello ─────────────│
│ • Accept/reject 0-RTT │
│ │
│═══ Encrypted Application Data ═════│
TLS 1.2 vs TLS 1.3 Comparison
| Feature | TLS 1.2 | TLS 1.3 |
|---|---|---|
| Handshake RTTs | 2 RTT (full), 1 RTT (resume) | 1 RTT (full), 0 RTT (resume) |
| Key Exchange | RSA, DH, ECDH | ECDH only (RSA removed) |
| Forward Secrecy | Optional (DHE/ECDHE) | Mandatory |
| Cipher Suites | 30+ (many insecure) | 5 (all secure) |
| Hash Algorithms | MD5, SHA-1, SHA-256 | SHA-256 only |
| MAC | HMAC (separate) | AEAD only (integrated) |
| Compression | Supported | Removed (CRIME attack) |
| RSA Key Transport | Supported | Removed |
| Static DH/RSA | Supported | Removed |
| Handshake Encryption | Partial | All handshake after ServerHello |
| Protocol Version | Explicit negotiation | Version fallback protection |
TLS 1.3 Cipher Suites
| Cipher Suite | Key Exchange | AEAD | Hash |
|---|---|---|---|
| TLS_AES_128_GCM_SHA256 | ECDHE | AES-128-GCM | SHA-256 |
| TLS_AES_256_GCM_SHA384 | ECDHE | AES-256-GCM | SHA-384 |
| TLS_CHACHA20_POLY1305_SHA256 | ECDHE | ChaCha20-Poly1305 | SHA-256 |
| TLS_AES_128_CCM_SHA256 | ECDHE | AES-128-CCM | SHA-256 |
| TLS_AES_128_CCM_8_SHA256 | ECDHE | AES-128-CCM-8 | SHA-256 |
5.3 Common TLS Vulnerabilities
POODLE (Padding Oracle On Downgraded Legacy Encryption)
Attack: POODLE (CVE-2014-3566)
├── Target: SSL 3.0
├── Type: Padding oracle attack
├── Method: Force downgrade to SSL 3.0, exploit CBC padding
├── Impact: Decrypt one byte per ~256 requests
├── Mitigation: Disable SSL 3.0 entirely
└── Status: SSL 3.0 is now universally disabled
BEAST (Browser Exploit Against SSL/TLS)
Attack: BEAST (CVE-2011-3389)
├── Target: TLS 1.0 CBC modes
├── Type: Chosen-plaintext attack
├── Method: Exploit predictable IV in CBC mode
├── Impact: Decrypt HTTP cookies via browser
├── Mitigation: Use TLS 1.1+, use TLS-record splitting
└── Status: TLS 1.0 is now deprecated
Heartbleed
Attack: Heartbleed (CVE-2014-0160)
├── Target: OpenSSL heartbeat extension
├── Type: Buffer over-read (information disclosure)
├── Method: Request more data than sent in heartbeat payload
├── Impact: Read up to 64KB of server memory per request
│ • Private keys
│ • Session cookies
│ • User credentials
├── Mitigation: Update OpenSSL to patched version
├── Affected: OpenSSL 1.0.1 through 1.0.1f
└── Status: One of the most critical vulnerabilities in history
CRIME (Compression Ratio Info-leak Made Easy)
Attack: CRIME (2012)
├── Target: TLS compression, HTTP compression
├── Type: Compression side-channel
├── Method: Inject data, observe compressed size changes
├── Impact: Decrypt session cookies byte by byte
├── Mitigation: Disable TLS compression
└── Status: TLS compression removed in TLS 1.3
Additional TLS Vulnerabilities
| Vulnerability | CVE | Target | Impact | Mitigation |
|---|---|---|---|---|
| FREAK | 2015-0204 | Export-grade DH | Downgrade to 512-bit DH | Disable export ciphers |
| Logjam | 2015-4000 | DH key exchange | Downgrade to 512-bit DH | Use 2048+ bit DH or ECDH |
| DROWN | 2016-0800 | SSLv2 | Decrypt TLS traffic | Disable SSLv2 completely |
| ROBOT | 2017-3439 | RSA key transport | Forged decryption | Disable RSA key exchange |
| Sweet32 | 2016-2183 | 64-bit block ciphers | Plaintext recovery | Disable 3DES, RC4 |
| Lucky13 | 2013-0169 | TLS CBC MAC | Timing side-channel | Use AEAD ciphers |
5.4 Testing TLS Configurations
Manual testing with OpenSSL:
# Connect to a server and view certificate
openssl s_client -connect example.com:443
# View certificate details
openssl s_client -connect example.com:443 -showcerts
# Test specific TLS version
openssl s_client -connect example.com:443 -tls1_2
openssl s_client -connect example.com:443 -tls1_3
# Test specific cipher suite
openssl s_client -connect example.com:443 -cipher ECDHE-RSA-AES256-GCM-SHA384
# Check certificate chain
openssl s_client -connect example.com:443 -servername example.com
# Test SNI
openssl s_client -connect example.com:443 -servername example.com
# View supported protocols and ciphers
openssl ciphers -v 'ALL'
6. OSCP Exam Relevance
6.1 Hash Identification and Cracking
Hash cracking is one of the most common tasks in the OSCP exam. You will encounter hashes in:
- Windows SAM database extracts
- Linux /etc/shadow files
- Database dumps
- Configuration files
- Challenge files
Common Hash Formats You’ll Encounter
| Hash Type | Example | Identifier | hashcat Mode | John Mode |
|---|---|---|---|---|
| MD5 | 5f4dcc3b5aa765d61d8327deb882cf99 |
32 hex chars | 0 | md5 |
| SHA-1 | 5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8 |
40 hex chars | 100 | sha1 |
| SHA-256 | 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8 |
64 hex chars | 1400 | sha256 |
| SHA-512 | cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e |
128 hex chars | 1700 | sha512 |
| NTLM | 5f4dcc3b5aa765d61d8327deb882cf99 |
32 hex chars | 1000 | nt |
| LM Hash | aad3b435b51404eeaad3b435b51404ee |
32 hex chars | 3000 | lm |
| bcrypt | $2a$12$WpznMDVI609YzfPgd2d6Yekm1TEXcV0QfByQmeHnBFlAp/zwBQCLq |
Starts with $2a$, $2b$, $2y$ | 3200 | bcrypt |
| MD5($pass.$salt) | salt:hash |
Colon-separated | 10 | md5($pass.$salt) |
| SHA-256($pass.$salt) | salt:hash |
Colon-separated | 140 | sha256($pass.$salt) |
| Kerberos 5 TGS | $krb5tgs$23$... |
Starts with $krb5tgs$ | 13100 | krb5tgs |
| Kerberos 5 AS-REP | $krb5asrep$... |
Starts with $krb5asrep$ | 18200 | krb5asrep |
| DPAPI master key | Various | Context-dependent | 6900 | - |
| Zip (AES) | Archive file | .zip extension | 19600 | zip |
| 7-Zip | Archive file | .7z extension | 11600 | 7zip |
Hash Identification Process
Step 1: Look at the hash format
├── Starts with $ → Likely salted hash (bcrypt, SHA-256 crypt, etc.)
├── 32 hex chars → MD5 or NTLM
├── 40 hex chars → SHA-1
├── 64 hex chars → SHA-256
├── 128 hex chars → SHA-512
├── Contains : → Likely salted hash
└── Contains $ → Likely modern hash format
Step 2: Use hash-identifier
├── Run: hash-identifier
├── Paste the hash
├── Review possible matches
└── Cross-reference with context
Step 3: Use hashcat --help
├── Check mode numbers for identified hash type
└── Verify with: hashcat -m <mode> --example
Step 4: Try cracking
├── Start with dictionary attack
├── Move to rule-based attack
└── Last resort: brute force (if short enough)
6.2 SSL/TLS Testing
Common OSCP TLS tasks:
1. Check for weak configurations:
testssl.sh https://target.com
2. Enumerate supported ciphers:
openssl s_client -connect target.com:443 -cipher ALL -v
3. Check for SSLv3/TLS 1.0 support:
openssl s_client -connect target.com:443 -ssl3
openssl s_client -connect target.com:443 -tls1
4. Extract certificate:
openssl s_client -connect target.com:443 -showcerts < /dev/null
5. Check certificate details:
openssl x509 -in cert.pem -text -noout
6. Test for Heartbleed:
testssl.sh --heartbleed https://target.com
7. Check certificate chain:
openssl s_client -connect target.com:443 -showcerts
6.3 Certificate Manipulation
Common OSCP certificate tasks:
1. Extract certificate from a server:
openssl s_client -connect target.com:443 -showcerts < /dev/null \
| openssl x509 -out target.crt
2. View certificate details:
openssl x509 -in target.crt -text -noout
3. Check certificate validity:
openssl x509 -in target.crt -dates -noout
4. Extract public key from certificate:
openssl x509 -in target.crt -pubkey -noout > pubkey.pem
5. Create self-signed certificate:
openssl req -x509 -newkey rsa:2048 -keyout key.pem \
-out cert.pem -days 365 -nodes
6. Create CA-signed certificate:
# Create CA
openssl req -x509 -newkey rsa:4096 -keyout ca-key.pem \
-out ca-cert.pem -days 3650 -nodes
# Create CSR
openssl req -newkey rsa:2048 -keyout server-key.pem \
-out server.csr -nodes
# Sign with CA
openssl x509 -req -in server.csr -CA ca-cert.pem \
-CAkey ca-key.pem -CAcreateserial -out server-cert.pem -days 365
7. Check if certificate is revoked:
openssl x509 -in cert.pem -text -noout | grep -A 5 "CRL Distribution"
6.4 Cryptographic Weaknesses in CTF Challenges
Common crypto challenges in OSCP/CTF:
1. Weak hash algorithms
├── MD5 collision exploitation
├── SHA-1 collision exploitation
└── Rainbow table attacks on unsalted hashes
2. Weak encryption
├── ECB mode pattern analysis
├── Known-plaintext attacks
├── Padding oracle attacks
└── Key reuse vulnerabilities
3. Weak key management
├── Default/hardcoded keys
├── Weak random number generation
├── Key derivation without salt
└── Reused keys across systems
4. Certificate issues
├── Self-signed certificates accepted blindly
├── Expired certificates
├── Weak signature algorithms (SHA-1)
└── Certificate pinning bypass
5. Protocol weaknesses
├── SSL/TLS downgrade attacks
├── Weak cipher suite selection
├── Missing forward secrecy
└── Heartbleed-like vulnerabilities
7. Practical Examples
7.1 OpenSSL Commands
Encryption and Decryption
# AES-256-CBC encryption
openssl enc -aes-256-cbc -salt -in plaintext.txt -out encrypted.bin -pass pass:MySecretPassword
# AES-256-CBC decryption
openssl enc -aes-256-cbc -d -in encrypted.bin -out decrypted.txt -pass pass:MySecretPassword
# AES-256-GCM encryption (requires OpenSSL 1.1.1+)
openssl enc -aes-256-gcm -in plaintext.txt -out encrypted.bin -pass pass:MySecretPassword
# RSA encryption
openssl rsautl -encrypt -inkey public.pem -in plaintext.txt -out encrypted.bin
# RSA decryption
openssl rsautl -decrypt -inkey private.pem -in encrypted.bin -out decrypted.txt
# Encrypt file with password (high-level, recommended)
openssl pkeyutl -encrypt -pubin -inkey public.pem -in plaintext.txt -out encrypted.bin
# Generate random bytes
openssl rand -hex 32
Hashing
# MD5 hash
echo -n "password" | openssl md5
# Output: 5f4dcc3b5aa765d61d8327deb882cf99
# SHA-256 hash
echo -n "password" | openssl sha256
# Output: 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8
# SHA-512 hash
echo -n "password" | openssl sha512
# SHA-3-256 hash (OpenSSL 1.1.1+)
echo -n "password" | openssl sha3-256
# File hash
openssl sha256 file.txt
# HMAC-SHA256
echo -n "message" | openssl dgst -sha256 -hmac "secret_key"
Certificate Management
# Generate RSA private key
openssl genrsa -out private.key 2048
# Generate ECC private key (P-256)
openssl ecparam -genkey -name prime256v1 -out private_ec.key
# Generate Ed25519 private key (OpenSSL 1.1.1+)
openssl genpkey -algorithm ED25519 -out private_ed25519.key
# Extract public key from private key
openssl rsa -in private.key -pubout -out public.key
# Generate CSR (Certificate Signing Request)
openssl req -new -key private.key -out request.csr -subj "/CN=example.com/O=Example Inc/C=US"
# Create self-signed certificate
openssl req -x509 -newkey rsa:2048 -keyout private.key -out certificate.crt \
-days 365 -nodes -subj "/CN=example.com"
# View certificate details
openssl x509 -in certificate.crt -text -noout
# Check certificate expiry
openssl x509 -in certificate.crt -noout -dates
# Verify certificate against CA
openssl verify -CAfile ca.crt certificate.crt
# Convert certificate formats
# PEM to DER
openssl x509 -in cert.pem -outform der -out cert.der
# DER to PEM
openssl x509 -in cert.der -inform der -outform pem -out cert.pem
# PKCS#12 (PFX) creation
openssl pkcs12 -export -out certificate.pfx -inkey private.key -in certificate.crt \
-certfile ca.crt -passout pass:export_password
# PKCS#12 extraction
openssl pkcs12 -in certificate.pfx -out extracted.pem -passin pass:export_password \
-passout pass:extract_password
# Check private key matches certificate
openssl x509 -noout -modulus -in certificate.crt | openssl md5
openssl rsa -noout -modulus -in private.key | openssl md5
# Both should produce the same hash
TLS Testing
# Full connection test
openssl s_client -connect example.com:443
# With SNI
openssl s_client -connect example.com:443 -servername example.com
# Test specific TLS version
openssl s_client -connect example.com:443 -tls1_2
openssl s_client -connect example.com:443 -tls1_3
# Test specific cipher
openssl s_client -connect example.com:443 -cipher ECDHE-RSA-AES256-GCM-SHA384
# List all supported ciphers
openssl ciphers -v 'ALL'
# Check certificate chain
openssl s_client -connect example.com:443 -showcerts
# Extract certificate
openssl s_client -connect example.com:443 -showcerts < /dev/null \
| openssl x509 -out example.com.crt
# Test OCSP stapling
openssl s_client -connect example.com:443 -status
7.2 Hashcat Command Examples
# Basic syntax
hashcat -m <mode> -a <attack> <hash_file> <wordlist>
# MD5 crack with dictionary
hashcat -m 0 -a 0 hashes.txt rockyou.txt
# NTLM crack with dictionary
hashcat -m 1000 -a 0 ntlm_hashes.txt rockyou.txt
# bcrypt crack with dictionary
hashcat -m 3200 -a 0 bcrypt_hashes.txt rockyou.txt
# SHA-256 crack with rules
hashcat -m 1400 -a 0 sha256_hashes.txt rockyou.txt -r rules/best64.rule
# Mask attack (8 lowercase letters)
hashcat -m 0 -a 3 hashes.txt ?l?l?l?l?l?l?l?l
# Mask attack (Capital + 6 lowercase + 2 digits)
hashcat -m 1000 -a 3 ntlm_hashes.txt ?u?l?l?l?l?l?l?d?d
# Hybrid attack (wordlist + mask)
hashcat -m 0 -a 6 hashes.txt rockyou.txt ?d?d?d?d
# Brute force with custom charset
hashcat -m 0 -a 3 hashes.txt -1 ?l?a ?1?1?1?1?1?1?1?1
# GPU optimization flags
hashcat -m 1000 -a 0 hashes.txt rockyou.txt \
--optimize \
--force \
-w 3 \
--session my_session
# Resume interrupted attack
hashcat -m 1000 -a 0 hashes.txt rockyou.txt --restore
# Show cracked passwords
hashcat -m 1000 -a 0 hashes.txt rockyou.txt --show
# Benchmark hashcat speed
hashcat -b -m 1000
# Crack single hash directly
hashcat -m 0 -a 0 5f4dcc3b5aa765d61d8327deb882cf99 rockyou.txt
# Zip file crack
hashcat -m 19600 -a 0 protected.zip rockyou.txt
# 7-Zip crack
hashcat -m 11600 -a 0 archive.7z rockyou.txt
# Kerberos 5 TGS-REP crack
hashcat -m 13100 -a 0 krb5tgs_hash.txt rockyou.txt
# Kerberos 5 AS-REP crack (no pre-auth)
hashcat -m 18200 -a 0 asrep_hash.txt rockyou.txt
# WPA/WPA2 handshake crack
hashcat -m 22000 -a 0 handshake.hccapx rockyou.txt
# Common hashcat modes reference:
# 0 = MD5
# 10 = MD5 ($salt.$pass)
# 100 = SHA-1
# 1400 = SHA-256
# 1700 = SHA-512
# 1000 = NTLM
# 3000 = LM
# 3200 = bcrypt
# 1800 = SHA-512 crypt ($6$)
# 1200 = SHA-256 crypt ($5$)
# 11600 = 7-Zip
# 19600 = Zip (AES)
# 22000 = WPA/WPA2 (PMK)
# 13100 = Kerberos 5 TGS-REP
# 18200 = Kerberos 5 AS-REP
7.3 John the Ripper Usage
# Basic syntax
john <hash_file> [options]
# Auto-detect hash type and crack
john hashes.txt
# Specify hash format
john --format=NT hashes.txt
john --format=sha256crypt hashes.txt
john --format=bcrypt hashes.txt
# Use custom wordlist
john --wordlist=/usr/share/wordlists/rockyou.txt hashes.txt
# Use rules
john --wordlist=/usr/share/wordlists/rockyou.txt --rules hashes.txt
# Show cracked passwords
john --show hashes.txt
# Incremental (brute force) mode
john --incremental hashes.txt
# Session management
john --session=my_session hashes.txt
john --restore=my_session
# Crack Windows SAM database
john --format=nt sam_hashes.txt
# Crack Linux shadow file
john /etc/shadow
# Crack ZIP file
zip2john protected.zip > zip_hash.txt
john zip_hash.txt
# Crack KeePass database
keepass2john database.kdbx > kp_hash.txt
john kp_hash.txt
# Crack PDF password
pdf2john protected.pdf > pdf_hash.txt
john pdf_hash.txt
# Custom rules
john --wordlist=wordlist.txt --rule=Capitalize,AppendDigits hashes.txt
# Benchmark
john --test
# Common John formats:
# NT = Windows NTLM
# md5 = Raw MD5
# sha1 = Raw SHA-1
# sha256 = Raw SHA-256
# sha512 = Raw SHA-512
# bcrypt = bcrypt ($2a$, $2b$, $2y$)
# sha256crypt = Linux SHA-256 ($5$)
# sha512crypt = Linux SHA-512 ($6$)
# descrypt = Unix DES crypt
# md5crypt = Unix MD5 crypt ($1$)
7.4 testssl.sh Usage
# Basic scan
testssl.sh https://example.com
# Hostname instead of URL
testssl.sh example.com
# Specific port
testssl.sh example.com:8443
# All tests (comprehensive)
testssl.sh --all example.com
# Quick test
testssl.sh --quick example.com
# Test specific features
testssl.sh --ssl2 example.com # SSL 2.0
testssl.sh --ssl3 example.com # SSL 3.0
testssl.sh --tls1_0 example.com # TLS 1.0
testssl.sh --tls1_1 example.com # TLS 1.1
testssl.sh --tls1_2 example.com # TLS 1.2
testssl.sh --tls1_3 example.com # TLS 1.3
# Cipher suite testing
testssl.sh --ciphers example.com
# Certificate testing
testssl.sh --certs example.com
# Vulnerability testing
testssl.sh --heartbleed example.com
testssl.sh --poodle example.com
testssl.sh --poodletls example.com
testssl.sh --freak example.com
testssl.sh --logjam example.com
testssl.sh --drown example.com
testssl.sh --robot example.com
# Output to file
testssl.sh --html > report.html example.com
testssl.sh --json > report.json example.com
testssl.sh --txt > report.txt example.com
# Color output control
testssl.sh --color 0 example.com # No color
testssl.sh --color 1 example.com # Color (default)
# Ignore return codes
testssl.sh --ignore-return-code example.com
# Effective SSL check (what browsers accept)
testssl.sh --eff example.com
8. Lab Exercises
Lab 1: Hash Cracking Lab
Objective: Practice identifying and cracking various hash types.
Setup
# Create practice hashes
echo -n "password123" | openssl md5 > md5_hash.txt
echo -n "password123" | openssl sha1 > sha1_hash.txt
echo -n "password123" | openssl sha256 > sha256_hash.txt
# Generate bcrypt hash
python3 -c "import bcrypt; print(bcrypt.hashpw(b'password123', bcrypt.gensalt(rounds=12)).decode())" > bcrypt_hash.txt
# Generate NTLM hash (using impacket)
python3 -c "from impacket.crypto import NTOWFv1; print(NTOWFv1('password123').hex())" > ntlm_hash.txt
Exercises
Exercise 1.1: Identify Hash Types
# Use hash-identifier to identify each hash
hash-identifier
# Paste each hash and note the possible types
# Verify with hashcat
hashcat -m 0 --example # MD5 example
hashcat -m 100 --example # SHA-1 example
hashcat -m 1400 --example # SHA-256 example
hashcat -m 3200 --example # bcrypt example
hashcat -m 1000 --example # NTLM example
Exercise 1.2: Dictionary Attack
# Crack MD5 with dictionary
hashcat -m 0 md5_hash.txt /usr/share/wordlists/rockyou.txt
# Crack NTLM with dictionary
hashcat -m 1000 ntlm_hash.txt /usr/share/wordlists/rockyou.txt
# Crack with John the Ripper
john --wordlist=/usr/share/wordlists/rockyou.txt md5_hash.txt
john --show md5_hash.txt
Exercise 1.3: Rule-Based Attack
# Apply common mutations
hashcat -m 0 md5_hash.txt /usr/share/wordlists/rockyou.txt \
-r /usr/share/hashcat/rules/best64.rule
# John with built-in rules
john --wordlist=/usr/share/wordlists/rockyou.txt --rules md5_hash.txt
Exercise 1.4: Mask Attack
# Crack 8-character lowercase password
hashcat -m 0 -a 3 md5_hash.txt ?l?l?l?l?l?l?l?l
# Crack password with pattern: Word + 2 digits
hashcat -m 1000 -a 6 ntlm_hash.txt /usr/share/wordlists/rockyou.txt ?d?d
Lab 2: TLS Testing Lab
Objective: Analyze and test TLS configurations of target systems.
Exercises
Exercise 2.1: Basic TLS Analysis
# Connect and analyze
openssl s_client -connect target.com:443 -servername target.com
# Note:
# - TLS version used
# - Cipher suite negotiated
# - Certificate chain
# - Server name indication
Exercise 2.2: Comprehensive TLS Scan
# Full testssl.sh scan
testssl.sh --all target.com
# Analyze results:
# - Which protocols are supported?
# - Which cipher suites are offered?
# - Are there any vulnerabilities?
# - Is the certificate valid and properly configured?
Exercise 2.3: Weak Configuration Testing
# Test for old protocol support
openssl s_client -connect target.com:443 -ssl3 2>/dev/null | grep "Protocol"
openssl s_client -connect target.com:443 -tls1 2>/dev/null | grep "Protocol"
openssl s_client -connect target.com:443 -tls1_1 2>/dev/null | grep "Protocol"
# Test for weak ciphers
openssl s_client -connect target.com:443 -cipher 'RC4:DES:3DES:NULL:eNULL:aNULL'
# Test for export ciphers
openssl s_client -connect target.com:443 -cipher 'EXPORT'
Exercise 2.4: Certificate Analysis
# Extract and analyze certificate
openssl s_client -connect target.com:443 -showcerts < /dev/null \
| openssl x509 -out target.crt
openssl x509 -in target.crt -text -noout
# Check:
# - Issuer and subject
# - Validity period
# - Key size and algorithm
# - Signature algorithm
# - Extensions (SAN, key usage, etc.)
# - CRL and OCSP endpoints
Lab 3: Certificate Creation Lab
Objective: Create a complete PKI infrastructure with root CA, intermediate CA, and server certificates.
Exercises
Exercise 3.1: Create Root CA
# Create directory structure
mkdir -p ca/{private,certs,newcerts,crl}
touch ca/index.txt
echo 1000 > ca/serial
# Create OpenSSL config
cat > ca/openssl.cnf << 'EOF'
[ca]
default_ca = CA_default
[CA_default]
dir = /path/to/ca
certs = $dir/certs
crl_dir = $dir/crl
new_certs_dir = $dir/newcerts
database = $dir/index.txt
serial = $dir/serial
RANDFILE = $dir/private/.rand
private_key = $dir/private/ca.key
certificate = $dir/certs/ca.crt
crlnumber = $dir/crlnumber
crl = $dir/crl/ca.crl
crl_extensions = crl_ext
default_crl_days = 30
default_md = sha256
name_opt = ca_default
cert_opt = ca_default
default_days = 375
preserve = no
policy = policy_strict
[policy_strict]
countryName = match
stateOrProvinceName = match
organizationName = match
organizationalUnitName = optional
commonName = supplied
emailAddress = optional
[req]
default_bits = 4096
distinguished_name = req_distinguished_name
string_mask = utf8only
default_md = sha256
x509_extensions = v3_ca
[req_distinguished_name]
countryName = Country Name (2 letter code)
stateOrProvinceName = State or Province Name
localityName = Locality Name
0.organizationName = Organization Name
organizationalUnitName = Organizational Unit Name
commonName = Common Name
emailAddress = Email Address
[v3_ca]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true
keyUsage = critical, digitalSignature, cRLSign, keyCertSign
[v3_intermediate_ca]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:true, pathlen:0
keyUsage = critical, digitalSignature, cRLSign, keyCertSign
EOF
# Generate Root CA key
openssl genrsa -out ca/private/ca.key 4096
# Generate Root CA certificate
openssl req -config ca/openssl.cnf \
-key ca/private/ca.key \
-new -x509 -days 7300 -sha256 \
-extensions v3_ca \
-out ca/certs/ca.crt \
-subj "/C=US/ST=State/L=City/O=MyOrg/OU=CA/CN=MyOrg Root CA"
Exercise 3.2: Create Intermediate CA
# Generate Intermediate CA key
openssl genrsa -out ca/private/intermediate.key 4096
# Generate Intermediate CA CSR
openssl req -config ca/openssl.cnf \
-key ca/private/intermediate.key \
-new -sha256 \
-out ca/certs/intermediate.csr \
-subj "/C=US/ST=State/L=City/O=MyOrg/OU=CA/CN=MyOrg Intermediate CA"
# Sign Intermediate CA with Root CA
openssl ca -config ca/openssl.cnf \
-extensions v3_intermediate_ca \
-days 375 -notext -md sha256 \
-in ca/certs/intermediate.csr \
-out ca/certs/intermediate.crt \
-batch
Exercise 3.3: Create Server Certificate
# Generate server key
openssl genrsa -out ca/private/server.key 2048
# Generate server CSR
openssl req -config ca/openssl.cnf \
-key ca/private/server.key \
-new -sha256 \
-out ca/certs/server.csr \
-subj "/C=US/ST=State/L=City/O=MyOrg/OU=IT/CN=server.myorg.com"
# Create server extensions config
cat > ca/server_ext.cnf << 'EOF'
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = server.myorg.com
DNS.2 = www.server.myorg.com
IP.1 = 192.168.1.100
EOF
# Sign server certificate with Intermediate CA
openssl ca -config ca/openssl.cnf \
-extensions server_ext \
-days 375 -notext -md sha256 \
-in ca/certs/server.csr \
-out ca/certs/server.crt \
-batch
Exercise 3.4: Verify Certificate Chain
# Create chain file
cat ca/certs/intermediate.crt ca/certs/ca.crt > ca/certs/chain.crt
# Verify server certificate against chain
openssl verify -CAfile ca/certs/ca.crt -untrusted ca/certs/intermediate.crt \
ca/certs/server.crt
# View full chain
openssl verify -show_chain -CAfile ca/certs/ca.crt \
-untrusted ca/certs/intermediate.crt ca/certs/server.crt
9. Key Tools
Tool Summary Table
| Tool | Purpose | Key Commands |
|---|---|---|
| openssl | Encryption, hashing, certificates, TLS testing | enc, dgst, x509, s_client, req, genrsa |
| hashcat | GPU-accelerated password recovery | -m <mode> -a <attack> <hash> <wordlist> |
| john | CPU-based password recovery | john <hash>, john --format=<fmt>, john --wordlist=<wl> |
| testssl.sh | TLS/SSL configuration testing | testssl.sh --all <host> |
| sslscan | TLS cipher suite enumeration | sslscan <host>:<port> |
| hash-identifier | Hash type identification | hash-identifier |
| tshark | Network traffic analysis (TLS) | tshark -Y tls -r capture.pcap |
Detailed Tool References
OpenSSL
# Encryption/Decryption
openssl enc -<cipher> [-e|-d] [-in file] [-out file] [-pass pass:<password>]
# Hashing
openssl dgst -<algorithm> [file]
openssl <algorithm> [file]
# Certificate operations
openssl x509 -in cert.pem -text -noout # View certificate
openssl x509 -in cert.pem -dates -noout # Check dates
openssl x509 -req -in csr.pem -CA ca.pem -CAkey ca.key -out cert.pem # Sign CSR
openssl req -new -key key.pem -out csr.pem # Generate CSR
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 # Self-signed
# Key generation
openssl genrsa -out key.pem 2048 # RSA key
openssl ecparam -genkey -name prime256v1 -out key.pem # ECC key
# TLS testing
openssl s_client -connect host:port [-servername host] [-tls1_2] [-cipher suite]
Hashcat
# Attack modes (-a):
# 0 = Dictionary
# 1 = Combination
# 3 = Brute-force (mask)
# 6 = Dictionary + Mask (wordlist first)
# 7 = Dictionary + Mask (wordlist second)
# Common options:
# --force Ignore warnings
# --optimize Use optimized kernels
# -w <level> Workload (1=low, 2=normal, 3=high, 4=nightmare)
# -s <offset> Start offset
# -l <length> Attack length
# --session <name> Session name
# --restore Restore session
# --show Show cracked hashes
# -O Optimize for newer GPUs
# Rule files location:
# /usr/share/hashcat/rules/
# Common rules: best64.rule, one2rule.rule, torrent.rule
John the Ripper
# Common options:
# --wordlist=<file> Use custom wordlist
# --format=<format> Specify hash format
# --rules Apply default rules
# --incremental Brute force mode
# --show Show cracked passwords
# --session=<name> Session name
# --restore=<name> Restore session
# --test Benchmark mode
# --pot=<file> Pot file location (stores cracked passwords)
# Default wordlist: /usr/share/john/password.lst
# Default rules: Built-in (WORD, word, CAP1, etc.)
# Pot file: ~/.john/john.pot
testssl.sh
# Installation
wget --no-check-certificate https://raw.githubusercontent.com/drwetter/testssl.sh/master/testssl.sh
chmod +x testssl.sh
# Common options:
# --all All tests
# --quick Quick test
# --ciphers Cipher suites only
# --certs Certificates only
# --protocols Protocols only
# --compression Compression test
# --ocsp OCSP test
# --heartbleed Heartbleed test
# --poodle POODLE test
# --eff Effective SSL (what browsers accept)
# --html HTML output
# --json JSON output
# --color 0|1 Disable/enable color
sslscan
# Installation
sudo apt install sslscan
# Usage
sslscan target.com:443
sslscan --show-certificate target.com:443
sslscan --no-fallback target.com:443
hash-identifier
# Installation
sudo apt install hash-identifier
# Usage
hash-identifier
# Paste hash when prompted
# Review possible matches
tshark (TLS Analysis)
# Capture TLS traffic
tshark -i eth0 -Y "tls" -w capture.pcap
# Analyze captured TLS traffic
tshark -r capture.pcap -Y "tls.handshake" -T fields -e tls.handshake.type
tshark -r capture.pcap -Y "tls.handshake.cipher_suite" -T fields -e tls.handshake.cipher_suite
# Decrypt TLS traffic (requires pre-master secret log)
export SSLKEYLOGFILE=/tmp/sslkeylog.log
tshark -r capture.pcap -o "tls.keylog_file:/tmp/sslkeylog.log"
# Extract certificate information
tshark -r capture.pcap -Y "x509sat" -T fields -e x509sat.rdnId
10. Exam Tips
Quick Hash Identification
Hash Length → Likely Type:
├── 32 hex chars → MD5 or NTLM
│ └── Check context: Windows = NTLM, Linux/other = MD5
├── 40 hex chars → SHA-1
├── 64 hex chars → SHA-256
├── 128 hex chars → SHA-512
├── Starts with $1$ → MD5 crypt (Unix)
├── Starts with $5$ → SHA-256 crypt (Unix)
├── Starts with $6$ → SHA-512 crypt (Unix)
├── Starts with $2a$, $2b$, $2y$ → bcrypt
├── Starts with $krb5tgs$ → Kerberos TGS
├── Starts with $krb5asrep$ → Kerberos AS-REP
├── 32 hex chars, all lowercase, from Windows → NTLM
└── 32 hex chars, first 16 = aad3b435b51404ee → LM Hash (empty password)
Efficient Cracking Strategy
Step-by-step approach for exam:
1. IDENTIFY the hash type
├── Use hash-identifier
├── Check length and format
└── Consider the context (OS, service, file type)
2. START with dictionary attack
├── Use rockyou.txt first
├── If on Windows target, try common Windows passwords
└── Command: hashcat -m <mode> -a 0 hash.txt rockyou.txt
3. APPLY rules if dictionary fails
├── Use best64.rule for common mutations
└── Command: hashcat -m <mode> -a 0 hash.txt rockyou.txt -r best64.rule
4. TRY mask attack for short passwords
├── If you know the pattern (e.g., 8 chars, alphanumeric)
└── Command: hashcat -m <mode> -a 3 hash.txt ?a?a?a?a?a?a?a?a
5. USE John the Ripper as alternative
├── john --wordlist=rockyou.txt hash.txt
└── john --wordlist=rockyou.txt --rules hash.txt
6. CONSIDER context clues
├── Username as password base
├── Company name, location, dates
├── Previous passwords found on the system
└── Password policy information
7. LAST RESORT: brute force
├── Only if password is short (≤8 chars)
└── Use hashcat with GPU for speed
Time-Saving Tips
⏱️ Exam time savers:
1. Pre-load wordlists on attack machine
├── Copy rockyou.txt to a fast drive
└── Keep SecLists handy
2. Use hashcat over John for speed
├── GPU acceleration is much faster
└── John is good for formats hashcat doesn't support
3. Crack multiple hashes at once
├── Put all hashes in one file
└── hashcat cracks them all simultaneously
4. Use --session to resume
├── If you need to switch tasks
└── hashcat --restore brings it back
5. Check for default/common passwords first
├── password, password123, admin, toor
└── Service defaults (postgres, mysql, etc.)
6. Look for password reuse
├── If you crack one password, try it everywhere
└── Check /etc/passwd, config files, databases
7. Use online resources (if allowed)
├── crackstation.net for quick lookup
└── Hashes.com for common hashes
Common Exam Scenarios
Scenario 1: Linux password cracking
├── Extract shadow file: cat /etc/shadow
├── Identify hash type (usually $6$ = SHA-512 crypt)
├── Crack: hashcat -m 1800 shadow.txt rockyou.txt
└── Alternative: john /etc/shadow
Scenario 2: Windows NTLM cracking
├── Extract SAM: secretsdump.py or procdump + samdump2
├── Hash format: NTLM (32 hex chars)
├── Crack: hashcat -m 1000 ntlm.txt rockyou.txt
└── Alternative: john --format=NT ntlm.txt
Scenario 3: Database password cracking
├── Identify hash type from database schema
├── Common: MD5, SHA-1, bcrypt
├── Crack with appropriate mode
└── Check for unsalted hashes (easier to crack)
Scenario 4: Kerberos cracking
├── AS-REP roasting: GetNPUsers.py -format hashcat
├── TGS-REP roasting: GetUserSPNs.py -format hashcat
├── Crack AS-REP: hashcat -m 18200 asrep.txt rockyou.txt
└── Crack TGS-REP: hashcat -m 13100 tgs.txt rockyou.txt
11. Cross-References
Related Topics
| Topic | Reference | Connection |
|---|---|---|
| Password Attacks | 01-intro-cybersecurity/0X-password-attacks.md |
Hash cracking is a core password attack technique |
| CIA Triad | 01-intro-cybersecurity/0X-cia-triad.md |
Cryptography provides Confidentiality, Integrity, Authentication |
| Network Security | 01-intro-cybersecurity/0X-network-security.md |
TLS/SSL is fundamental to secure network communications |
| Web Application Security | 02-web-applications/0X-tls-ssl.md |
TLS misconfigurations are common web vulnerabilities |
| Active Directory Attacks | 04-active-directory/0X-kerberos-attacks.md |
Kerberos ticket cracking uses hashcat/John |
| Post-Exploitation | 05-post-exploitation/0X-credential-dumping.md |
Credential dumping produces hashes for cracking |
| Linux Privilege Escalation | 03-linux-privesc/0X-shadow-file.md |
/etc/shadow contains password hashes |
| Windows Privilege Escalation | 04-windows-privesc/0X-sam-database.md |
SAM database contains NTLM hashes |
Key Concepts Map
Cryptography
├── Symmetric Encryption
│ ├── AES (ECB, CBC, CTR, GCM)
│ ├── ChaCha20-Poly1305
│ └── 3DES (deprecated)
│
├── Asymmetric Encryption
│ ├── RSA
│ ├── ECC (P-256, Ed25519)
│ ├── Diffie-Hellman
│ └── Digital Signatures
│
├── Hashing
│ ├── MD5 (broken)
│ ├── SHA-1 (deprecated)
│ ├── SHA-2 (current standard)
│ ├── SHA-3 (alternative)
│ └── Password Hashing (bcrypt, Argon2)
│
├── PKI & Certificates
│ ├── X.509 Structure
│ ├── CA Hierarchy
│ ├── CRL/OCSP
│ └── Certificate Pinning
│
├── TLS/SSL
│ ├── Handshake Process
│ ├── Cipher Suites
│ ├── TLS 1.2 vs 1.3
│ └── Vulnerabilities
│
└── Practical Attacks
├── Hash Cracking
├── TLS Testing
├── Certificate Manipulation
└── Cryptographic Weakness Exploitation
Summary
Cryptography is a foundational pillar of cybersecurity. For the OSCP exam, you need to:
- Identify hash types quickly and accurately
- Crack passwords efficiently using hashcat and John the Ripper
- Test TLS configurations for weaknesses using testssl.sh and OpenSSL
- Understand certificate structures and how to manipulate them
- Recognize cryptographic weaknesses in real-world scenarios
The most important practical skills are hash identification and cracking, as these appear frequently in OSCP machines. Master the workflow: identify → dictionary → rules → mask → brute force.
Last Updated: 2026-09-01 Difficulty: Core Tags: encryption, hashing, tls-ssl, certificates, pki