Crypto CTF Helper
A skill for practical cryptography in hacking and CTF contexts. Focus on speed: classify the primitive, identify what you control (oracle/leak/nonce reuse), then apply known attack templates.
When to use this skill
Use this skill when the user:
- Asks about encryption/decryption challenges
- Needs help with CTF crypto problems
- Wants to analyze cryptographic systems
- Is working with hashes, MACs, or KDFs
- Needs help with RSA, ECC, or other public-key crypto
- Is dealing with TLS/certificate issues
- Wants to understand crypto in malware
- Needs to recognize cipher patterns or vulnerabilities
Quick Setup
# Python environment
python3 -m venv .venv && source .venv/bin/activate
# Required libraries
pip install pycryptodome gmpy2 sympy pwntools
# SageMath (essential for lattice/RSA/ECC)
# Download from: https://www.sagemath.org/
CTF Workflow
Step 1: Classify the Primitive
Identify what you're dealing with:
| Pattern |
Likely Primitive |
| Base64, hex strings |
Encoded data |
| Fixed-length blocks (16/32 bytes) |
Block cipher (AES, DES) |
| Variable-length with padding |
Stream cipher or block cipher |
| 32-char hex |
MD5 hash |
| 64-char hex |
SHA-256 hash |
| 128-char hex |
SHA-512 hash |
-----BEGIN RSA |
RSA public key |
-----BEGIN EC |
ECC key |
-----BEGIN CERTIFICATE |
X.509 certificate |
0x3082 prefix |
ASN.1/DER encoded |
Step 2: Identify What You Control
Look for:
- Oracle access: Can you encrypt/decrypt arbitrary data?
- Leakage: Timing, side-channels, error messages?
- Nonce/IV reuse: Same key with same nonce?
- Known plaintext: Do you know part of the message?
- Chosen plaintext/ciphertext: Can you influence input/output?
- Key weaknesses: Small exponents, weak primes, predictable randomness?
Step 3: Apply Attack Template
Match your situation to known attacks:
Symmetric Crypto Attacks
- ECB mode: Look for repeated blocks → pattern leakage
- CBC padding oracle: Manipulate ciphertext, observe padding errors
- Nonce reuse (CTR/GCM): XOR two ciphertexts to recover plaintext
- Stream cipher reuse: XOR keystreams to recover messages
- Meet-in-the-middle: For double encryption
Hash Attacks
- Length extension: Append data to hash (MD5, SHA-1, SHA-256)
- Collision attacks: MD5, SHA-1 (use hashclash, shashcoll)
- Rainbow tables: Precomputed hash lookups
- Brute force: Weak passwords, small keyspaces
RSA Attacks
- Small exponent (e=3): Cube root attack if m^e < n
- Common factor: gcd(n1, n2) reveals shared prime
- Wiener's attack: Small d, continued fractions
- Bleichenbacher: Padding oracle
- Lattice attacks: Coppersmith for partial key knowledge
- Factoring: Pollard's p-1, ECM, GNFS (use yafu, msieve)
ECC Attacks
- Weak curves: Small order, anomalous curves
- Side-channel: Timing, power analysis
- Invalid curve: Point on different curve
- Small subgroup: Force point into small subgroup
Tools Reference
Python Libraries
from Crypto.Cipher import AES, DES, PKCS1_OAEP
from Crypto.Util.number import *
from Crypto.Hash import SHA256, MD5
import gmpy2
import sympy
from pwn import *
Common Utilities
| Task |
Tool |
| Base64/hex decode |
scripts/crypto-decode.py |
| Hash identification |
hashid, scripts/hash-identify.py |
| RSA factoring |
yafu, msieve, factordb.com |
| Hash cracking |
hashcat, john |
| SSL/TLS analysis |
nmap --script ssl-enum-ciphers |
| Certificate inspection |
openssl x509 -text -in cert.pem |
| Lattice attacks |
SageMath, fplll |
Common Patterns
Base64 Detection
import base64
import re
# Standard base64
if re.match(r'^[A-Za-z0-9+/=]+$', data):
try:
decoded = base64.b64decode(data)
except:
pass
# URL-safe base64
if re.match(r'^[A-Za-z0-9_-]+$', data):
try:
decoded = base64.urlsafe_b64decode(data + '==')
except:
pass
Hash Identification
import hashlib
import re
hash_patterns = {
'MD5': (32, r'^[a-f0-9]{32}$'),
'SHA-1': (40, r'^[a-f0-9]{40}$'),
'SHA-256': (64, r'^[a-f0-9]{64}$'),
'SHA-512': (128, r'^[a-f0-9]{128}$'),
}
for name, (length, pattern) in hash_patterns.items():
if re.match(pattern, data):
print(f"Likely {name}")
RSA Helper Functions
from Crypto.Util.number import *
def rsa_decrypt(c, d, n):
"""Decrypt RSA ciphertext"""
m = pow(c, d, n)
return long_to_bytes(m)
def rsa_encrypt(m, e, n):
"""Encrypt with RSA"""
c = pow(bytes_to_long(m), e, n)
return c
def factor_rsa(n, e, c):
"""Factor n and decrypt (use factordb or yafu for large n)"""
# Use external tools for large numbers
pass
Attack Templates
CBC Padding Oracle
def cbc_padding_oracle(oracle, ciphertext):
"""Exploit CBC padding oracle"""
block_size = 16
plaintext = b''
for block_idx in range(len(ciphertext) // block_size - 1, -1, -1):
block = ciphertext[block_idx*block_size:(block_idx+1)*block_size]
prev_block = ciphertext[(block_idx-1)*block_size:block_idx*block_size] if block_idx > 0 else b'\x00' * block_size
for byte_idx in range(block_size - 1, -1, -1):
# ... padding oracle logic
pass
return plaintext
Hash Length Extension
def length_extension(hash_value, original_data, appended_data):
"""Perform hash length extension attack"""
# Works on MD5, SHA-1, SHA-256 (Merkle-Damgard)
from hash_extender import HashExtender
extender = HashExtender(hash_value, original_data)
extended_hash = extender.extend_hash(appended_data)
return extended_hash
RSA Small Exponent Attack
def rsa_small_e_attack(c, n, e=3):
"""Cube root attack for small e"""
if e == 3:
# Try cube root
m = round(c ** (1/e))
if pow(m, e, n) == c:
return long_to_bytes(m)
return None
Best Practices
- Always check for weak randomness: Many crypto challenges fail due to predictable PRNGs
- Look for implementation bugs: Padding errors, timing leaks, side-channels
- Use the right tool: Don't brute force when a mathematical attack exists
- Document your approach: Write down what you tried and why
- Verify your solution: Double-check decrypted output makes sense
Next Steps
For detailed coverage of specific topics, see:
- Symmetric crypto: Block ciphers, stream ciphers, modes of operation
- Hashes, MACs, KDFs: Collision attacks, length extension, HMAC
- Public-key crypto: RSA, ECC, Diffie-Hellman attacks
- TLS and certificates: Protocol vulnerabilities, certificate validation
- Crypto in malware: Obfuscation, key extraction, runtime analysis
- CTF misc: Encoding schemes, custom ciphers, steganography
Scripts
Use the bundled scripts for common tasks:
scripts/crypto-decode.py - Decode various encodings (base64, hex, rot13, etc.)
scripts/hash-identify.py - Identify hash types and attempt cracking
scripts/rsa-helper.py - RSA encryption, decryption, and basic attacks
Run with --help for usage details.
1---2name: crypto-ctf-helper3description: Help with cryptography challenges for CTFs, security research, and hacking. Use this skill whenever the user mentions crypto, encryption, decryption, hashes, RSA, AES, CTF challenges, cryptographic attacks, or anything related to breaking or analyzing cryptographic systems. This includes recognizing cipher types, identifying vulnerabilities, applying known attacks, and working with crypto primitives.4---56# Crypto CTF Helper78A skill for practical cryptography in hacking and CTF contexts. Focus on speed: classify the primitive, identify what you control (oracle/leak/nonce reuse), then apply known attack templates.910## When to use this skill1112Use this skill when the user:13- Asks about encryption/decryption challenges14- Needs help with CTF crypto problems15- Wants to analyze cryptographic systems16- Is working with hashes, MACs, or KDFs17- Needs help with RSA, ECC, or other public-key crypto18- Is dealing with TLS/certificate issues19- Wants to understand crypto in malware20- Needs to recognize cipher patterns or vulnerabilities2122## Quick Setup2324```bash25# Python environment26python3 -m venv .venv && source .venv/bin/activate2728# Required libraries29pip install pycryptodome gmpy2 sympy pwntools3031# SageMath (essential for lattice/RSA/ECC)32# Download from: https://www.sagemath.org/33```3435## CTF Workflow3637### Step 1: Classify the Primitive3839Identify what you're dealing with:4041| Pattern | Likely Primitive |42|---------|------------------|43| Base64, hex strings | Encoded data |44| Fixed-length blocks (16/32 bytes) | Block cipher (AES, DES) |45| Variable-length with padding | Stream cipher or block cipher |46| 32-char hex | MD5 hash |47| 64-char hex | SHA-256 hash |48| 128-char hex | SHA-512 hash |49| `-----BEGIN RSA` | RSA public key |50| `-----BEGIN EC` | ECC key |51| `-----BEGIN CERTIFICATE` | X.509 certificate |52| `0x3082` prefix | ASN.1/DER encoded |5354### Step 2: Identify What You Control5556Look for:57- **Oracle access**: Can you encrypt/decrypt arbitrary data?58- **Leakage**: Timing, side-channels, error messages?59- **Nonce/IV reuse**: Same key with same nonce?60- **Known plaintext**: Do you know part of the message?61- **Chosen plaintext/ciphertext**: Can you influence input/output?62- **Key weaknesses**: Small exponents, weak primes, predictable randomness?6364### Step 3: Apply Attack Template6566Match your situation to known attacks:6768#### Symmetric Crypto Attacks69- **ECB mode**: Look for repeated blocks → pattern leakage70- **CBC padding oracle**: Manipulate ciphertext, observe padding errors71- **Nonce reuse (CTR/GCM)**: XOR two ciphertexts to recover plaintext72- **Stream cipher reuse**: XOR keystreams to recover messages73- **Meet-in-the-middle**: For double encryption7475#### Hash Attacks76- **Length extension**: Append data to hash (MD5, SHA-1, SHA-256)77- **Collision attacks**: MD5, SHA-1 (use hashclash, shashcoll)78- **Rainbow tables**: Precomputed hash lookups79- **Brute force**: Weak passwords, small keyspaces8081#### RSA Attacks82- **Small exponent (e=3)**: Cube root attack if m^e < n83- **Common factor**: gcd(n1, n2) reveals shared prime84- **Wiener's attack**: Small d, continued fractions85- **Bleichenbacher**: Padding oracle86- **Lattice attacks**: Coppersmith for partial key knowledge87- **Factoring**: Pollard's p-1, ECM, GNFS (use yafu, msieve)8889#### ECC Attacks90- **Weak curves**: Small order, anomalous curves91- **Side-channel**: Timing, power analysis92- **Invalid curve**: Point on different curve93- **Small subgroup**: Force point into small subgroup9495## Tools Reference9697### Python Libraries9899```python100from Crypto.Cipher import AES, DES, PKCS1_OAEP101from Crypto.Util.number import *102from Crypto.Hash import SHA256, MD5103import gmpy2104import sympy105from pwn import *106```107108### Common Utilities109110| Task | Tool |111|------|------|112| Base64/hex decode | `scripts/crypto-decode.py` |113| Hash identification | `hashid`, `scripts/hash-identify.py` |114| RSA factoring | `yafu`, `msieve`, `factordb.com` |115| Hash cracking | `hashcat`, `john` |116| SSL/TLS analysis | `nmap --script ssl-enum-ciphers` |117| Certificate inspection | `openssl x509 -text -in cert.pem` |118| Lattice attacks | SageMath, `fplll` |119120## Common Patterns121122### Base64 Detection123```python124import base64125import re126127# Standard base64128if re.match(r'^[A-Za-z0-9+/=]+$', data):129 try:130 decoded = base64.b64decode(data)131 except:132 pass133134# URL-safe base64135if re.match(r'^[A-Za-z0-9_-]+$', data):136 try:137 decoded = base64.urlsafe_b64decode(data + '==')138 except:139 pass140```141142### Hash Identification143```python144import hashlib145import re146147hash_patterns = {148 'MD5': (32, r'^[a-f0-9]{32}$'),149 'SHA-1': (40, r'^[a-f0-9]{40}$'),150 'SHA-256': (64, r'^[a-f0-9]{64}$'),151 'SHA-512': (128, r'^[a-f0-9]{128}$'),152}153154for name, (length, pattern) in hash_patterns.items():155 if re.match(pattern, data):156 print(f"Likely {name}")157```158159### RSA Helper Functions160```python161from Crypto.Util.number import *162163def rsa_decrypt(c, d, n):164 """Decrypt RSA ciphertext"""165 m = pow(c, d, n)166 return long_to_bytes(m)167168def rsa_encrypt(m, e, n):169 """Encrypt with RSA"""170 c = pow(bytes_to_long(m), e, n)171 return c172173def factor_rsa(n, e, c):174 """Factor n and decrypt (use factordb or yafu for large n)"""175 # Use external tools for large numbers176 pass177```178179## Attack Templates180181### CBC Padding Oracle182```python183def cbc_padding_oracle(oracle, ciphertext):184 """Exploit CBC padding oracle"""185 block_size = 16186 plaintext = b''187 188 for block_idx in range(len(ciphertext) // block_size - 1, -1, -1):189 block = ciphertext[block_idx*block_size:(block_idx+1)*block_size]190 prev_block = ciphertext[(block_idx-1)*block_size:block_idx*block_size] if block_idx > 0 else b'\x00' * block_size191 192 for byte_idx in range(block_size - 1, -1, -1):193 # ... padding oracle logic194 pass195 196 return plaintext197```198199### Hash Length Extension200```python201def length_extension(hash_value, original_data, appended_data):202 """Perform hash length extension attack"""203 # Works on MD5, SHA-1, SHA-256 (Merkle-Damgard)204 from hash_extender import HashExtender205 206 extender = HashExtender(hash_value, original_data)207 extended_hash = extender.extend_hash(appended_data)208 return extended_hash209```210211### RSA Small Exponent Attack212```python213def rsa_small_e_attack(c, n, e=3):214 """Cube root attack for small e"""215 if e == 3:216 # Try cube root217 m = round(c ** (1/e))218 if pow(m, e, n) == c:219 return long_to_bytes(m)220 return None221```222223## Best Practices2242251. **Always check for weak randomness**: Many crypto challenges fail due to predictable PRNGs2262. **Look for implementation bugs**: Padding errors, timing leaks, side-channels2273. **Use the right tool**: Don't brute force when a mathematical attack exists2284. **Document your approach**: Write down what you tried and why2295. **Verify your solution**: Double-check decrypted output makes sense230231## Next Steps232233For detailed coverage of specific topics, see:234- **Symmetric crypto**: Block ciphers, stream ciphers, modes of operation235- **Hashes, MACs, KDFs**: Collision attacks, length extension, HMAC236- **Public-key crypto**: RSA, ECC, Diffie-Hellman attacks237- **TLS and certificates**: Protocol vulnerabilities, certificate validation238- **Crypto in malware**: Obfuscation, key extraction, runtime analysis239- **CTF misc**: Encoding schemes, custom ciphers, steganography240241## Scripts242243Use the bundled scripts for common tasks:244- `scripts/crypto-decode.py` - Decode various encodings (base64, hex, rot13, etc.)245- `scripts/hash-identify.py` - Identify hash types and attempt cracking246- `scripts/rsa-helper.py` - RSA encryption, decryption, and basic attacks247248Run with `--help` for usage details.