- Zero-dependency pure-Python cryptography: SHA-2 / SHA-3 / SHAKE / BLAKE2b, HMAC, PBKDF2 / HKDF / scrypt / Argon2id, AES (ECB/CBC/CTR/CFB/OFB/GCM), AES-GCM-SIV, ChaCha20-Poly1305 / XChaCha20-Poly1305, X25519, Ed25519, RSA (keygen / OAEP / PSS / PEM), ASN.1 DER - Unified error system: PPYC_ERR fatal exception vs (code, message, suggestion) non-fatal 3-tuple return - Interactive TUI (Chinese / English i18n) + non-interactive CLI - v3.2.0 adds the encoding, rand and kdf2 modules - Documentation, code comments and error messages fully in English; the interactive TUI keeps its Chinese interface - Tests: RFC / FIPS / NIST test vectors, 639 passing
488 lines
18 KiB
Python
488 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
build_single.py -- purepycrypto single-file bundler (multi-version)
|
|
=======================================================
|
|
Merge the purepycrypto package (multiple modules) into a standalone single file. Three artifacts are supported:
|
|
|
|
* tui -- merged library + full interactive TUI entry (terminal menu, pipe-drivable)
|
|
artifact: purepycrypto_tui.py
|
|
* cli -- merged library + command-line argument entry (argparse subcommands, suitable for scripts/CI)
|
|
artifact: purepycrypto_cli.py
|
|
* lib -- merged library only (no entry, for embedding / import use)
|
|
artifact: purepycrypto_lib.py
|
|
|
|
You can also generate both the tui and cli versions at once with --mode all (the default).
|
|
|
|
Usage
|
|
----
|
|
python build_single.py # generate tui + cli (default all)
|
|
python build_single.py --mode tui # generate only the TUI version
|
|
python build_single.py --mode cli # generate only the CLI version
|
|
python build_single.py --mode lib # generate only the pure-library version
|
|
python build_single.py -o out/x.py # specify the output (valid only for a single mode)
|
|
python build_single.py --all # same as all, and additionally generate the lib version
|
|
|
|
Artifact usage
|
|
--------
|
|
python purepycrypto_tui.py # start the interactive TUI
|
|
echo -e "1\\n1\\nabc\\n\\n0\\n0" | python purepycrypto_tui.py # pipe-driven
|
|
python purepycrypto_cli.py hash --algo sha256 --text abc --hex
|
|
python purepycrypto_cli.py --help
|
|
import purepycrypto_lib as ppc # use as a library
|
|
"""
|
|
import argparse
|
|
import ast
|
|
import os
|
|
import re
|
|
|
|
# Module concatenation order (strictly bottom-up by dependency); entry modules excluded
|
|
LIB_MODULES = [
|
|
"_ppyc_error", # unified error scheme (must be merged first; other modules depend on it)
|
|
"common",
|
|
"parallel",
|
|
"hash",
|
|
"kdf",
|
|
"aes",
|
|
"chacha",
|
|
"x25519",
|
|
"rsa",
|
|
"der",
|
|
]
|
|
# New modules in v1.1 / v3.2.0 (included if present)
|
|
OPTIONAL_MODULES = [
|
|
"sha3",
|
|
"ed25519",
|
|
"aes_gcm_siv",
|
|
# v3.2.0
|
|
"encoding",
|
|
"rand",
|
|
"kdf2",
|
|
]
|
|
ENTRY_TUI = "cli" # interactive TUI module
|
|
ENTRY_CLI = "cli_args" # command-line argument module
|
|
|
|
PKG_DIR = os.path.normpath(
|
|
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
|
|
)
|
|
# Single-file artifacts default to the in-package single/ directory (to avoid polluting the project root)
|
|
SINGLE_DIR = os.path.join(PKG_DIR, "single")
|
|
# Compatibility: another location can still be given via --outdir
|
|
ROOT_DIR = SINGLE_DIR
|
|
|
|
COMMON_IMPORTS = '''
|
|
import os
|
|
import sys
|
|
import math
|
|
import time
|
|
import struct
|
|
import base64
|
|
import atexit
|
|
import argparse
|
|
import json
|
|
from typing import Tuple, Optional, List, Dict, Any, Union
|
|
|
|
try:
|
|
import multiprocessing as mp
|
|
from multiprocessing import Pool, cpu_count
|
|
from multiprocessing import shared_memory
|
|
_HAS_MP = True
|
|
except (ImportError, ModuleNotFoundError):
|
|
mp = None
|
|
Pool = None
|
|
cpu_count = lambda: 1
|
|
shared_memory = None
|
|
_HAS_MP = False
|
|
|
|
# ---- Package metadata (merged from __init__) ----
|
|
__version__ = "@@VERSION@@"
|
|
__author__ = "Dvs(DvsXT)"
|
|
__license__ = "MIT"
|
|
__version_tuple__ = tuple(int(x) for x in __version__.split(".")[:3])
|
|
'''
|
|
|
|
# Standard-library modules provided by the merged header (matching imports are removed)
|
|
STDLIB_NAMES = {
|
|
"os", "sys", "math", "time", "struct", "base64", "atexit",
|
|
"hashlib", "typing", "array", "datetime",
|
|
"multiprocessing",
|
|
}
|
|
STDLIB_FROMS = {"typing", "array", "datetime", "multiprocessing"}
|
|
|
|
DQ = '"' * 3
|
|
SQ = "'" * 3
|
|
|
|
|
|
# -------------------------------------------------------------
|
|
# Header template
|
|
# -------------------------------------------------------------
|
|
|
|
def _header(mode, version="2.7.10"):
|
|
title = {
|
|
"one": "purepycrypto.py -- purepycrypto single-file integrated build (no args=TUI, with args=command line)",
|
|
"tui": "purepycrypto_tui.py -- purepycrypto single-file build (interactive TUI)",
|
|
"cli": "purepycrypto_cli.py -- purepycrypto single-file build (command-line arguments)",
|
|
"lib": "purepycrypto_lib.py -- purepycrypto single-file build (pure library)",
|
|
}[mode]
|
|
usage = {
|
|
"one": (' python purepycrypto.py # no args -> interactive TUI\n'
|
|
' python purepycrypto.py hash --text abc --hex # with args -> command line'),
|
|
"tui": (' python purepycrypto_tui.py # start the interactive TUI\n'
|
|
' echo -e "1\\n1\\nabc\\n\\n0\\n0" | python purepycrypto_tui.py'),
|
|
"cli": (' python purepycrypto_cli.py hash --algo sha256 --text abc --hex\n'
|
|
' python purepycrypto_cli.py --help'),
|
|
"lib": (' import purepycrypto_lib as ppc\n'
|
|
' ppc.sha256(b"abc").hex()'),
|
|
}[mode]
|
|
return (
|
|
'# -*- coding: utf-8 -*-\n'
|
|
'"""\n'
|
|
+ title + '\n'
|
|
+ '=' * len(title) + '\n'
|
|
'purepycrypto -- Pure-Python cryptography library (zero dependencies) · Single-file merged build v' + version + '\n\n'
|
|
'This file was auto-generated by purepycrypto/scripts/build_single.py; do not edit it by hand.\n\n'
|
|
'Includes: SHA-2 / SHA-512 / BLAKE2b / SHA-3(Keccak) / SHAKE\n'
|
|
' HMAC-SHA256/512/3 · PBKDF2 / HKDF / scrypt / Argon2id\n'
|
|
' AES(ECB,CBC,CTR,CFB,OFB,GCM) / AES-GCM-SIV\n'
|
|
' ChaCha20-Poly1305 / XChaCha20-Poly1305\n'
|
|
' X25519 / Ed25519 / RSA(keygen,OAEP,PSS,PEM) / ASN.1 DER\n\n'
|
|
'Usage:\n' + usage + '\n\n'
|
|
'License: MIT (see LICENSE).\n'
|
|
'"""\n'
|
|
)
|
|
|
|
|
|
# Single-file mode: register the aliases expected by cli / cli_args for new module functions
|
|
_ALIAS_BOOTSTRAP = """
|
|
# ---- Single-file aliases (used by cli / cli_args; provided by try-import in package mode) ----
|
|
try:
|
|
_b64e = b64encode; _b64d = b64decode
|
|
_b64e_u = b64encode_urlsafe; _b64d_u = b64decode_urlsafe
|
|
_b32e = b32encode; _b32d = b32decode
|
|
_hexe = hex_encode; _hexd = hex_decode
|
|
_b58e = b58encode; _b58d = b58decode
|
|
except NameError:
|
|
pass
|
|
try:
|
|
_rbytes = random_bytes; _token_hex = token_hex
|
|
_token_urlsafe = token_urlsafe; _rpassword = random_password
|
|
_uuid4 = random_uuid4
|
|
except NameError:
|
|
pass
|
|
try:
|
|
_a2id = argon2id_hash; _a2enc = argon2id_hash_encoded
|
|
_scrypt_simple = scrypt_simple
|
|
except NameError:
|
|
pass
|
|
try:
|
|
_b64encode = b64encode; _b64decode = b64decode
|
|
_b32encode = b32encode; _hex_encode = hex_encode; _b58encode = b58encode
|
|
except NameError:
|
|
pass
|
|
try:
|
|
_random_bytes = random_bytes; _token_hex = token_hex
|
|
_token_urlsafe = token_urlsafe; _random_password = random_password
|
|
_random_uuid4 = random_uuid4
|
|
except NameError:
|
|
pass
|
|
"""
|
|
|
|
|
|
# -------------------------------------------------------------
|
|
# Source processing
|
|
# -------------------------------------------------------------
|
|
|
|
def _read_actual_version():
|
|
"""Read the real version from purepycrypto/_version.py (takes precedence over the command-line argument)."""
|
|
vp = os.path.join(PKG_DIR, "_version.py")
|
|
try:
|
|
with open(vp, "r", encoding="utf-8") as f:
|
|
m = re.search(r'__version__\s*=\s*["\']([^"\']+)["\']', f.read())
|
|
return m.group(1) if m else None
|
|
except OSError:
|
|
return None
|
|
|
|
|
|
def _read_module(name):
|
|
path = os.path.join(PKG_DIR, name + ".py")
|
|
if not os.path.exists(path):
|
|
raise FileNotFoundError("module file not found: " + path)
|
|
with open(path, "r", encoding="utf-8") as f:
|
|
return f.read()
|
|
|
|
|
|
def _import_line_spans(src):
|
|
spans = set()
|
|
try:
|
|
tree = ast.parse(src)
|
|
except SyntaxError:
|
|
return spans
|
|
for node in tree.body:
|
|
if isinstance(node, (ast.Import, ast.ImportFrom)):
|
|
start = node.lineno
|
|
end = getattr(node, "end_lineno", start)
|
|
for ln in range(start, end + 1):
|
|
spans.add(ln)
|
|
return spans
|
|
|
|
|
|
def _is_droppable_import(node):
|
|
if isinstance(node, ast.ImportFrom):
|
|
if node.level and node.level > 0:
|
|
return True
|
|
if node.module in STDLIB_FROMS:
|
|
return True
|
|
if node.module is None and node.level == 0:
|
|
return True
|
|
return False
|
|
if isinstance(node, ast.Import):
|
|
for alias in node.names:
|
|
if alias.name.split(".")[0] in STDLIB_NAMES:
|
|
return True
|
|
return False
|
|
return False
|
|
|
|
|
|
def _strip(src):
|
|
"""Drop the module header docstring and the coding line, and remove imports that the merged header replaces / relative imports.
|
|
|
|
Implementation note: use the AST to precisely locate the (line, column) range of the module docstring,
|
|
avoiding false boundary detection when the docstring text contains quotes (such as 'foo' / "__main__").
|
|
"""
|
|
lines = src.split("\n")
|
|
|
|
# ---- 1) Use the AST to find the module docstring's start/end lines ----
|
|
doc_start = doc_end = None
|
|
try:
|
|
tree = ast.parse(src)
|
|
if (tree.body and isinstance(tree.body[0], ast.Expr)
|
|
and isinstance(tree.body[0].value, ast.Constant)
|
|
and isinstance(tree.body[0].value.value, str)):
|
|
doc = tree.body[0]
|
|
doc_start = doc.lineno # 1-based
|
|
doc_end = getattr(doc, "end_lineno", doc.lineno)
|
|
except SyntaxError:
|
|
pass
|
|
|
|
# ---- 2) Collect lines to drop: coding/shebang lines + docstring + droppable imports ----
|
|
drop = set()
|
|
n = len(lines)
|
|
i = 0
|
|
while i < n and lines[i].strip() == "":
|
|
i += 1
|
|
if i < n and lines[i].startswith("#!"):
|
|
drop.add(i + 1)
|
|
i += 1
|
|
if i < n and "coding" in lines[i] and lines[i].lstrip().startswith("#"):
|
|
drop.add(i + 1)
|
|
|
|
if doc_start is not None:
|
|
for ln in range(doc_start, doc_end + 1):
|
|
drop.add(ln)
|
|
|
|
# ---- 3) Remove imports that the merged header replaces / relative imports (the AST locates multi-line parenthesized forms) ----
|
|
# Note: if these imports are inside a try/except ImportError fallback block, the ENTIRE block must be removed,
|
|
# otherwise a dangling try:/except: is left behind and causes a syntax error.
|
|
def _is_try_import_block(node):
|
|
"""Is node a try block whose body consists solely of droppable imports?"""
|
|
if not isinstance(node, ast.Try):
|
|
return False
|
|
body = [b for b in node.body if not isinstance(b, ast.Expr)]
|
|
return bool(body) and all(
|
|
isinstance(b, (ast.Import, ast.ImportFrom)) and _is_droppable_import(b)
|
|
for b in body
|
|
)
|
|
|
|
try:
|
|
tree2 = ast.parse(src)
|
|
for node in tree2.body:
|
|
target = None
|
|
if isinstance(node, (ast.Import, ast.ImportFrom)) and _is_droppable_import(node):
|
|
target = node
|
|
elif _is_try_import_block(node):
|
|
# remove the whole try/except block (including all handlers / orelse / finalbody)
|
|
target = node
|
|
if target is not None:
|
|
start = target.lineno
|
|
end = getattr(target, "end_lineno", start)
|
|
for ln in range(start, end + 1):
|
|
drop.add(ln)
|
|
except SyntaxError:
|
|
pass
|
|
|
|
# ---- 4) Remove each module's own __main__ entry block ----
|
|
# Only recognize a **top-level (zero-indent)** if __name__, to avoid breaking example code inside docstrings/functions
|
|
for idx, line in enumerate(lines, start=1):
|
|
if line.startswith("if __name__") and "__main__" in line:
|
|
j = idx
|
|
# skip the entire indented block
|
|
while j < n:
|
|
nxt = lines[j]
|
|
if nxt.strip() == "":
|
|
j += 1
|
|
continue
|
|
if nxt.startswith((" ", "\t")):
|
|
j += 1
|
|
continue
|
|
break
|
|
for ln in range(idx, j + 1):
|
|
drop.add(ln)
|
|
break
|
|
|
|
out = [ln for idx, ln in enumerate(lines, start=1) if idx not in drop]
|
|
return "\n".join(out)
|
|
|
|
|
|
# -------------------------------------------------------------
|
|
# Merge
|
|
# -------------------------------------------------------------
|
|
|
|
def _available_modules():
|
|
mods = []
|
|
for name in LIB_MODULES + OPTIONAL_MODULES:
|
|
if os.path.exists(os.path.join(PKG_DIR, name + ".py")):
|
|
mods.append(name)
|
|
return mods
|
|
|
|
|
|
def build(mode="one", version="2.7.10"):
|
|
"""Generate single-file source. mode in {one, tui, cli, lib}.
|
|
|
|
one : integrated build (no args=TUI, with args=command line), matching the `purepycrypto` command behavior
|
|
tui : TUI-only build
|
|
cli : command-line-only build
|
|
lib : pure library (no entry)
|
|
"""
|
|
if mode not in ("one", "tui", "cli", "lib"):
|
|
raise ValueError("mode must be one / tui / cli / lib")
|
|
|
|
parts = [_header(mode, version), COMMON_IMPORTS]
|
|
|
|
modules = _available_modules()
|
|
if mode in ("one", "tui", "cli"):
|
|
# always merge cli first (it provides the TUI menu + _self_test)
|
|
if os.path.exists(os.path.join(PKG_DIR, ENTRY_TUI + ".py")):
|
|
modules = modules + [ENTRY_TUI]
|
|
if mode in ("one", "cli"):
|
|
# then merge cli_args (the command-line argument entry)
|
|
if os.path.exists(os.path.join(PKG_DIR, ENTRY_CLI + ".py")):
|
|
modules = modules + [ENTRY_CLI]
|
|
|
|
for name in modules:
|
|
body = _strip(_read_module(name))
|
|
bar = "# " + "=" * 60
|
|
parts.append("\n\n" + bar + "\n# module: " + name + "\n" + bar + "\n")
|
|
parts.append(body.strip("\n"))
|
|
|
|
# Alias bootstrap: must come **after** all modules are merged (only then are the functions defined)
|
|
parts.append("\n\n" + _ALIAS_BOOTSTRAP)
|
|
|
|
if mode == "tui":
|
|
parts.append('\n\n# ' + '=' * 60 +
|
|
'\n# Entry point (interactive TUI)\n# ' + '=' * 60 +
|
|
'\n\nif __name__ == "__main__":\n'
|
|
' _entry()\n')
|
|
elif mode == "cli":
|
|
parts.append('\n\n# ' + '=' * 60 +
|
|
'\n# Entry point (command-line arguments)\n# ' + '=' * 60 +
|
|
'\n\nif __name__ == "__main__":\n'
|
|
' import sys as _sys\n'
|
|
' _sys.exit(_cli_main(_sys.argv[1:]))\n')
|
|
elif mode == "one":
|
|
# Integrated build: no args -> TUI; with args -> command line (matches this package's console script behavior)
|
|
parts.append('\n\n# ' + '=' * 60 +
|
|
'\n# Entry point (no args=TUI, with args=command line)\n# ' + '=' * 60 +
|
|
'\n\n'
|
|
'def _entry():\n'
|
|
' argv = sys.argv[1:]\n'
|
|
' if not argv:\n'
|
|
' return _tui_main()\n'
|
|
' if argv[0] == "tui":\n'
|
|
' return _tui_main()\n'
|
|
' if argv[0] == "cli":\n'
|
|
' return _cli_main(argv[1:])\n'
|
|
' return _cli_main(argv)\n'
|
|
'\n\n'
|
|
'if __name__ == "__main__":\n'
|
|
' sys.exit(_entry() or 0)\n')
|
|
|
|
code = "\n".join(parts)
|
|
code = re.sub(r"\n{4,}", "\n\n\n", code)
|
|
# Substitute the real version for the template placeholder (to avoid a stale hard-coded value)
|
|
actual = _read_actual_version() or version
|
|
code = code.replace("@@VERSION@@", actual)
|
|
return code
|
|
|
|
|
|
OUTPUT_NAMES = {
|
|
"one": "purepycrypto.py", # single-file integrated build: no args=TUI, with args=CLI
|
|
"tui": "purepycrypto_tui.py",
|
|
"cli": "purepycrypto_cli.py",
|
|
"lib": "purepycrypto_lib.py",
|
|
}
|
|
|
|
|
|
def _emit(mode, out_path, version):
|
|
code = build(mode=mode, version=version)
|
|
os.makedirs(os.path.dirname(os.path.abspath(out_path)), exist_ok=True)
|
|
with open(out_path, "w", encoding="utf-8") as f:
|
|
f.write(code)
|
|
|
|
try:
|
|
compile(code, out_path, "exec")
|
|
status = "syntax check passed"
|
|
except SyntaxError as e:
|
|
status = "⚠ syntax error: " + str(e)
|
|
|
|
print("[✓] " + mode.upper() + " -> " + out_path)
|
|
print(" size: {:,} chars / {:,} lines".format(len(code), len(code.splitlines())))
|
|
print(" " + status)
|
|
return status.startswith("syntax check passed")
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(
|
|
description="purepycrypto single-file bundler (TUI / CLI / pure-library versions)",
|
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
epilog=__doc__,
|
|
)
|
|
ap.add_argument("--mode", default="one",
|
|
choices=["one", "tui", "cli", "lib", "all"],
|
|
help="artifact type: one=integrated (recommended) / tui / cli / lib / all")
|
|
ap.add_argument("-o", "--output", default=None,
|
|
help="output file path (valid only when --mode is a single type)")
|
|
ap.add_argument("--outdir", default=None,
|
|
help="output directory (default: project root dev dir/)")
|
|
ap.add_argument("--all", action="store_true",
|
|
help="equivalent to all, and additionally generate the lib version")
|
|
ap.add_argument("--version", default="2.7.10", help="version string written into the file")
|
|
args = ap.parse_args()
|
|
|
|
outdir = args.outdir or ROOT_DIR
|
|
|
|
if args.mode == "all":
|
|
modes = ["tui", "cli"]
|
|
if args.all:
|
|
modes.append("lib")
|
|
else:
|
|
modes = [args.mode]
|
|
|
|
if args.output and len(modes) > 1:
|
|
ap.error("-o/--output can only be used together with --mode tui|cli|lib")
|
|
|
|
all_ok = True
|
|
for mode in modes:
|
|
out_path = args.output or os.path.join(outdir, OUTPUT_NAMES[mode])
|
|
all_ok &= _emit(mode, out_path, args.version)
|
|
|
|
print()
|
|
if all_ok:
|
|
print("[✓] all artifacts passed the syntax check")
|
|
else:
|
|
print("[!] syntax errors present, please check")
|
|
return 0 if all_ok else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|