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.4metadata:5 source: https://skillmd.com/skills/abelrguezr/crypto-ctf-helper6---78# Crypto CTF Helper910A 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.1112## When to use this skill1314Use this skill when the user:15- Asks about encryption/decryption challenges16- Needs help with CTF crypto problems17- Wants to analyze cryptographic systems18- Is working with hashes, MACs, or KDFs19- Needs help with RSA, ECC, or other public-key crypto20- Is dealing with TLS/certificate issues21- Wants to understand crypto in malware22- Needs to recognize cipher patterns or vulnerabilities2324## Quick Setup2526```bash27# Python environment28python3 -m venv .venv && source .venv/bin/activate2930# Required libraries31pip install pycryptodome gmpy2 sympy pwntools3233# SageMath (essential for lattice/RSA/ECC)34# Download from: https://www.sagemath.org/35```3637## CTF Workflow3839### Step 1: Classify the Primitive4041Identify what you're dealing with:4243| Pattern | Likely Primitive |44|---------|------------------|45| Base64, hex strings | Encoded data |46| Fixed-length blocks (16/32 bytes) | Block cipher (AES, DES) |47| Variable-length with padding | Stream cipher or block cipher |48| 32-char hex | MD5 hash |49| 64-char hex | SHA-256 hash |50| 128-char hex | SHA-512 hash |51| `-----BEGIN RSA` | RSA public key |52| `-----BEGIN EC` | ECC key |53| `-----BEGIN CERTIFICATE` | X.509 certificate |54| `0x3082` prefix | ASN.1/DER encoded |5556### Step 2: Identify What You Control5758Look for:59- **Oracle access**: Can you encrypt/decrypt arbitrary data?60- **Leakage**: Timing, side-channels, error messages?61- **Nonce/IV reuse**: Same key with same nonce?62- **Known plaintext**: Do you know part of the message?63- **Chosen plaintext/ciphertext**: Can you influence input/output?64- **Key weaknesses**: Small exponents, weak primes, predictable randomness?6566### Step 3: Apply Attack Template6768Match your situation to known attacks:6970#### Symmetric Crypto Attacks71- **ECB mode**: Look for repeated blocks → pattern leakage72- **CBC padding oracle**: Manipulate ciphertext, observe padding errors73- **Nonce reuse (CTR/GCM)**: XOR two ciphertexts to recover plaintext74- **Stream cipher reuse**: XOR keystreams to recover messages75- **Meet-in-the-middle**: For double encryption7677#### Hash Attacks78- **Length extension**: Append data to hash (MD5, SHA-1, SHA-256)79- **Collision attacks**: MD5, SHA-1 (use hashclash, shashcoll)80- **Rainbow tables**: Precomputed hash lookups81- **Brute force**: Weak passwords, small keyspaces8283#### RSA Attacks84- **Small exponent (e=3)**: Cube root attack if m^e < n85- **Common factor**: gcd(n1, n2) reveals shared prime86- **Wiener's attack**: Small d, continued fractions87- **Bleichenbacher**: Padding oracle88- **Lattice attacks**: Coppersmith for partial key knowledge89- **Factoring**: Pollard's p-1, ECM, GNFS (use yafu, msieve)9091#### ECC Attacks92- **Weak curves**: Small order, anomalous curves93- **Side-channel**: Timing, power analysis94- **Invalid curve**: Point on different curve95- **Small subgroup**: Force point into small subgroup9697## Tools Reference9899### Python Libraries100101```python102from Crypto.Cipher import AES, DES, PKCS1_OAEP103from Crypto.Util.number import *104from Crypto.Hash import SHA256, MD5105import gmpy2106import sympy107from pwn import *108```109110### Common Utilities111112| Task | Tool |113|------|------|114| Base64/hex decode | `scripts/crypto-decode.py` |115| Hash identification | `hashid`, `scripts/hash-identify.py` |116| RSA factoring | `yafu`, `msieve`, `factordb.com` |117| Hash cracking | `hashcat`, `john` |118| SSL/TLS analysis | `nmap --script ssl-enum-ciphers` |119| Certificate inspection | `openssl x509 -text -in cert.pem` |120| Lattice attacks | SageMath, `fplll` |121122## Common Patterns123124### Base64 Detection125```python126import base64127import re128129# Standard base64130if re.match(r'^[A-Za-z0-9+/=]+$', data):131 try:132 decoded = base64.b64decode(data)133 except:134 pass135136# URL-safe base64137if re.match(r'^[A-Za-z0-9_-]+$', data):138 try:139 decoded = base64.urlsafe_b64decode(data + '==')140 except:141 pass142```143144### Hash Identification145```python146import hashlib147import re148149hash_patterns = {150 'MD5': (32, r'^[a-f0-9]{32}$'),151 'SHA-1': (40, r'^[a-f0-9]{40}$'),152 'SHA-256': (64, r'^[a-f0-9]{64}$'),153 'SHA-512': (128, r'^[a-f0-9]{128}$'),154}155156for name, (length, pattern) in hash_patterns.items():157 if re.match(pattern, data):158 print(f"Likely {name}")159```160161### RSA Helper Functions162```python163from Crypto.Util.number import *164165def rsa_decrypt(c, d, n):166 """Decrypt RSA ciphertext"""167 m = pow(c, d, n)168 return long_to_bytes(m)169170def rsa_encrypt(m, e, n):171 """Encrypt with RSA"""172 c = pow(bytes_to_long(m), e, n)173 return c174175def factor_rsa(n, e, c):176 """Factor n and decrypt (use factordb or yafu for large n)"""177 # Use external tools for large numbers178 pass179```180181## Attack Templates182183### CBC Padding Oracle184```python185def cbc_padding_oracle(oracle, ciphertext):186 """Exploit CBC padding oracle"""187 block_size = 16188 plaintext = b''189 190 for block_idx in range(len(ciphertext) // block_size - 1, -1, -1):191 block = ciphertext[block_idx*block_size:(block_idx+1)*block_size]192 prev_block = ciphertext[(block_idx-1)*block_size:block_idx*block_size] if block_idx > 0 else b'\x00' * block_size193 194 for byte_idx in range(block_size - 1, -1, -1):195 # ... padding oracle logic196 pass197 198 return plaintext199```200201### Hash Length Extension202```python203def length_extension(hash_value, original_data, appended_data):204 """Perform hash length extension attack"""205 # Works on MD5, SHA-1, SHA-256 (Merkle-Damgard)206 from hash_extender import HashExtender207 208 extender = HashExtender(hash_value, original_data)209 extended_hash = extender.extend_hash(appended_data)210 return extended_hash211```212213### RSA Small Exponent Attack214```python215def rsa_small_e_attack(c, n, e=3):216 """Cube root attack for small e"""217 if e == 3:218 # Try cube root219 m = round(c ** (1/e))220 if pow(m, e, n) == c:221 return long_to_bytes(m)222 return None223```224225## Best Practices2262271. **Always check for weak randomness**: Many crypto challenges fail due to predictable PRNGs2282. **Look for implementation bugs**: Padding errors, timing leaks, side-channels2293. **Use the right tool**: Don't brute force when a mathematical attack exists2304. **Document your approach**: Write down what you tried and why2315. **Verify your solution**: Double-check decrypted output makes sense232233## Next Steps234235For detailed coverage of specific topics, see:236- **Symmetric crypto**: Block ciphers, stream ciphers, modes of operation237- **Hashes, MACs, KDFs**: Collision attacks, length extension, HMAC238- **Public-key crypto**: RSA, ECC, Diffie-Hellman attacks239- **TLS and certificates**: Protocol vulnerabilities, certificate validation240- **Crypto in malware**: Obfuscation, key extraction, runtime analysis241- **CTF misc**: Encoding schemes, custom ciphers, steganography242243## Scripts244245Use the bundled scripts for common tasks:246- `scripts/crypto-decode.py` - Decode various encodings (base64, hex, rot13, etc.)247- `scripts/hash-identify.py` - Identify hash types and attempt cracking248- `scripts/rsa-helper.py` - RSA encryption, decryption, and basic attacks249250Run with `--help` for usage details.