Metadata-Version: 2.5
Name: fermentanyl
Version: 0.2.0
Summary: A CTF-oriented crypto toolkit for RSA, AES, ECC, DH, hashes and PRNG attacks
Project-URL: Homepage, https://github.com/kiyowa-39/fermentanyl
Project-URL: Documentation, https://github.com/kiyowa-39/fermentanyl/blob/main/docs/index.md
Project-URL: Repository, https://github.com/kiyowa-39/fermentanyl
Project-URL: Issues, https://github.com/kiyowa-39/fermentanyl/issues
Project-URL: Changelog, https://github.com/kiyowa-39/fermentanyl/blob/main/CHANGELOG.md
Author: fermentanyl contributors
License-Expression: MIT
License-File: LICENSE
Keywords: aes,capture-the-flag,classical-ciphers,crc32,cryptography,ctf,ecc,hash-length-extension,prng,rsa
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Security :: Cryptography
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: pycryptodome>=3.20
Requires-Dist: sympy>=1.12
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Requires-Dist: twine>=5; extra == 'dev'
Provides-Extra: fast
Requires-Dist: gmpy2>=2.1; extra == 'fast'
Provides-Extra: lattice
Requires-Dist: fpylll>=0.6; extra == 'lattice'
Description-Content-Type: text/markdown

# Fermentanyl

[![PyPI](https://img.shields.io/pypi/v/fermentanyl.svg)](https://pypi.org/project/fermentanyl/)
[![Python versions](https://img.shields.io/pypi/pyversions/fermentanyl.svg)](https://pypi.org/project/fermentanyl/)
[![CI](https://github.com/kiyowa-39/fermentanyl/actions/workflows/ci.yml/badge.svg)](https://github.com/kiyowa-39/fermentanyl/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

A CTF-oriented crypto toolkit: RSA attacks, block-cipher oracles, elliptic-curve
arithmetic, classical ciphers, hash length extension, PRNG recovery, encoding
chains (Base58/62/85/91, compression, Morse and more), and a small
auto-detection helper. May include grapes.

The API is callback-friendly, so a socket wrapper fits directly into the oracle
attacks, and every attack verifies its result before returning it.

> **Educational use only.** This library deliberately implements attacks and
> weak primitives. It is not hardened for production cryptography and should not
> be used to protect real data.

## Status

- **Alpha** (`0.1.x`). The API is usable but may change between minor releases.
- **Python 3.10+**; CI covers 3.10 through 3.15.
- Base dependencies are `pycryptodome` and `sympy`.
- `gmpy2` is optional and accelerates big-integer roots; a pure-Python fallback
  is always available.
- `fpylll` is optional and required only for `boneh_durfee` and the lattice
  extra. Missing it raises `MissingDependencyError`, never a silent wrong answer.

## The name

`fermentanyl` is a portmanteau of **ferment** and the chemistry suffix
**-anyl** (as in a generic reagent name). It is **not** a drug name and has nothing to do with fentanyl or
pharmacology. If the spelling is awkward in your environment, you can import it under an
alias:

```python
import fermentanyl as ferm
```

## Contents

- [Installation](#installation)
- [Quickstart](#quickstart)
- [Auto-detection](#auto-detection)
- [Command line](#command-line)
- [Callback-driven attacks](#callback-driven-attacks)
- [Failure behavior](#failure-behavior)
- [Scope and limitations](#scope-and-limitations)
- [Aliases](#aliases)
- [Function reference](#function-reference)
- [Documentation](#documentation)
- [Credits and prior art](#credits-and-prior-art)
- [Development](#development)
- [Contributing](#contributing)
- [Security](#security)
- [License](#license)

## Installation

```bash
pip install fermentanyl
```

Optional extras:

```bash
pip install "fermentanyl[fast]"     # gmpy2 for faster big-int operations
pip install "fermentanyl[lattice]"  # fpylll for Boneh-Durfee
pip install "fermentanyl[dev]"      # pytest, ruff, build, twine
```

For a development checkout:

```bash
git clone https://github.com/kiyowa-39/fermentanyl
cd fermentanyl
python -m venv .venv
source .venv/bin/activate
python -m pip install -e ".[dev]"
```

## Quickstart

```python
import hashlib

from fermentanyl import aes, classical, dh, hashes, numtheory, prng, rsa, utils

# Forgiving conversions
n = utils.to_int("0xff00", encoding="hex")
assert utils.to_bytes(n) == b"\xff\x00"

# CRT, including non-coprime moduli
assert numtheory.crt([2, 3], [3, 5]) == (8, 15)

# RSA: recover two factors with Fermat when the primes are close
p, q = rsa.fermat_factor(1009 * 1013)
assert p * q == 1009 * 1013

# Plain small-exponent RSA: m**e did not wrap around n
assert rsa.small_e_root(424242**3, 3) == 424242

# Hastad's broadcast attack (same message, small e)
moduli = [1009 * 1013, 1019 * 1021, 1031 * 1033]
ciphertexts = [pow(424242, 3, n) for n in moduli]
assert rsa.hastad_broadcast(ciphertexts, 3, moduli) == 424242

# AES-ECB detection
key = b"0" * 16
assert aes.detect_ecb(aes.ecb_encrypt(b"A" * 64, key))

# CTR nonce reuse: the keystream cancels and plaintexts XOR together
nonce = b"1" * 8
c1 = aes.ctr_encrypt(b"hello", key, nonce)
c2 = aes.ctr_encrypt(b"world", key, nonce)
assert aes.ctr_recover(c1, c2, b"hello") == b"world"

# Classical cipher
assert classical.caesar_decrypt(classical.caesar_encrypt("hello", 13), 13) == "hello"
assert classical.affine_decrypt(classical.affine_encrypt("hello", 5, 8), 5, 8) == "hello"

# Hash length extension (MD5, SHA-1, SHA-256 and SHA-512)
secret, message = b"pepper", b"user=guest"
old = hashlib.sha256(secret + message).hexdigest()
forged, digest = hashes.sha256_length_extension(message, old, b"&admin=1", len(secret))
assert hashlib.sha256(secret + forged).hexdigest() == digest

# LCG recovery
values = [7, 10, 25, 4, 27]
assert prng.lcg_recover(values, modulus=32) == (5, 7, 32)
assert prng.lcg_next(values, modulus=32) == 14

# ElGamal
p, g, x = 23, 5, 6
c1, c2 = dh.elgamal_encrypt(7, pow(g, x, p), p, g, k=3)
assert dh.elgamal_decrypt(c1, c2, x, p) == 7
```

### Auto-detection

`solve()` is a convenience for triage, not a replacement for choosing an attack:

```python
from fermentanyl import classify, solve

solve("ZmxhZ3tmZXJtZW50YW55bH0=")
# {'kind': 'encoding', 'value': b'flag{fermentanyl}', 'details': {'steps': ['base64']}}

solve("5d41402abc4b2a76b9719d911017c592")
# {'kind': 'hash', 'value': '5d41402abc4b2a76b9719d911017c592',
#  'details': {'candidates': ['MD5', 'NTLM', 'MD4']}}

classify("n = 3233\ne = 17")["kind"]   # "rsa"
```

`kind` is one of `flag`, `rsa_private_key`, `rsa_public_key`,
`rsa_parameters`, `encoding`, `hash`, `caesar`, `xor`, `text`, or `raw`. The
function returns a dictionary with `kind`, `value`, and `details`; it does not
raise when it cannot identify the input. `classify` ranks the likely domain
(`rsa`, `encoding`, `hash`, `ecc`, `symmetric`, `prng`, `classical`, ...) without
solving it.

## Command line

Installing the package creates `ferm`, a small front end for triage and the
registered attacks:

```bash
ferm solve challenge.txt
ferm solve challenge.txt --json --explain
ferm rsa --n 3233 --e 17 --c 2790
ferm rsa --n 3233 --json --verbose
ferm rsa --n 3233 --e 17 --c 2790 --jobs 2
```

`ferm rsa` runs matching registry attacks cheapest-first, verifies their results
and records skipped optional dependencies. `--timeout` and `--budget` enforce
per-attack and global limits; `--jobs` uses worker processes. See
[`docs/cli.md`](docs/cli.md) for the full option list.

Raw challenge files can also be parsed without the CLI:

```python
from fermentanyl.extract import extract_file, extract_rsa
from fermentanyl.flags import find_flags

extract_rsa("n = 0x0ca1\ne = 65537")
extract_file("output.txt")["kind"]
find_flags("the answer is CTF{grapes}")
```

## Callback-driven attacks

Oracle attacks accept plain Python callables, so a socket wrapper fits directly:

```python
from fermentanyl import aes

def check_padding(ciphertext: bytes) -> bool:
    # Send ciphertext to the challenge, return True if it reports valid padding.
    ...

plaintext = aes.cbc_padding_oracle(ciphertext, check_padding)
```

```python
from fermentanyl import rsa

def lsb(ciphertext_int: int) -> int:
    # Send the integer to the challenge, return its decrypted LSB (0 or 1).
    ...

plaintext_int = rsa.lsb_oracle_attack(ciphertext, e, n, lsb)
```

### Oracle parameters

- `aes.cbc_padding_oracle(ciphertext, check_padding, *, iv=None, block_size=16, unpad=True)`
  - When `iv` is `None`, the first `block_size` bytes of `ciphertext` are the IV
    and `check_padding` receives `forged_previous_block + target_block`.
  - When `iv` is supplied, it must be exactly `block_size` bytes and
    `ciphertext` is the raw ciphertext without a prepended IV.
  - `check_padding` returns `True` only for valid PKCS#7 padding.
- `rsa.bleichenbacher_attack(ciphertext, e, n, oracle, *, max_iterations=1_000_000)`
  - `oracle(ciphertext_int) -> bool`; it returns `True` when the integer
    decrypts to a block beginning with `00 02`.
  - Returns the plaintext integer.
- `rsa.lsb_oracle_attack(ciphertext, e, n, oracle, *, iterations=None)`
  - `oracle(ciphertext_int) -> int | bool`; `0`/`False` and `1`/`True` are both
    accepted.
  - Returns the plaintext integer.
- `aes.ecb_byte_at_a_time(encrypt, *, block_size=None, max_secret_len=4096)`
  - `encrypt(attacker_bytes) -> ciphertext_bytes` for
    `attacker_bytes || secret`.
  - Returns the recovered secret bytes.
- `ecc.small_subgroup_attack(oracle, generators)`
  - `oracle(Point) -> Point` computes `d * P` without subgroup validation.
  - `generators` is a sequence of `(point, order)` pairs.
  - Returns `(d_mod_m, m)`.
- `ecc.invalid_curve_attack(oracle, invalid_points)`
  - Same callback shape as `small_subgroup_attack`.
  - Returns `(d_mod_m, m)`.
- `dh.dh_small_subgroup_attack(oracle, generators, modulus)`
  - `oracle(element_int) -> int` computes `element**d mod p`.
  - `generators` is a sequence of `(element, order)` pairs of small or smooth
    order.
  - Returns `(d_mod_m, m)`.

## Failure behavior

The library prefers an explicit exception over a plausible-looking wrong value.
Attacks verify their recovered plaintext, key, or factor before returning.

| Situation | Behavior |
| --- | --- |
| Bad type, length, key size, or impossible argument | `ValueError` |
| Attack precondition not met (wrong exponent, no small root, non-smooth order, ...) | `AttackNotApplicable` (subclass of `ValueError`) |
| Optional dependency missing (`fpylll`) | `MissingDependencyError` (subclass of `ImportError`) |
| Oracle callback fails, contradicts itself, or stalls | `OracleError` |
| Hash cracking or brute force finds no match | `None` |
| `solve()` cannot identify the input | Returns `kind="text"` or `kind="raw"` |

`AttackNotApplicable`, `MissingDependencyError`, and `OracleError` all inherit
from `FermentanylError`, so a challenge script can catch one base class:

```python
from fermentanyl import FermentanylError

try:
    d = rsa.wiener_attack(e, n)
except FermentanylError:
    # Fall through to another attack.
    ...
```

## Scope and limitations

The library intentionally stays dependency-light, so a few advanced attacks are
not included:

- **GCM tag forgery.** `gcm_nonce_reuse` recovers plaintext XOR only. Recovering
  the GHASH key `H` and forging tags needs polynomial root finding over
  `GF(2**128)`.
- **General lattice attacks.** `boneh_durfee` uses `fpylll`, but general
  Coppersmith small roots and biased-nonce ECDSA (HNP) are not implemented.
- **Pairing attacks.** MOV and Frey-Rück reductions are not implemented;
  `singular_curve_dlog` covers the singular-curve case.
- **Smart's attack** for anomalous curves (`#E(F_p) == p`) is not implemented.
- **factordb lookup.** The package makes no network requests.
- **Multi-prime key generation.** `factor_with_private_exponent` factors a
  multi-prime modulus when `(n, e, d)` is known, but `generate_keypair` produces
  two-prime keys.

These omissions are deliberate rather than silent: no function pretends to run
an attack it cannot complete.

## Aliases

These names refer to the same function object; they exist so challenge scripts
can use whichever reads better:

| Alias | Canonical name |
| --- | --- |
| `auto_solve` | `solve` |
| `dictionary_attack` | `crack_hash` |
| `brute_force_attack` | `brute_force_hash` |

`close_prime_factor` is a thin wrapper around `fermat_factor` with a
close-prime-specific error message, not a separate algorithm.

## Function reference

Signatures below omit type annotations for readability. Every function has a
full docstring with types, arguments, return value, and an example.

### `fermentanyl.utils`

| Function | Signature | Returns |
| --- | --- | --- |
| `to_bytes` | `to_bytes(data, *, encoding="utf-8", byteorder="big", length=None)` | `bytes` |
| `to_int` | `to_int(data, *, encoding="utf-8", byteorder="big")` | `int` |
| `to_hex` | `to_hex(data, *, encoding="utf-8", byteorder="big")` | lowercase hex `str` |
| `from_hex` | `from_hex(text)` | `bytes`; accepts spaces, colons, `0x`, odd length |
| `xor_bytes` | `xor_bytes(a, b)` | `bytes`; repeats the shorter operand |
| `repeating_key_xor` | `repeating_key_xor(data, key)` | `bytes` |
| `single_byte_xor` | `single_byte_xor(data, key)` | `bytes` |
| `xor_bruteforce` | `xor_bruteforce(data, *, top=5)` | `list[(key:int, plaintext:bytes, score:float)]` |
| `single_byte_xor_bruteforce` | `single_byte_xor_bruteforce(data, *, top=5)` | same as `xor_bruteforce` |
| `break_repeating_key_xor` | `break_repeating_key_xor(data, *, key_size=None, max_key_size=40, top=5)` | `list[(key:bytes, plaintext:bytes, score:float)]` |
| `hamming_distance` | `hamming_distance(a, b)` | `int` |
| `english_score` | `english_score(data)` | `float` (higher is more English-like) |
| `chunks` | `chunks(data, size)` | `list[bytes]` |
| `printable_ratio` | `printable_ratio(data)` | `float` in `[0, 1]` |
| `looks_like_text` | `looks_like_text(data, threshold=0.9)` | `bool` |

### `fermentanyl.numtheory`

| Function | Signature | Returns |
| --- | --- | --- |
| `egcd` | `egcd(a, b)` | `(g, x, y)` with `a*x + b*y == g` |
| `modinv` | `modinv(a, m)` | `int`; raises `ValueError` if not invertible |
| `gcd`, `lcm` | `gcd(a, b)`, `lcm(a, b)` | `int` |
| `crt` | `crt(residues, moduli)` | `(x, modulus)`; supports non-coprime moduli |
| `is_quadratic_residue` | `is_quadratic_residue(a, p)` | `bool` |
| `modular_sqrt` | `modular_sqrt(a, p)` | one square root `int`; raises if non-residue |
| `iroot` | `iroot(n, k)` | `(floor_root, exact:bool)` |
| `nth_root` | `nth_root(n, k)` | floor `int` root |
| `dlog_bsgs` | `dlog_bsgs(g, h, p, order=None)` | `x` with `g**x == h (mod p)` |
| `dlog_rho` | `dlog_rho(g, h, p, order=None, *, max_restarts=30)` | `x`; lower memory than BSGS |
| `pohlig_hellman` | `pohlig_hellman(g, h, p, *, order=None, factors=None)` | `x` for smooth orders |
| `is_prime` | `is_prime(n)` | `bool` |
| `factorint` | `factorint(n)` | `dict[prime, exponent]` |

### `fermentanyl.rsa`

| Function | Signature | Returns |
| --- | --- | --- |
| `generate_keypair` | `generate_keypair(bits=2048, e=65537)` | `(RSAPublicKey, RSAPrivateKey)` |
| `load_public_key` | `load_public_key(data)` | `RSAPublicKey` |
| `load_private_key` | `load_private_key(data)` | `RSAPrivateKey` |
| `RSAPublicKey` | `RSAPublicKey(n, e)` | `.encrypt_int`, `.encrypt`, `.to_pem`, `.from_pem` |
| `RSAPrivateKey` | `RSAPrivateKey(n, e, d, p=None, q=None)` | `.decrypt_int`, `.decrypt`, `.sign_int`, `.sign`, `.to_pem`, `.from_pem` |
| `recover_primes` | `recover_primes(n, e, d)` | `(p, q)` |
| `factor_with_private_exponent` | `factor_with_private_exponent(n, e, d)` | sorted `list[int]` of all prime factors; handles multi-prime `n` |
| `common_modulus_attack` | `common_modulus_attack(c1, e1, c2, e2, n)` | plaintext `int` |
| `batch_gcd` | `batch_gcd(moduli)` | `dict[modulus, shared_factor]` |
| `hastad_broadcast` | `hastad_broadcast(ciphertexts, e, moduli)` | plaintext `int` |
| `small_e_root` | `small_e_root(ciphertext, e, modulus=None)` | plaintext `int` |
| `wiener_attack` | `wiener_attack(e, n)` | private exponent `d` (`int`) |
| `boneh_durfee` | `boneh_durfee(n, e, *, delta=0.28, m=3)` | private exponent `d`; needs `fpylll` |
| `small_private_exponent_attack` | `small_private_exponent_attack(e, n)` | `d`; Wiener then Boneh-Durfee |
| `fermat_factor` | `fermat_factor(n, *, max_iterations=1_000_000)` | `(p, q)` |
| `close_prime_factor` | `close_prime_factor(n, *, max_iterations=1_000_000)` | `(p, q)`; Fermat wrapper |
| `pollard_p_minus_1` | `pollard_p_minus_1(n, *, bound=100_000, base=2)` | a nontrivial factor `int` |
| `williams_p_plus_1` | `williams_p_plus_1(n, *, bound=100_000, base=3)` | a nontrivial factor `int` |
| `franklin_reiter` | `franklin_reiter(c1, c2, e, n, *, a=1, b=1)` | plaintext `int` for `m` and `a*m+b` |
| `crt_fault_attack` | `crt_fault_attack(n, e, message, faulty_signature, correct_signature=None)` | `(p, q)` |
| `bleichenbacher_attack` | `bleichenbacher_attack(ciphertext, e, n, oracle, *, max_iterations=1_000_000)` | plaintext `int` |
| `lsb_oracle_attack` | `lsb_oracle_attack(ciphertext, e, n, oracle, *, iterations=None)` | plaintext `int` |
| `pkcs1_v15_pad` | `pkcs1_v15_pad(message, length, *, randbytes=os.urandom)` | padded `bytes` |
| `pkcs1_v15_unpad` | `pkcs1_v15_unpad(data)` | unpadded `bytes` |

### `fermentanyl.aes`

| Function | Signature | Returns |
| --- | --- | --- |
| `pkcs7_pad` | `pkcs7_pad(data, block_size=16)` | padded `bytes` |
| `pkcs7_unpad` | `pkcs7_unpad(data, block_size=16)` | unpadded `bytes`; raises on bad padding |
| `is_pkcs7_padded` | `is_pkcs7_padded(data, block_size=16)` | `bool` |
| `ecb_encrypt` | `ecb_encrypt(plaintext, key, *, pad=True)` | `bytes` |
| `ecb_decrypt` | `ecb_decrypt(ciphertext, key, *, unpad=True)` | `bytes` |
| `cbc_encrypt` | `cbc_encrypt(plaintext, key, iv=None, *, pad=True)` | `iv || ciphertext` when `iv` is `None` |
| `cbc_decrypt` | `cbc_decrypt(ciphertext, key, iv=None, *, unpad=True)` | `bytes`; reads prepended IV when `iv` is `None` |
| `ctr_encrypt` | `ctr_encrypt(plaintext, key, nonce=None)` | `nonce || ciphertext` when `nonce` is `None` |
| `ctr_decrypt` | `ctr_decrypt(ciphertext, key, nonce=None)` | `bytes`; reads prepended 8-byte nonce when `nonce` is `None` |
| `gcm_encrypt` | `gcm_encrypt(plaintext, key, nonce=None, *, aad=b"")` | `(nonce, ciphertext, tag)` |
| `gcm_decrypt` | `gcm_decrypt(ciphertext, key, nonce, tag, *, aad=b"")` | `bytes`; raises on tag failure |
| `detect_ecb` | `detect_ecb(ciphertext, block_size=16)` | `bool` |
| `ecb_repeated_blocks` | `ecb_repeated_blocks(ciphertext, block_size=16)` | repeated-block count `int` |
| `cbc_padding_oracle` | `cbc_padding_oracle(ciphertext, check_padding, *, iv=None, block_size=16, unpad=True)` | decrypted `bytes` |
| `ecb_byte_at_a_time` | `ecb_byte_at_a_time(encrypt, *, block_size=None, max_secret_len=4096)` | secret `bytes` |
| `cbc_bit_flip` | `cbc_bit_flip(ciphertext, offset, known, target, *, iv=None, block_size=16)` | forged `bytes` |
| `cbc_bit_flip_iv` | `cbc_bit_flip_iv(iv, ciphertext, offset, known, target, *, block_size=16)` | `(new_iv, new_ciphertext)` |
| `ctr_keystream` | `ctr_keystream(ciphertext, known_plaintext)` | keystream `bytes` |
| `ctr_nonce_reuse` | `ctr_nonce_reuse(ciphertext1, ciphertext2)` | `plaintext1 XOR plaintext2` |
| `ctr_recover` | `ctr_recover(ciphertext1, ciphertext2, known_plaintext)` | the other plaintext `bytes` |
| `ctr_forge` | `ctr_forge(ciphertext, known_plaintext, target_plaintext)` | forged `bytes` |
| `gcm_nonce_reuse` | `gcm_nonce_reuse(ciphertext1, ciphertext2, *, known_plaintext=None)` | XOR, or the other plaintext if one is known |
| `rc4` | `rc4(key, data)` | `bytes` (encrypt/decrypt are the same) |
| `rc4_keystream` | `rc4_keystream(key, length)` | keystream `bytes` |

### `fermentanyl.dh`

| Function | Signature | Returns |
| --- | --- | --- |
| `dh_shared_secret` | `dh_shared_secret(private_key, peer_public, modulus)` | shared secret `int` |
| `elgamal_encrypt` | `elgamal_encrypt(message, public_key, p, g, *, k=None)` | `(c1, c2)` |
| `elgamal_decrypt` | `elgamal_decrypt(c1, c2, private_key, p)` | plaintext `int` |
| `dh_small_subgroup_attack` | `dh_small_subgroup_attack(oracle, generators, modulus)` | `(d_mod_m, m)` |

### `fermentanyl.ecc`

| Function | Signature | Returns |
| --- | --- | --- |
| `EllipticCurve` | `EllipticCurve(p, a, b)` | curve object with `.point`, `.lift_x`, `.is_on_curve`, `.discriminant`, `.is_singular`, `.j_invariant` |
| `Point` | `Point(x, y, curve)` | point with `+`, `-`, scalar `*`, equality, `.is_infinity` |
| `SECP256K1`, `SECP256K1_G`, `SECP256K1_N` | constants | secp256k1 curve, generator, order |
| `P256`, `P256_G`, `P256_N` | constants | NIST P-256 curve, generator, order |
| `ecdsa_hash` | `ecdsa_hash(message)` | SHA-256 digest as `int` |
| `ecdsa_sign` | `ecdsa_sign(message_or_hash, private_key, G, order, *, k=None, hash_bytes=True)` | `(r, s)` |
| `ecdsa_verify` | `ecdsa_verify(message_or_hash, signature, public_key, G, order, *, hash_bytes=True)` | `bool` |
| `ecdsa_known_nonce` | `ecdsa_known_nonce(message_or_hash, signature, nonce, order, *, hash_bytes=True)` | private key `d` |
| `ecdsa_nonce_reuse` | `ecdsa_nonce_reuse(message1, sig1, message2, sig2, order, *, hash_bytes=True)` | private key `d` |
| `ec_dlog_bsgs` | `ec_dlog_bsgs(P, Q, order)` | `k` with `k*P == Q` |
| `pohlig_hellman_ecc` | `pohlig_hellman_ecc(P, Q, order, *, factors=None)` | `k` for smooth orders |
| `singular_curve_dlog` | `singular_curve_dlog(curve, P, Q)` | `k` by mapping to `F_p+` or `F_p*` |
| `small_subgroup_attack` | `small_subgroup_attack(oracle, generators)` | `(d_mod_m, m)` |
| `invalid_curve_for_point` | `invalid_curve_for_point(curve, x, y)` | invalid `EllipticCurve` through `(x, y)` |
| `invalid_curve_attack` | `invalid_curve_attack(oracle, invalid_points)` | `(d_mod_m, m)` |
| `check_curve_weaknesses` | `check_curve_weaknesses(curve, *, order=None, G=None)` | `list[str]` of warnings |

### `fermentanyl.classical`

| Function | Signature | Returns |
| --- | --- | --- |
| `caesar_encrypt`, `caesar_decrypt` | `caesar_encrypt(text, shift)` | `str` |
| `caesar_bruteforce` | `caesar_bruteforce(ciphertext, *, top=5)` | `list[(shift:int, plaintext:str, score:float)]` |
| `vigenere_encrypt`, `vigenere_decrypt` | `vigenere_encrypt(text, key)` | `str` |
| `vigenere_break` | `vigenere_break(ciphertext, *, min_key_len=1, max_key_len=20, top=5)` | `list[(key:str, plaintext:str, score:float)]` |
| `substitution_encrypt`, `substitution_decrypt` | `substitution_encrypt(text, key)` | `str` |
| `substitution_break` | `substitution_break(ciphertext, *, restarts=16, steps=1500, seed=0)` | `(key:str, plaintext:str, score:float)` |
| `affine_encrypt`, `affine_decrypt` | `affine_encrypt(text, a, b)` | `str`; `a` must be coprime to 26 |
| `affine_bruteforce` | `affine_bruteforce(ciphertext, *, top=5)` | `list[(a:int, b:int, plaintext:str, score:float)]` |
| `atbash` | `atbash(text)` | `str` |
| `rail_fence_encrypt`, `rail_fence_decrypt` | `rail_fence_encrypt(text, rails)` | `str` |
| `rail_fence_bruteforce` | `rail_fence_bruteforce(ciphertext, *, max_rails=10, top=5)` | `list[(rails:int, plaintext:str, score:float)]` |
| `playfair_encrypt`, `playfair_decrypt` | `playfair_encrypt(text, key)` | `str`; `J` merges with `I` |
| `bacon_encode`, `bacon_decode` | `bacon_encode(text, *, variant="ab")` | `str`; `variant` is `"ab"` or `"01"` |
| `b64_encode`, `b64_decode` | `b64_encode(data, *, urlsafe=False)` | `str` / `bytes` |
| `b32_encode`, `b32_decode` | `b32_encode(data)` | `str` / `bytes` |
| `b16_encode`, `b16_decode` | `b16_encode(data)` | hex `str` / `bytes` |
| `url_encode`, `url_decode` | `url_encode(data, *, safe="")` | `str` |
| `auto_decode` | `auto_decode(data, *, max_depth=10)` | `(decoded:bytes, steps:list[str])` |

### `fermentanyl.decoders`

| Function | Signature | Returns |
| --- | --- | --- |
| `base58_encode`, `base58_decode` | `base58_encode(data)` | Base58 `str` / `bytes` |
| `base62_encode`, `base62_decode` | `base62_encode(data, *, alphabet=B62_ALPHABET)` | Base62 `str` / `bytes` |
| `base85_encode`, `base85_decode` | `base85_encode(data)` | RFC 1924 Base85 `str` / `bytes` |
| `base91_encode`, `base91_decode` | `base91_encode(data)` | basE91 `str` / `bytes` |
| `binary_encode`, `binary_decode` | `binary_encode(data)` | space-separated bits / `bytes` |
| `octal_encode`, `octal_decode` | `octal_encode(data)` | octal groups / `bytes` |
| `morse_encode`, `morse_decode` | `morse_encode(text)` | Morse `str` / `str` |
| `rot47` | `rot47(data)` | `str`; self-inverse |
| `html_decode` | `html_decode(data)` | `str` |
| `decompress` | `decompress(data)` | `bytes`; gzip/bzip2/zlib by magic |
| `zlib_decompress`, `gzip_decompress`, `bz2_decompress` | `zlib_decompress(data)` | `bytes` |
| `uu_decode` | `uu_decode(data)` | `bytes` |
| `decode_candidates` | `decode_candidates(data)` | `list[Decoded]`, best first |
| `auto_decode` | `auto_decode(data, *, max_depth=10)` | `(decoded:bytes, steps:list[str])` |
| `quadgram_score` | `quadgram_score(data)` | `float` (higher is more English-like) |
| `shannon_entropy` | `shannon_entropy(data)` | bits per byte |
| `text_score` | `text_score(data)` | `float`; combines the above and flag hits |

### `fermentanyl.hashes`

| Function | Signature | Returns |
| --- | --- | --- |
| `identify_hash` | `identify_hash(digest)` | ranked `list[str]` (possibly empty) |
| `hash_data` | `hash_data(data, algorithm="sha256", *, encoding="utf-8")` | lowercase hex `str` |
| `length_extension` | `length_extension(message, digest, append, secret_length, *, algorithm="sha256")` | `(forged_message:bytes, forged_hex_digest:str)` |
| `md5_length_extension` | `md5_length_extension(message, digest, append, secret_length)` | same tuple |
| `sha1_length_extension` | `sha1_length_extension(message, digest, append, secret_length)` | same tuple |
| `sha256_length_extension` | `sha256_length_extension(message, digest, append, secret_length)` | same tuple |
| `sha512_length_extension` | `sha512_length_extension(message, digest, append, secret_length)` | same tuple |
| `crack_hash`, `dictionary_attack` | `crack_hash(target, wordlist, algorithm="sha256", *, workers=None, encoding="utf-8", chunk_size=2048)` | matching word `bytes` or `None` |
| `brute_force_hash`, `brute_force_attack` | `brute_force_hash(target, alphabet, max_length, *, min_length=1, algorithm="sha256", workers=None, encoding="utf-8", chunk_size=4096)` | matching candidate `bytes` or `None` |
| `crc32` | `crc32(data, *, initial=0)` | 32-bit `int` |
| `crc32_forge` | `crc32_forge(message, target_crc, *, original_crc=None)` | 4-byte suffix `bytes` |

### `fermentanyl.prng`

| Function | Signature | Returns |
| --- | --- | --- |
| `lcg_recover` | `lcg_recover(outputs, modulus=None)` | `(a, b, m)` |
| `lcg_next` | `lcg_next(outputs, modulus=None)` | next output `int` |
| `mt19937_temper` | `mt19937_temper(value)` | tempered 32-bit `int` |
| `mt19937_untemper` | `mt19937_untemper(value)` | 32-bit state word `int` |
| `mt19937_clone` | `mt19937_clone(outputs)` | `random.Random` clone; needs 624 outputs (1248 to auto-detect a mid-cycle start) |

### `fermentanyl.solve`

| Function | Signature | Returns |
| --- | --- | --- |
| `solve`, `auto_solve` | `solve(data, *, max_depth=10, try_classical=True)` | `{"kind": str, "value": object, "details": dict}` |
| `classify` | `classify(data)` | `{"kind": str, "score": float, "candidates": list[dict]}` |

### `fermentanyl.extract`

| Function | Signature | Returns |
| --- | --- | --- |
| `parse_values` | `parse_values(data, *, fields=RSA_FIELDS)` | `dict[str, int]` from `n = ...`/`n: ...` text |
| `extract_rsa` | `extract_rsa(data)` | RSA fields as `dict[str, int]`; understands JSON and Base64 JSON |
| `extract_key` | `extract_key(data)` | `RSAPublicKey`/`RSAPrivateKey`, or `None`; PEM and DER |
| `extract` | `extract(data)` | `{"kind": str, "value": object, "details": dict}` |
| `extract_file` | `extract_file(path)` | `extract(path.read_bytes())` with `details["path"]` |

### `fermentanyl.flags`

| Function | Signature | Returns |
| --- | --- | --- |
| `find_flags` | `find_flags(data, *, patterns=None, prefixes=None, include_defaults=True, ignore_case=True)` | distinct matches in first-seen order |
| `first_flag` | same keyword arguments | first match `str` or `None` |
| `has_flag` | same keyword arguments | `bool` |

### `fermentanyl.cli`

| Function | Signature | Returns |
| --- | --- | --- |
| `run_attacks` | `run_attacks(params, *, budget=None, workers=1, max_cost=None, include_oracles=False)` | `AttackResult`; verifies values and records skipped dependencies |
| `main` | `main(argv=None)` | exit status: `0` recovered, `1` nothing found, `2` usage/runtime error |
| `build_parser` | `build_parser()` | the `ferm` `argparse.ArgumentParser` |

### `fermentanyl.results`

| Function | Signature | Returns |
| --- | --- | --- |
| `Attempt` | `Attempt.ok(attack, value, *, elapsed=0.0, confidence=1.0)`, `Attempt.failed(attack, reason, *, elapsed=0.0)`, `Attempt.not_run(attack, reason, *, elapsed=0.0)` | one attempt: `status`, `value`, `confidence`, `elapsed`, `failure` |
| `AttackResult` | `AttackResult.from_attempts(attempts, *, elapsed=None)` | best result, with `tried`, `succeeded` and `as_dict()` |
| `Budget` | `Budget(total=None, per_attack=None)` | `.remaining()`, `.expired()`, `.timeout_for(default=None)`; raises `AttackTimeout` when spent |

### `fermentanyl.registry`

| Function | Signature | Returns |
| --- | --- | --- |
| `Attack` | `Attack(name, category, func, summary, input_types, *, cost="moderate", optional_deps=(), preconditions=(), needs_oracle=False)` | metadata record with `.available`, `.missing_deps`, `.as_dict()` |
| `attacks` | `attacks()` | `tuple[Attack, ...]` in declaration order |
| `get` | `get(name)` | `Attack`; `ValueError` listing known names |
| `select` | `select(catalog, *, category=None, inputs=None, max_cost=None, include_oracles=False, available_only=False)` | `list[Attack]` |
| `find` | `find(**filters)` | `select(attacks(), ...)` |
| `categories` | `categories()` | sorted category names |

### `fermentanyl.backends`

| Function | Signature | Returns |
| --- | --- | --- |
| `Backend` | `Backend(name, module, purpose, install, executable=None)` | capability record with `.available` |
| `backends` | `backends()` | `tuple[Backend, ...]` |
| `available` | `available()` | names of the backends usable right now |
| `has` | `has(name)` | `bool` |
| `load` | `load(name)` | module; `MissingDependencyError` with the install command |
| `run_with_timeout` | `run_with_timeout(func, *args, timeout, **kwargs)` | result of `func`; `AttackTimeout` kills the worker process |
| `map_parallel` | `map_parallel(func, items, *, workers=None, timeout=None)` | `list` of results in input order |
| `sage_available` | `sage_available(*, binary="sage")` | `bool` |
| `run_sage` | `run_sage(script, *, timeout, params=(), binary="sage")` | stdout `str`; parameters travel as argv, never as code |

### Errors

| Exception | Meaning |
| --- | --- |
| `FermentanylError` | Base class for library-specific errors |
| `AttackNotApplicable` | The attack's preconditions are not met; subclass of `ValueError` |
| `AttackTimeout` | An attack, budget or backend call ran out of time; subclass of `TimeoutError` |
| `MissingDependencyError` | An optional dependency is needed; subclass of `ImportError` |
| `OracleError` | A callback oracle failed or contradicted itself |

## Documentation

Per-module usage notes live in [`docs/`](docs/index.md). The docs cover the
intended workflow, callback signatures, and failure modes.

## Credits and prior art

`fermentanyl` is a small, readable reimplementation of techniques documented in:

- [RsaCtfTool](https://github.com/RsaCtfTool/RsaCtfTool) for the RSA attack
  catalogue and CTF workflow.
- [Cryptopals](https://cryptopals.com/) for the block-cipher oracle exercises.
- Boneh, Durfee, Franklin, Reiter, Wiener, Bleichenbacher, Pollard, Williams,
  Pohlig, Hellman, and the standard ECDSA/ECC literature for the attacks.
- [pycryptodome](https://www.pycryptodome.org/) for AES, GCM, and RSA key
  parsing.
- [sympy](https://www.sympy.org/) for factoring and polynomial helpers.
- [fpylll](https://github.com/fplll/fpylll) for the optional lattice reduction.

The implementations here are written for clarity and CTF-sized inputs, not for
production performance or side-channel resistance.

## Development

```bash
python -m venv .venv
source .venv/bin/activate
python -m pip install -e ".[dev]"

ruff check src tests
ruff format --check src tests
pytest
pytest --doctest-modules src/fermentanyl
python -m build
twine check dist/*
```

Cut a release from `main` with `python scripts/release.py --bump patch`; it
runs the checks, updates the version and changelog, tags the commit and
triggers the PyPI upload. See [`docs/releasing.md`](docs/releasing.md).

The package is typed and ships a `py.typed` marker. Tests run without the
optional `gmpy2` and `fpylll` dependencies; the missing-dependency paths are
tested explicitly.

## Contributing

Bug reports, new attacks, docstring improvements, and tests are welcome. See
[`CONTRIBUTING.md`](CONTRIBUTING.md) for the development workflow and release
process. Changes are tracked in [`CHANGELOG.md`](CHANGELOG.md).

## Security

This library deliberately implements attacks and weak primitives. It is not a
production cryptography library. See [`SECURITY.md`](SECURITY.md) for the
reporting policy and scope.

## License

MIT. See [`LICENSE`](LICENSE).
