Chapter 28 Exercises: Cryptography for Hackers

⚠️ Authorization Reminder: All exercises must be performed in your personal lab environment or on systems you have explicit authorization to test. Intercepting or manipulating cryptographic communications on systems you do not own is illegal.


Exercise 28.1: Hash Algorithm Comparison (Beginner)

Objective: Understand the practical differences between hash algorithms.

Tasks: 1. Create a text file containing the sentence "The quick brown fox jumps over the lazy dog" 2. Hash the file with the following algorithms: MD5, SHA-1, SHA-256, SHA-512, BLAKE2b bash md5sum testfile.txt sha1sum testfile.txt sha256sum testfile.txt sha512sum testfile.txt b2sum testfile.txt 3. Change a single character in the file and re-hash with all algorithms. Document the avalanche effect. 4. Time each hash algorithm processing a large file (100MB+): bash dd if=/dev/urandom of=largefile.bin bs=1M count=100 time md5sum largefile.bin time sha256sum largefile.bin 5. Research and document: For each algorithm, what is its current security status? Which are considered broken and why? 6. Use Python's hashlib to programmatically demonstrate hashing (see example-02-hash-demo.py)

Discussion: Why would an attacker prefer to find a system using MD5 over one using SHA-256 for file integrity?


Exercise 28.2: TLS Configuration Assessment (Beginner)

Objective: Learn to assess TLS configurations using industry-standard tools.

Setup: Set up a local web server (Apache or Nginx) with TLS enabled.

Tasks: 1. Configure your web server with a deliberately weak TLS configuration: - Enable TLS 1.0, 1.1, 1.2, and 1.3 - Include weak cipher suites (RC4, DES, 3DES) - Use a 1024-bit RSA key - Create a self-signed certificate 2. Scan the server with testssl.sh: bash testssl.sh https://localhost 3. Scan with sslyze: bash sslyze --regular localhost 4. Scan with Nmap's ssl-enum-ciphers script: bash nmap --script ssl-enum-ciphers -p 443 localhost 5. Document all findings from each tool, noting differences in coverage 6. Reconfigure the server with a hardened TLS configuration (TLS 1.2+ only, AEAD ciphers, 2048+ bit key, proper certificate chain) 7. Re-scan and verify all vulnerabilities are resolved 8. Create a comparison table showing before and after results


Exercise 28.3: Understanding Block Cipher Modes (Beginner-Intermediate)

Objective: Visually demonstrate why ECB mode is insecure.

Tasks: 1. Review the example-02-hash-demo.py code that demonstrates ECB vs CBC encryption 2. Create a simple BMP image (or use any uncompressed image format) with large areas of solid color 3. Encrypt the image data (excluding the BMP header) using: - AES-ECB mode - AES-CBC mode - AES-CTR mode 4. Replace the original image data with each encrypted version (keeping the BMP header intact) 5. Open the encrypted images. The ECB version should reveal visual patterns from the original image. 6. Write a brief explanation of why ECB mode preserves patterns while CBC and CTR do not 7. Research the Adobe breach (Case Study 2) and explain how ECB mode exposed password patterns

Expected Outcome: The ECB-encrypted image will show recognizable shapes from the original, while CBC and CTR produce uniform noise.


Exercise 28.4: Certificate Chain Analysis (Intermediate)

Objective: Analyze and validate TLS certificate chains.

Tasks: 1. Use openssl s_client to connect to five well-known websites and extract their certificate chains: bash echo | openssl s_client -showcerts -connect example.com:443 2>/dev/null | openssl x509 -text -noout 2. For each certificate, document: - Subject and Issuer - Validity period (Not Before / Not After) - Key type and size (RSA 2048, ECC P-256, etc.) - Signature algorithm - Subject Alternative Names (SANs) - Certificate Transparency SCT (Signed Certificate Timestamp) 3. Map the complete chain from end-entity to root CA for at least two sites 4. Use CT log search (crt.sh) to find all certificates issued for a domain you own or control: bash curl -s "https://crt.sh/?q=yourdomain.com&output=json" | jq '.[] | {id, name_value, not_before, not_after, issuer_name}' 5. Identify any certificates with concerning characteristics (weak key, SHA-1 signature, expired) 6. Create a visual diagram of the PKI trust hierarchy for one of the analyzed sites


Exercise 28.5: Padding Oracle Attack Simulation (Intermediate)

Objective: Understand how padding oracle attacks work through a controlled simulation.

Setup: Deploy the PentesterLab "Padding Oracle" exercise or use a custom vulnerable application.

Tasks: 1. Set up a simple web application that encrypts session cookies using AES-CBC with PKCS#7 padding 2. Configure the application to return different error responses for: - Valid padding + valid data: HTTP 200 - Valid padding + invalid data: HTTP 403 - Invalid padding: HTTP 500 3. Confirm the padding oracle exists by modifying the last byte of the ciphertext and observing different responses 4. Use PadBuster to exploit the oracle: bash padbuster http://target/app/login.php <encrypted_cookie> 16 -cookies "auth=<encrypted_cookie>" 5. Document each step of the attack: - How many requests were required? - What was the decrypted plaintext? - Could you forge a new valid ciphertext? 6. Fix the vulnerability by implementing constant-time padding verification and re-test 7. Alternatively, switch to AES-GCM mode and explain why AEAD ciphers eliminate padding oracles


Exercise 28.6: JWT Security Testing (Intermediate)

Objective: Identify and exploit common JWT vulnerabilities.

Setup: Use OWASP WebGoat, PortSwigger Web Security Academy JWT labs, or a custom JWT application.

Tasks: 1. Capture a legitimate JWT from the application and decode it: bash # Using command line echo "<JWT>" | cut -d. -f1 | base64 -d 2>/dev/null echo "<JWT>" | cut -d. -f2 | base64 -d 2>/dev/null Or use jwt.io to decode and inspect 2. None Algorithm Attack: Modify the JWT header to {"alg":"none"}, change the payload (e.g., set role to "admin"), remove the signature, and submit 3. Algorithm Confusion Attack: If the server uses RS256, attempt to change the algorithm to HS256 and sign with the public key 4. Weak Secret Brute-Force: Use hashcat to crack the HMAC secret: bash hashcat -a 0 -m 16500 jwt.txt rockyou.txt 5. JKU/X5U Injection: If the JWT uses JKU, host your own JWK set and modify the JKU URL to point to it 6. Document which attacks succeeded and why 7. Recommend secure JWT implementation practices: - Algorithm verification - Strong signing keys - Proper claim validation - Token expiration


Exercise 28.7: TLS Stripping Attack Lab (Intermediate)

Objective: Demonstrate TLS stripping and the effectiveness of HSTS as a mitigation.

Setup: Kali Linux, victim VM with a web browser, target web server with HTTPS.

Tasks: 1. Configure your target web server with both HTTP and HTTPS (HTTP redirects to HTTPS) 2. Set up ARP spoofing between the victim and the gateway: bash arpspoof -i eth0 -t <victim_ip> <gateway_ip> 3. Run sslstrip: bash sslstrip -l 8080 4. Configure iptables to redirect HTTP traffic: bash iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080 5. From the victim VM, browse to the target website (typing the domain without https://) 6. Observe the sslstrip output -- captured credentials should appear in plaintext 7. Enable HSTS on the web server and re-test: Strict-Transport-Security: max-age=31536000; includeSubDomains; preload 8. After the victim's browser has received the HSTS header, attempt the strip attack again 9. Document why HSTS prevents the attack and discuss HSTS limitations (first-visit problem, preload list)


Exercise 28.8: Protocol Vulnerability Scanning (Intermediate)

Objective: Use automated tools to identify cryptographic protocol vulnerabilities.

Tasks: 1. Set up multiple servers with different TLS configurations: - Server A: Deliberately vulnerable (SSL 3.0 enabled, weak ciphers) - Server B: Modern but imperfect (TLS 1.2 only, missing HSTS) - Server C: Hardened (TLS 1.3 only, HSTS, AEAD ciphers) 2. Scan each server with testssl.sh and record all vulnerabilities 3. Scan with Nmap vulnerability scripts: bash nmap -sV --script ssl-heartbleed,ssl-poodle,ssl-ccs-injection,ssl-dh-params -p 443 target 4. Test for DROWN by checking SSL 2.0 support: bash openssl s_client -connect target:443 -ssl2 5. Check for ROBOT vulnerability: bash python3 robot-detect.py -h target 6. Create a vulnerability report for each server, rating each finding by severity (Critical, High, Medium, Low) 7. Provide specific remediation steps for each finding 8. Compare tool coverage: which vulnerabilities were detected by all tools? Which were only detected by specific tools?


Exercise 28.9: Analyzing TLS with Wireshark (Intermediate)

Objective: Understand TLS handshake mechanics through packet analysis.

Tasks: 1. Start a Wireshark capture on your network interface 2. Browse to several HTTPS websites using different TLS versions 3. Filter for TLS traffic: tls 4. For a TLS 1.2 handshake, identify and document each message: - ClientHello (record the offered cipher suites, extensions, SNI) - ServerHello (record the selected cipher suite) - Certificate (identify the certificate chain) - ServerKeyExchange (if present -- what does this indicate about PFS?) - ClientKeyExchange - ChangeCipherSpec - Finished 5. For a TLS 1.3 handshake, compare: - How many round trips does it take? - Which messages are encrypted? - What cipher suites are available? 6. If possible, capture a 0-RTT (early data) resumption and analyze it 7. Export the server certificate from the capture and analyze it with openssl x509 -text 8. Document the JA3 fingerprint of your browser (Wireshark has a JA3 dissector plugin)


Exercise 28.10: Cryptographic Implementation Review (Advanced)

Objective: Identify cryptographic flaws in application source code.

Tasks: 1. Review the following Python code snippets and identify the cryptographic vulnerability in each:

Snippet A: python from Crypto.Cipher import AES key = b'mysecretkey12345' cipher = AES.new(key, AES.MODE_ECB) ciphertext = cipher.encrypt(pad(plaintext, 16))

Snippet B: python import hashlib password_hash = hashlib.md5(password.encode()).hexdigest() db.store(username, password_hash)

Snippet C: python iv = b'\x00' * 16 # Fixed IV cipher = AES.new(key, AES.MODE_CBC, iv=iv)

Snippet D: python import random key = bytes([random.randint(0, 255) for _ in range(32)])

Snippet E: python token = jwt.encode(payload, secret_key, algorithm='HS256') decoded = jwt.decode(token, secret_key, algorithms=['HS256', 'none'])

  1. For each snippet, document: - The specific vulnerability - The potential impact - The correct implementation
  2. Search a GitHub repository (your own or an open-source project you have permission to review) for similar patterns: bash grep -rn "MODE_ECB\|md5(\|\.md5\b" --include="*.py" /path/to/project/
  3. Create a checklist of cryptographic anti-patterns for code review

Exercise 28.11: Password Hash Cracking Lab (Intermediate)

Objective: Practice cracking various hash types to understand the importance of proper password hashing.

Tasks: 1. Create sample password hashes using different algorithms: python import hashlib, bcrypt passwords = ['password', 'Summer2025!', 'correct-horse-battery-staple', 'x7$kP2mQ9!'] for p in passwords: print(f"MD5: {hashlib.md5(p.encode()).hexdigest()}") print(f"SHA256: {hashlib.sha256(p.encode()).hexdigest()}") print(f"bcrypt: {bcrypt.hashpw(p.encode(), bcrypt.gensalt(rounds=12)).decode()}") 2. Attempt to crack the MD5 and SHA256 hashes using hashcat: bash hashcat -m 0 md5_hashes.txt rockyou.txt # MD5 hashcat -m 1400 sha256_hashes.txt rockyou.txt # SHA256 3. Attempt to crack the bcrypt hashes: bash hashcat -m 3200 bcrypt_hashes.txt rockyou.txt 4. Compare cracking times across algorithms: - How long did each take? - What is the hash rate (hashes per second) for each algorithm? 5. Test the effect of password complexity: - Which passwords were cracked regardless of algorithm? - Which survived even with MD5? 6. Document your findings in a table showing algorithm, password, crack time, and whether it was cracked 7. Write recommendations for password hashing that balance security and performance


Exercise 28.12: Post-Quantum Cryptography Exploration (Advanced)

Objective: Explore post-quantum cryptographic algorithms and their practical implications.

Tasks: 1. Research NIST's post-quantum cryptographic standards (ML-KEM, ML-DSA, SLH-DSA) 2. Install the oqs (Open Quantum Safe) Python library if available, or use OpenSSL 3.x with PQ providers: bash pip install pqcrypto # or equivalent 3. Generate key pairs using a post-quantum algorithm and a classical algorithm 4. Compare key sizes, signature sizes, and encapsulation sizes: | Algorithm | Public Key Size | Secret Key Size | Ciphertext/Signature Size | |-----------|----------------|-----------------|--------------------------| | RSA-2048 | | | | | ECDSA P-256 | | | | | ML-KEM-768 | | | | | ML-DSA-65 | | | | 5. Benchmark the performance: - Key generation time - Encryption/encapsulation time - Decryption/decapsulation time - Signature generation time - Signature verification time 6. Discuss the practical implications of larger key and ciphertext sizes for: - TLS handshakes - Certificate chains - Constrained IoT devices - Network bandwidth


Exercise 28.13: Certificate Transparency Log Mining (Intermediate)

Objective: Use Certificate Transparency logs for reconnaissance and security monitoring.

Tasks: 1. Choose a target domain (one you own or a public organization's domain) 2. Query crt.sh for all certificates: bash curl -s "https://crt.sh/?q=%25.example.com&output=json" | jq -r '.[].name_value' | sort -u 3. Analyze the results: - What subdomains were discovered? - Are there any unexpected or shadow IT subdomains? - What CAs issued certificates for this domain? - Are there any certificates with concerning validity periods? 4. Check for certificate misconfigurations: - Wildcard certificates (security implications?) - Certificates with excessive SANs - Certificates from unusual CAs 5. Set up CT log monitoring for your own domain using tools like certspotter or Facebook's CT monitoring 6. Document how CT log mining fits into the reconnaissance phase of a penetration test


Exercise 28.14: Building a TLS Assessment Script (Advanced)

Objective: Build a custom TLS assessment tool that automates key checks.

Tasks: 1. Review the example-01-tls-analyzer.py code in this chapter's code directory 2. Extend the script to check for: - Supported TLS versions (1.0, 1.1, 1.2, 1.3) - Cipher suite enumeration - Certificate validity and chain - HSTS header presence - Certificate Transparency support - Key exchange type (RSA vs ECDHE -- PFS check) 3. Add severity ratings to each finding 4. Generate a formatted report (text or HTML) 5. Test your script against: - Your deliberately vulnerable lab server - Your hardened lab server - A well-known public website (with permission or within acceptable use) 6. Compare your results with testssl.sh output and identify any discrepancies


Exercise 28.15: Crypto in the Wild: Real-World Audit (Advanced)

Objective: Conduct a comprehensive cryptographic audit of a lab environment mimicking a real engagement.

Scenario: MedSecure has asked you to audit the cryptographic posture of their patient portal, internal API, and email server.

Tasks: 1. Set up three services in your lab: - Web server with HTTPS (patient portal) - API server with JWT authentication - SMTP server with STARTTLS 2. Assess TLS configuration on all three services 3. Review JWT implementation for common vulnerabilities 4. Test SMTP STARTTLS for downgrade attacks: bash openssl s_client -starttls smtp -connect mail:25 5. Check for password hash storage in any accessible databases 6. Look for hardcoded secrets in application configuration files 7. Test certificate validation in any client applications 8. Compile a professional cryptographic assessment report with: - Executive summary - Detailed findings with severity ratings - Evidence (screenshots, tool output) - Remediation recommendations prioritized by risk 9. Present findings as if delivering to MedSecure's CISO, Dr. Sarah Chen


Challenge Exercise: Cryptographic Capture the Flag (Advanced)

Objective: Solve a series of cryptographic challenges that test your understanding of real-world crypto weaknesses.

Challenges (set these up or use an online crypto CTF):

  1. Challenge 1: Weak Hash: You are given an MD5 hash. Crack it using rainbow tables or hashcat.
  2. Challenge 2: ECB Oracle: A web service encrypts user input with AES-ECB. Discover the secret by exploiting the ECB mode.
  3. Challenge 3: Padding Oracle: A web service uses AES-CBC with PKCS#7 padding. Exploit the padding oracle to decrypt a cookie.
  4. Challenge 4: RSA Weak Key: An RSA public key uses a small modulus. Factor it and decrypt the message.
  5. Challenge 5: IV Reuse: Two ciphertexts encrypted with AES-CTR using the same key and nonce. XOR them and recover the plaintexts.
  6. Challenge 6: JWT Forgery: Forge a JWT to gain admin access using the none algorithm or algorithm confusion attack.

Recommended Platforms: CryptoHack (cryptohack.org), CryptoPals (cryptopals.com), PicoCTF crypto challenges.

Scoring: Document your methodology for each challenge, including failed approaches. Understanding why an approach fails is as valuable as finding one that succeeds.