decryptre 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
decryptre/cli.py ADDED
@@ -0,0 +1,373 @@
1
+ """Command line interface: ``decryptre decrypt|encrypt|identify``."""
2
+
3
+ import argparse
4
+ import base64
5
+ import sys
6
+ from pathlib import Path
7
+ from typing import Iterable, List, Optional
8
+
9
+ from . import __version__, classical, encodings, modern_crypto, xor
10
+ from .auto_detect import XOR_PREFIX, detect
11
+ from .containers import ContainerError
12
+ from .models import Candidate
13
+ from .scorer import score_text
14
+
15
+ RESPONSIBLE_USE = (
16
+ "Responsible use: decrypt only data you own or have explicit permission "
17
+ "to test. DecryptRE is an educational and CTF tool, not an attack service."
18
+ )
19
+
20
+ METHOD_ALIASES = {
21
+ "rot": "caesar",
22
+ "rot-n": "caesar",
23
+ "rotn": "caesar",
24
+ "rot13": "rot13",
25
+ "rail-fence": "railfence",
26
+ "rail_fence": "railfence",
27
+ "rail": "railfence",
28
+ "vig": "vigenere",
29
+ "sub": "substitution",
30
+ "auto": "auto",
31
+ "all": "auto",
32
+ "base64": "base64",
33
+ "base32": "base32",
34
+ "base16": "base16",
35
+ "hex": "base16",
36
+ "url": "url",
37
+ "ascii85": "ascii85",
38
+ "aes": "aes",
39
+ "aes-cbc": "aes",
40
+ "aes-gcm": "aes",
41
+ "fernet": "fernet",
42
+ "xor": "xor",
43
+ "caesar": "caesar",
44
+ "atbash": "atbash",
45
+ "vigenere": "vigenere",
46
+ "railfence": "railfence",
47
+ "substitution": "substitution",
48
+ }
49
+
50
+
51
+ def _normalise_method(name: str) -> str:
52
+ key = name.strip().lower()
53
+ return METHOD_ALIASES.get(key, key)
54
+
55
+
56
+ def read_input(value: str) -> str:
57
+ """Read a file when ``value`` names one, otherwise treat it as text."""
58
+ if value == "-":
59
+ return sys.stdin.read()
60
+ try:
61
+ path = Path(value)
62
+ is_file = len(value) < 4096 and path.is_file()
63
+ except OSError:
64
+ # Long tokens and odd names are ciphertext, not paths.
65
+ is_file = False
66
+ if is_file:
67
+ # surrogateescape keeps arbitrary bytes recoverable for XOR.
68
+ return path.read_text(encoding="utf-8", errors="surrogateescape")
69
+ return value
70
+
71
+
72
+ def load_wordlist(path: Optional[str] = None) -> List[str]:
73
+ """Load a newline-separated passphrase list (bundled by default)."""
74
+ if path is None:
75
+ candidate = Path(__file__).parent / "wordlists" / "common-passwords.txt"
76
+ else:
77
+ candidate = Path(path)
78
+ if not candidate.is_file():
79
+ raise SystemExit(f"error: wordlist not found: {candidate}")
80
+ words = []
81
+ for line in candidate.read_text(encoding="utf-8", errors="replace").splitlines():
82
+ line = line.strip()
83
+ if line and not line.startswith("#"):
84
+ words.append(line)
85
+ return words
86
+
87
+
88
+ def _display(text: str) -> str:
89
+ """Make control characters visible without hiding the plaintext."""
90
+ return "".join(
91
+ ch if ch in "\n\t" or 32 <= ord(ch) <= 126 else f"\\x{ord(ch):02x}"
92
+ for ch in text
93
+ )
94
+
95
+
96
+ def print_candidates(candidates: Iterable[Candidate], verbose: bool = False) -> None:
97
+ candidates = list(candidates)
98
+ if not candidates:
99
+ print("No result. Try --method with an explicit cipher, or --max-depth 4.")
100
+ return
101
+ for index, candidate in enumerate(candidates, start=1):
102
+ params = candidate.describe_params()
103
+ header = f"[{index}] score={candidate.score:7.3f} method={candidate.method}"
104
+ if params:
105
+ header += f" {params}"
106
+ if verbose and candidate.depth:
107
+ header += f" depth={candidate.depth}"
108
+ print(header)
109
+ for line in _display(candidate.text).splitlines() or [""]:
110
+ print(f" {line}")
111
+ if index < len(candidates):
112
+ print()
113
+
114
+
115
+ def _xor_wrapper(raw: bytes) -> str:
116
+ token = base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
117
+ return XOR_PREFIX + token
118
+
119
+
120
+ def _unwrap_xor(text: str) -> Optional[bytes]:
121
+ stripped = text.strip()
122
+ if not stripped.startswith(XOR_PREFIX):
123
+ return None
124
+ token = stripped[len(XOR_PREFIX):]
125
+ token += "=" * ((-len(token)) % 4)
126
+ try:
127
+ return base64.urlsafe_b64decode(token.encode("ascii"))
128
+ except (ValueError, UnicodeDecodeError):
129
+ return None
130
+
131
+
132
+ # ---------------------------------------------------------------------------
133
+ # decrypt
134
+ # ---------------------------------------------------------------------------
135
+
136
+ def _decrypt_with_method(method: str, text: str, args) -> List[Candidate]:
137
+ if method in encodings.ENCODINGS:
138
+ plain = encodings.decode(text, method)
139
+ return [Candidate(plain, method, {}, score_text(plain))]
140
+
141
+ if method == "rot13":
142
+ plain = classical.rot13(text)
143
+ return [Candidate(plain, "caesar", {"shift": 13}, score_text(plain))]
144
+
145
+ if method == "caesar":
146
+ if args.shift is not None:
147
+ plain = classical.caesar_decrypt(text, args.shift)
148
+ return [Candidate(plain, "caesar", {"shift": args.shift}, score_text(plain))]
149
+ return classical.break_caesar(text, top=args.top)
150
+
151
+ if method == "atbash":
152
+ return classical.break_atbash(text)
153
+
154
+ if method == "vigenere":
155
+ if not args.key:
156
+ return classical.break_vigenere(text, top=args.top)
157
+ plain = classical.vigenere_decrypt(text, args.key)
158
+ return [Candidate(plain, "vigenere", {"key": args.key}, score_text(plain))]
159
+
160
+ if method == "railfence":
161
+ if args.rails is None:
162
+ return classical.break_railfence(text, top=args.top)
163
+ plain = classical.railfence_decrypt(text, args.rails)
164
+ return [Candidate(plain, "railfence", {"rails": args.rails}, score_text(plain))]
165
+
166
+ if method == "substitution":
167
+ if args.key:
168
+ plain = classical.substitution_decrypt(text, args.key)
169
+ return [Candidate(plain, "substitution", {"key": args.key}, score_text(plain))]
170
+ return classical.break_substitution(text, top=args.top)
171
+
172
+ if method == "xor":
173
+ raw = _unwrap_xor(text)
174
+ if raw is None:
175
+ raw = xor.to_bytes(text)
176
+ if args.key:
177
+ plain = xor.from_bytes(xor.xor_bytes(raw, args.key))
178
+ return [Candidate(plain, "xor", {"key": args.key}, score_text(plain))]
179
+ return xor.break_xor(raw, top=args.top)
180
+
181
+ if method in ("fernet", "aes"):
182
+ if not args.key:
183
+ words = [] if args.no_wordlist else load_wordlist(args.wordlist)
184
+ if not words:
185
+ raise SystemExit("error: modern crypto needs --key (no wordlist loaded)")
186
+ results = modern_crypto.dictionary_attack(text, words, top=args.top)
187
+ if not results:
188
+ raise SystemExit(
189
+ "No passphrase in the wordlist worked. Modern crypto cannot be "
190
+ "brute-forced; supply --key if you know it."
191
+ )
192
+ return results
193
+ plain = modern_crypto.decrypt_modern(text, args.key)
194
+ return [Candidate(plain, "modern", {"alg": method}, score_text(plain))]
195
+
196
+ raise SystemExit(f"error: unknown method: {method}")
197
+
198
+
199
+ def cmd_decrypt(args) -> int:
200
+ text = read_input(args.input)
201
+ method = _normalise_method(args.method)
202
+
203
+ if method == "auto":
204
+ words = [] if args.no_wordlist else load_wordlist(args.wordlist)
205
+ results = detect(
206
+ text,
207
+ max_depth=args.max_depth,
208
+ max_candidates=args.max_candidates,
209
+ top=args.top,
210
+ wordlist=words,
211
+ include_substitution=not args.no_substitution,
212
+ )
213
+ else:
214
+ try:
215
+ results = _decrypt_with_method(method, text, args)
216
+ except (encodings.DecodeError, ContainerError, ValueError) as exc:
217
+ raise SystemExit(f"error: {exc}")
218
+
219
+ print_candidates(results, verbose=args.verbose > 0)
220
+ return 0
221
+
222
+
223
+ # ---------------------------------------------------------------------------
224
+ # encrypt
225
+ # ---------------------------------------------------------------------------
226
+
227
+ def cmd_encrypt(args) -> int:
228
+ method = _normalise_method(args.method)
229
+ text = read_input(args.input)
230
+
231
+ if method in encodings.ENCODINGS:
232
+ print(encodings.encode(text, method))
233
+ return 0
234
+ if method == "rot13":
235
+ print(classical.rot13(text))
236
+ return 0
237
+ if method == "caesar":
238
+ print(classical.caesar_encrypt(text, args.shift if args.shift is not None else 3))
239
+ return 0
240
+ if method == "atbash":
241
+ print(classical.atbash(text))
242
+ return 0
243
+ if method == "vigenere":
244
+ if not args.key:
245
+ raise SystemExit("error: --key is required for Vigenere")
246
+ print(classical.vigenere_encrypt(text, args.key))
247
+ return 0
248
+ if method == "railfence":
249
+ if args.rails is None:
250
+ raise SystemExit("error: --rails is required for Rail Fence")
251
+ print(classical.railfence_encrypt(text, args.rails))
252
+ return 0
253
+ if method == "substitution":
254
+ if not args.key:
255
+ raise SystemExit("error: --key (26-letter alphabet) is required for substitution")
256
+ print(classical.substitution_encrypt(text, args.key))
257
+ return 0
258
+ if method == "xor":
259
+ if not args.key:
260
+ raise SystemExit("error: --key is required for XOR")
261
+ print(_xor_wrapper(xor.xor_encrypt(text, args.key)))
262
+ return 0
263
+ if method == "fernet":
264
+ if not args.key:
265
+ raise SystemExit("error: --key is required for Fernet")
266
+ print(modern_crypto.encrypt_fernet(text, args.key, iterations=args.iterations))
267
+ return 0
268
+ if method == "aes":
269
+ if not args.key:
270
+ raise SystemExit("error: --key is required for AES")
271
+ print(
272
+ modern_crypto.encrypt_aes(
273
+ text,
274
+ args.key,
275
+ mode=args.aes_mode,
276
+ kdf=args.kdf,
277
+ iterations=args.iterations,
278
+ )
279
+ )
280
+ return 0
281
+
282
+ raise SystemExit(f"error: unknown method: {method}")
283
+
284
+
285
+ # ---------------------------------------------------------------------------
286
+ # identify
287
+ # ---------------------------------------------------------------------------
288
+
289
+ def cmd_identify(args) -> int:
290
+ text = read_input(args.input).strip()
291
+ matches = modern_crypto.identify_hash(text)
292
+ print(f"input length: {len(text)}")
293
+ if matches:
294
+ for match in matches:
295
+ print(f" {match}")
296
+ else:
297
+ print(" no known encoding or hash shape detected")
298
+ print(" note: hashes are one-way; DecryptRE identifies them but cannot reverse them")
299
+ return 0
300
+
301
+
302
+ # ---------------------------------------------------------------------------
303
+ # Parser
304
+ # ---------------------------------------------------------------------------
305
+
306
+ def build_parser() -> argparse.ArgumentParser:
307
+ parser = argparse.ArgumentParser(
308
+ prog="decryptre",
309
+ description=(
310
+ "Offline decryption and encryption of text. "
311
+ "No passphrase mode is a parameter/dictionary search, not a keyspace break."
312
+ ),
313
+ epilog=RESPONSIBLE_USE,
314
+ formatter_class=argparse.RawDescriptionHelpFormatter,
315
+ )
316
+ parser.add_argument("--version", action="version", version=f"decryptre {__version__}")
317
+ sub = parser.add_subparsers(dest="command", required=True)
318
+
319
+ decrypt = sub.add_parser(
320
+ "decrypt",
321
+ help="decrypt or decode text (auto or a chosen method)",
322
+ description="Decrypt text. With --method auto every supported layer is tried.",
323
+ epilog=RESPONSIBLE_USE,
324
+ )
325
+ decrypt.add_argument("--input", required=True, help="file path, literal text, or - for stdin")
326
+ decrypt.add_argument("--method", default="auto", help="method name or auto (default: auto)")
327
+ decrypt.add_argument("--key", help="passphrase or cipher key")
328
+ decrypt.add_argument("--shift", type=int, help="Caesar shift (default: try all)")
329
+ decrypt.add_argument("--rails", type=int, help="Rail Fence rails (default: try 2-12)")
330
+ decrypt.add_argument("--wordlist", help="offline passphrase list for modern crypto")
331
+ decrypt.add_argument("--no-wordlist", action="store_true", help="do not use the bundled wordlist")
332
+ decrypt.add_argument("--no-substitution", action="store_true", help="skip the slow substitution solver")
333
+ decrypt.add_argument("--max-depth", type=int, default=3, help="maximum peel layers (default: 3)")
334
+ decrypt.add_argument("--max-candidates", type=int, default=2000, help="candidate budget (default: 2000)")
335
+ decrypt.add_argument("--top", type=int, default=5, help="how many results to show (default: 5)")
336
+ decrypt.add_argument("-v", "--verbose", action="count", default=0, help="show extra detail")
337
+ decrypt.set_defaults(func=cmd_decrypt)
338
+
339
+ encrypt = sub.add_parser(
340
+ "encrypt",
341
+ help="encrypt or encode text",
342
+ description="Encrypt text with the same methods DecryptRE can decrypt.",
343
+ )
344
+ encrypt.add_argument("--input", required=True, help="file path, literal text, or - for stdin")
345
+ encrypt.add_argument("--method", required=True, help="encoding or cipher name")
346
+ encrypt.add_argument("--key", help="passphrase or cipher key")
347
+ encrypt.add_argument("--shift", type=int, default=3, help="Caesar shift (default: 3)")
348
+ encrypt.add_argument("--rails", type=int, help="Rail Fence rails")
349
+ encrypt.add_argument("--aes-mode", default="gcm", choices=["gcm", "cbc"], help="AES mode (default: gcm)")
350
+ encrypt.add_argument("--kdf", default="pbkdf2", choices=["pbkdf2", "scrypt"], help="key derivation (default: pbkdf2)")
351
+ encrypt.add_argument("--iterations", type=int, default=modern_crypto.DEFAULT_ITERATIONS, help="PBKDF2 iterations")
352
+ encrypt.add_argument("-v", "--verbose", action="count", default=0)
353
+ encrypt.set_defaults(func=cmd_encrypt)
354
+
355
+ identify = sub.add_parser(
356
+ "identify",
357
+ help="identify hashes and encodings (hashes cannot be decrypted)",
358
+ )
359
+ identify.add_argument("--input", required=True, help="file path, literal text, or - for stdin")
360
+ identify.add_argument("-v", "--verbose", action="count", default=0)
361
+ identify.set_defaults(func=cmd_identify)
362
+
363
+ return parser
364
+
365
+
366
+ def main(argv: Optional[List[str]] = None) -> int:
367
+ parser = build_parser()
368
+ args = parser.parse_args(argv)
369
+ return args.func(args)
370
+
371
+
372
+ if __name__ == "__main__":
373
+ raise SystemExit(main())
@@ -0,0 +1,47 @@
1
+ """The self-describing ciphertext container used for modern crypto.
2
+
3
+ AES needs a salt, an IV/nonce and the KDF settings to decrypt. Instead of
4
+ making the user remember them, DecryptRE stores them next to the ciphertext
5
+ in a small JSON envelope::
6
+
7
+ decryptre:v1:<urlsafe-base64 of the JSON envelope>
8
+
9
+ The envelope is authenticated by AES-GCM itself; for AES-CBC a wrong
10
+ passphrase usually shows up as invalid padding.
11
+ """
12
+
13
+ import base64
14
+ import json
15
+ from typing import Any, Dict
16
+
17
+ MAGIC = "decryptre:v1:"
18
+
19
+
20
+ class ContainerError(ValueError):
21
+ """Raised when a container is malformed or is not a DecryptRE container."""
22
+
23
+
24
+ def is_container(text: str) -> bool:
25
+ return text.strip().startswith(MAGIC)
26
+
27
+
28
+ def pack(payload: Dict[str, Any]) -> str:
29
+ raw = json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
30
+ token = base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
31
+ return MAGIC + token
32
+
33
+
34
+ def unpack(text: str) -> Dict[str, Any]:
35
+ stripped = text.strip()
36
+ if not stripped.startswith(MAGIC):
37
+ raise ContainerError("not a DecryptRE container")
38
+ token = stripped[len(MAGIC):]
39
+ token += "=" * ((-len(token)) % 4)
40
+ try:
41
+ raw = base64.urlsafe_b64decode(token.encode("ascii"))
42
+ payload = json.loads(raw.decode("utf-8"))
43
+ except (ValueError, UnicodeDecodeError) as exc:
44
+ raise ContainerError(f"corrupt container: {exc}") from exc
45
+ if not isinstance(payload, dict):
46
+ raise ContainerError("container payload must be an object")
47
+ return payload
@@ -0,0 +1,33 @@
1
+ # Bundled trigram table
2
+
3
+ `trigrams.txt` holds aggregate counts of three-letter sequences, used only by
4
+ the simple-substitution solver to judge which candidate plaintext reads most
5
+ like English. It contains no text from the source book -- only counts such as
6
+ `the 31254`.
7
+
8
+ - Source: *Pride and Prejudice* by Jane Austen, Project Gutenberg eBook #1342
9
+ (<https://www.gutenberg.org/ebooks/1342>), a public-domain work in the
10
+ United States.
11
+ - Derived: lowercased letters only (`a`-`z`), spaces and punctuation removed,
12
+ every overlapping three-letter window counted once.
13
+ - Retrieved: 2026-11-20 (one-time generation at build time).
14
+
15
+ Frequency statistics like these are facts about the text, not a copy of it.
16
+ They are committed so DecryptRE stays fully offline at runtime.
17
+
18
+ ## Regenerating
19
+
20
+ Any large English plaintext works. For example:
21
+
22
+ ```python
23
+ from collections import Counter
24
+
25
+ text = open("book.txt", encoding="utf-8", errors="ignore").read().lower()
26
+ letters = "".join(ch for ch in text if "a" <= ch <= "z")
27
+ counts = Counter(letters[i:i + 3] for i in range(len(letters) - 2))
28
+ for trigram, count in counts.most_common():
29
+ print(trigram, count)
30
+ ```
31
+
32
+ Keep the output small (tens of thousands of lines at most); large tables make
33
+ the package slower to import without improving results much.