ncr-cipher 1.0.0__tar.gz
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.
- ncr_cipher-1.0.0/LICENSE +21 -0
- ncr_cipher-1.0.0/PKG-INFO +95 -0
- ncr_cipher-1.0.0/README.md +76 -0
- ncr_cipher-1.0.0/ncr_cipher/__init__.py +3 -0
- ncr_cipher-1.0.0/ncr_cipher/cli.py +381 -0
- ncr_cipher-1.0.0/ncr_cipher/core.py +513 -0
- ncr_cipher-1.0.0/ncr_cipher/ui.py +136 -0
- ncr_cipher-1.0.0/ncr_cipher.egg-info/PKG-INFO +95 -0
- ncr_cipher-1.0.0/ncr_cipher.egg-info/SOURCES.txt +13 -0
- ncr_cipher-1.0.0/ncr_cipher.egg-info/dependency_links.txt +1 -0
- ncr_cipher-1.0.0/ncr_cipher.egg-info/entry_points.txt +2 -0
- ncr_cipher-1.0.0/ncr_cipher.egg-info/top_level.txt +1 -0
- ncr_cipher-1.0.0/pyproject.toml +29 -0
- ncr_cipher-1.0.0/setup.cfg +4 -0
- ncr_cipher-1.0.0/tests/test_core.py +176 -0
ncr_cipher-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ncr-cipher contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ncr-cipher
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Production-grade NCR3 encryption tool — encrypt, decrypt, and verify files from any terminal.
|
|
5
|
+
Author: ncr-cipher contributors
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: encryption,cipher,cli,security
|
|
8
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
9
|
+
Classifier: Environment :: Console
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Security :: Cryptography
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# ncr-cipher
|
|
21
|
+
|
|
22
|
+
**Production-grade NCR3 encryption tool** — a single `ncr` command available everywhere in the terminal after installation, on Windows, macOS, and Linux.
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install ncr-cipher
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Or install from source:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install -e .
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Quick Start
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
# Generate a key file
|
|
40
|
+
ncr --keygen mykey.key
|
|
41
|
+
|
|
42
|
+
# Encrypt a file
|
|
43
|
+
ncr --lock secret.txt --key mykey.key
|
|
44
|
+
|
|
45
|
+
# Decrypt a file
|
|
46
|
+
ncr --unlock secret.txt.ncr3 --key mykey.key
|
|
47
|
+
|
|
48
|
+
# Verify integrity without decrypting
|
|
49
|
+
ncr --verify secret.txt.ncr3 --key mykey.key
|
|
50
|
+
|
|
51
|
+
# Show file info (no password needed)
|
|
52
|
+
ncr --info secret.txt.ncr3
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Commands
|
|
56
|
+
|
|
57
|
+
| Command | Description |
|
|
58
|
+
|---|---|
|
|
59
|
+
| `ncr --keygen <keyfile>` | Generate a new key file |
|
|
60
|
+
| `ncr --lock <file> --key <k>` | Encrypt a file |
|
|
61
|
+
| `ncr --unlock <file> --key <k>` | Decrypt a file |
|
|
62
|
+
| `ncr --verify <file> --key <k>` | Check HMAC without decrypting |
|
|
63
|
+
| `ncr --info <file>` | Show NCR version, IV, block count, file size |
|
|
64
|
+
| `ncr --bench` | Benchmark KDF time + encrypt speed |
|
|
65
|
+
| `ncr --test` | Run internal self-tests |
|
|
66
|
+
| `ncr --version` | Print version |
|
|
67
|
+
|
|
68
|
+
## Flags
|
|
69
|
+
|
|
70
|
+
| Flag | Description |
|
|
71
|
+
|---|---|
|
|
72
|
+
| `--out, -o <path>` | Output path override |
|
|
73
|
+
| `--inplace, -i` | Overwrite the original file |
|
|
74
|
+
| `--silent, -s` | No output except errors |
|
|
75
|
+
| `--force, -f` | Overwrite output without confirmation |
|
|
76
|
+
| `--strength <1-5>` | KDF strength preset (keygen only) |
|
|
77
|
+
|
|
78
|
+
## Cipher: NCR3
|
|
79
|
+
|
|
80
|
+
- **KDF**: scrypt with configurable strength (5 presets)
|
|
81
|
+
- **Per-byte key mixing**: BLAKE2b-derived per-position keys
|
|
82
|
+
- **CBC chaining**: HMAC-SHA3-256 stream + ciphertext feedback
|
|
83
|
+
- **Authentication**: HMAC-SHA3-256 over full ciphertext
|
|
84
|
+
- **Math core**: nCr (binomial coefficient) based encryption mod 2¹²⁷−1
|
|
85
|
+
|
|
86
|
+
Backwards compatible: can read NCR2 files (read-only).
|
|
87
|
+
|
|
88
|
+
## Requirements
|
|
89
|
+
|
|
90
|
+
- Python 3.9+
|
|
91
|
+
- **Zero external dependencies** — stdlib only
|
|
92
|
+
|
|
93
|
+
## License
|
|
94
|
+
|
|
95
|
+
MIT
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# ncr-cipher
|
|
2
|
+
|
|
3
|
+
**Production-grade NCR3 encryption tool** — a single `ncr` command available everywhere in the terminal after installation, on Windows, macOS, and Linux.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install ncr-cipher
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Or install from source:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install -e .
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Quick Start
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
# Generate a key file
|
|
21
|
+
ncr --keygen mykey.key
|
|
22
|
+
|
|
23
|
+
# Encrypt a file
|
|
24
|
+
ncr --lock secret.txt --key mykey.key
|
|
25
|
+
|
|
26
|
+
# Decrypt a file
|
|
27
|
+
ncr --unlock secret.txt.ncr3 --key mykey.key
|
|
28
|
+
|
|
29
|
+
# Verify integrity without decrypting
|
|
30
|
+
ncr --verify secret.txt.ncr3 --key mykey.key
|
|
31
|
+
|
|
32
|
+
# Show file info (no password needed)
|
|
33
|
+
ncr --info secret.txt.ncr3
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Commands
|
|
37
|
+
|
|
38
|
+
| Command | Description |
|
|
39
|
+
|---|---|
|
|
40
|
+
| `ncr --keygen <keyfile>` | Generate a new key file |
|
|
41
|
+
| `ncr --lock <file> --key <k>` | Encrypt a file |
|
|
42
|
+
| `ncr --unlock <file> --key <k>` | Decrypt a file |
|
|
43
|
+
| `ncr --verify <file> --key <k>` | Check HMAC without decrypting |
|
|
44
|
+
| `ncr --info <file>` | Show NCR version, IV, block count, file size |
|
|
45
|
+
| `ncr --bench` | Benchmark KDF time + encrypt speed |
|
|
46
|
+
| `ncr --test` | Run internal self-tests |
|
|
47
|
+
| `ncr --version` | Print version |
|
|
48
|
+
|
|
49
|
+
## Flags
|
|
50
|
+
|
|
51
|
+
| Flag | Description |
|
|
52
|
+
|---|---|
|
|
53
|
+
| `--out, -o <path>` | Output path override |
|
|
54
|
+
| `--inplace, -i` | Overwrite the original file |
|
|
55
|
+
| `--silent, -s` | No output except errors |
|
|
56
|
+
| `--force, -f` | Overwrite output without confirmation |
|
|
57
|
+
| `--strength <1-5>` | KDF strength preset (keygen only) |
|
|
58
|
+
|
|
59
|
+
## Cipher: NCR3
|
|
60
|
+
|
|
61
|
+
- **KDF**: scrypt with configurable strength (5 presets)
|
|
62
|
+
- **Per-byte key mixing**: BLAKE2b-derived per-position keys
|
|
63
|
+
- **CBC chaining**: HMAC-SHA3-256 stream + ciphertext feedback
|
|
64
|
+
- **Authentication**: HMAC-SHA3-256 over full ciphertext
|
|
65
|
+
- **Math core**: nCr (binomial coefficient) based encryption mod 2¹²⁷−1
|
|
66
|
+
|
|
67
|
+
Backwards compatible: can read NCR2 files (read-only).
|
|
68
|
+
|
|
69
|
+
## Requirements
|
|
70
|
+
|
|
71
|
+
- Python 3.9+
|
|
72
|
+
- **Zero external dependencies** — stdlib only
|
|
73
|
+
|
|
74
|
+
## License
|
|
75
|
+
|
|
76
|
+
MIT
|
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
# pyre-ignore-all-errors
|
|
2
|
+
"""CLI entry point for the ``ncr`` command."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import getpass
|
|
7
|
+
import os
|
|
8
|
+
import signal
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
import time
|
|
12
|
+
|
|
13
|
+
from ncr_cipher import __version__ # type: ignore
|
|
14
|
+
from ncr_cipher import core # type: ignore
|
|
15
|
+
from ncr_cipher import ui # type: ignore
|
|
16
|
+
|
|
17
|
+
# ── Signal handling ─────────────────────────────────────────────────
|
|
18
|
+
|
|
19
|
+
def _handle_sigint(*_: object) -> None: # noqa: ANN401
|
|
20
|
+
sys.exit(130)
|
|
21
|
+
|
|
22
|
+
if os.name != "nt":
|
|
23
|
+
signal.signal(signal.SIGINT, _handle_sigint)
|
|
24
|
+
|
|
25
|
+
# ── Helpers ─────────────────────────────────────────────────────────
|
|
26
|
+
|
|
27
|
+
def _prompt_password(confirm: bool = False) -> bytes:
|
|
28
|
+
"""Prompt for password via getpass; optionally confirm."""
|
|
29
|
+
pw = getpass.getpass("Password: ")
|
|
30
|
+
if confirm:
|
|
31
|
+
pw2 = getpass.getpass("Confirm password: ")
|
|
32
|
+
if pw != pw2:
|
|
33
|
+
ui.error("Passwords do not match")
|
|
34
|
+
sys.exit(1)
|
|
35
|
+
return pw.encode("utf-8")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _resolve_password(args: argparse.Namespace, confirm: bool = False) -> bytes:
|
|
39
|
+
"""If --key is given, load the key file; otherwise prompt password."""
|
|
40
|
+
if args.key:
|
|
41
|
+
kf_path = args.key
|
|
42
|
+
if not os.path.isfile(kf_path):
|
|
43
|
+
ui.error(f"Key file not found: {kf_path}")
|
|
44
|
+
sys.exit(1)
|
|
45
|
+
kf_pw = getpass.getpass("Key-file password: ").encode("utf-8")
|
|
46
|
+
with ui.Spinner("Unlocking key file…", silent=getattr(args, "silent", False)):
|
|
47
|
+
try:
|
|
48
|
+
content = _read_text(kf_path)
|
|
49
|
+
passphrase = core.load_keyfile(content, kf_pw)
|
|
50
|
+
except ValueError as exc:
|
|
51
|
+
ui.error(str(exc))
|
|
52
|
+
sys.exit(1)
|
|
53
|
+
return passphrase
|
|
54
|
+
return _prompt_password(confirm=confirm)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _read_text(path: str) -> str:
|
|
58
|
+
with open(path, "r", encoding="utf-8") as fh:
|
|
59
|
+
return fh.read()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _atomic_write(path: str, content: str) -> None:
|
|
63
|
+
"""Write to a temp file then atomically rename."""
|
|
64
|
+
dirname = os.path.dirname(os.path.abspath(path))
|
|
65
|
+
fd, tmp = tempfile.mkstemp(dir=dirname, suffix=".tmp")
|
|
66
|
+
try:
|
|
67
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
68
|
+
fh.write(content)
|
|
69
|
+
os.replace(tmp, path)
|
|
70
|
+
except BaseException:
|
|
71
|
+
try:
|
|
72
|
+
os.unlink(tmp)
|
|
73
|
+
except OSError:
|
|
74
|
+
pass
|
|
75
|
+
raise
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _check_output(path: str, force: bool) -> None:
|
|
79
|
+
"""If *path* exists and not --force, ask for confirmation."""
|
|
80
|
+
if os.path.exists(path):
|
|
81
|
+
if not force:
|
|
82
|
+
if not ui.confirm(f"Output file already exists: {path}\nOverwrite?"):
|
|
83
|
+
ui.error("Aborted")
|
|
84
|
+
sys.exit(1)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _human_size(n: int) -> str:
|
|
88
|
+
for unit in ("B", "KB", "MB", "GB"):
|
|
89
|
+
if n < 1024:
|
|
90
|
+
return f"{n:.1f} {unit}" if isinstance(n, float) else f"{n} {unit}"
|
|
91
|
+
n /= 1024 # type: ignore[assignment]
|
|
92
|
+
return f"{n:.1f} TB"
|
|
93
|
+
|
|
94
|
+
# ── Commands ────────────────────────────────────────────────────────
|
|
95
|
+
|
|
96
|
+
def cmd_keygen(args: argparse.Namespace) -> None:
|
|
97
|
+
path = args.keygen
|
|
98
|
+
_check_output(path, args.force)
|
|
99
|
+
pow_level = args.pow
|
|
100
|
+
pw = _prompt_password(confirm=True)
|
|
101
|
+
|
|
102
|
+
with ui.Spinner(f"Generating key file (pow {pow_level})…", silent=args.silent):
|
|
103
|
+
content = core.generate_keyfile(pw, pow_level)
|
|
104
|
+
|
|
105
|
+
_atomic_write(path, content)
|
|
106
|
+
ui.ok(f"Key file written → {path}", silent=args.silent)
|
|
107
|
+
print(path) # stdout – machine-readable
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def cmd_lock(args: argparse.Namespace) -> None:
|
|
111
|
+
src = args.lock
|
|
112
|
+
if not os.path.isfile(src):
|
|
113
|
+
ui.error(f"File not found: {src}")
|
|
114
|
+
sys.exit(1)
|
|
115
|
+
|
|
116
|
+
# Determine output path
|
|
117
|
+
if args.inplace:
|
|
118
|
+
dst = src
|
|
119
|
+
elif args.out:
|
|
120
|
+
dst = args.out
|
|
121
|
+
else:
|
|
122
|
+
dst = src + ".ncr3"
|
|
123
|
+
|
|
124
|
+
if not args.inplace:
|
|
125
|
+
_check_output(dst, args.force)
|
|
126
|
+
|
|
127
|
+
pw = _resolve_password(args)
|
|
128
|
+
pow_level = args.pow
|
|
129
|
+
|
|
130
|
+
data = open(src, "rb").read()
|
|
131
|
+
ui.info(f"Encrypting {_human_size(len(data))}…", silent=args.silent)
|
|
132
|
+
|
|
133
|
+
with ui.Spinner("Deriving key (scrypt)…", silent=args.silent):
|
|
134
|
+
raw_iv = os.urandom(32)
|
|
135
|
+
n1, n2, n3, sk, hk, pepper = core.derive_key_v3(pw, raw_iv, pow_level)
|
|
136
|
+
|
|
137
|
+
with ui.Spinner("Encrypting…", silent=args.silent):
|
|
138
|
+
ct = core.encrypt_raw(data, n1, n2, n3, sk, hk, pepper, raw_iv, pow_level)
|
|
139
|
+
|
|
140
|
+
_atomic_write(dst, ct)
|
|
141
|
+
ui.ok(f"Encrypted → {dst}", silent=args.silent)
|
|
142
|
+
print(dst)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def cmd_unlock(args: argparse.Namespace) -> None:
|
|
146
|
+
src = args.unlock
|
|
147
|
+
if not os.path.isfile(src):
|
|
148
|
+
ui.error(f"File not found: {src}")
|
|
149
|
+
sys.exit(1)
|
|
150
|
+
|
|
151
|
+
content = _read_text(src)
|
|
152
|
+
version, file_strength = core.detect_version(content)
|
|
153
|
+
|
|
154
|
+
# Determine output path
|
|
155
|
+
if args.inplace:
|
|
156
|
+
dst = src
|
|
157
|
+
elif args.out:
|
|
158
|
+
dst = args.out
|
|
159
|
+
else:
|
|
160
|
+
# strip .ncr3 / .ncr2 extension
|
|
161
|
+
base, ext = os.path.splitext(src)
|
|
162
|
+
if ext.lower() in (".ncr3", ".ncr2"):
|
|
163
|
+
dst = base
|
|
164
|
+
else:
|
|
165
|
+
dst = src + ".dec"
|
|
166
|
+
|
|
167
|
+
if not args.inplace:
|
|
168
|
+
_check_output(dst, args.force)
|
|
169
|
+
|
|
170
|
+
pw = _resolve_password(args)
|
|
171
|
+
|
|
172
|
+
if args.pow != 3:
|
|
173
|
+
ui.info("Note: --pow flag is ignored during unlock (auto-detected from file)", silent=args.silent)
|
|
174
|
+
|
|
175
|
+
iv_hex = content.split("\n", 2)[1]
|
|
176
|
+
raw_iv = bytes.fromhex(iv_hex)
|
|
177
|
+
|
|
178
|
+
n3 = 0
|
|
179
|
+
pepper = b""
|
|
180
|
+
with ui.Spinner("Deriving key…", silent=args.silent):
|
|
181
|
+
if version == core.VERSION_3:
|
|
182
|
+
n1, n2, n3, sk, hk, pepper = core.derive_key_v3(pw, raw_iv, file_strength)
|
|
183
|
+
else:
|
|
184
|
+
n1, n2, sk, hk = core.derive_key_v2(pw, raw_iv)
|
|
185
|
+
|
|
186
|
+
with ui.Spinner("Decrypting…", silent=args.silent):
|
|
187
|
+
try:
|
|
188
|
+
if version == core.VERSION_3:
|
|
189
|
+
pt = core.decrypt_raw_v3(content, n1, n2, n3, sk, hk, pepper)
|
|
190
|
+
else:
|
|
191
|
+
pt = core.decrypt_raw_v2(content, n1, n2, sk, hk)
|
|
192
|
+
except ValueError as exc:
|
|
193
|
+
ui.error(str(exc))
|
|
194
|
+
sys.exit(1)
|
|
195
|
+
|
|
196
|
+
# Write as binary
|
|
197
|
+
dirname = os.path.dirname(os.path.abspath(dst))
|
|
198
|
+
fd, tmp = tempfile.mkstemp(dir=dirname, suffix=".tmp")
|
|
199
|
+
try:
|
|
200
|
+
with os.fdopen(fd, "wb") as fh:
|
|
201
|
+
fh.write(pt)
|
|
202
|
+
os.replace(tmp, dst)
|
|
203
|
+
except BaseException:
|
|
204
|
+
try:
|
|
205
|
+
os.unlink(tmp)
|
|
206
|
+
except OSError:
|
|
207
|
+
pass
|
|
208
|
+
raise
|
|
209
|
+
|
|
210
|
+
ui.ok(f"Decrypted → {dst} ({_human_size(len(pt))})", silent=args.silent)
|
|
211
|
+
print(dst)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def cmd_verify(args: argparse.Namespace) -> None:
|
|
215
|
+
src = args.verify
|
|
216
|
+
if not os.path.isfile(src):
|
|
217
|
+
ui.error(f"File not found: {src}")
|
|
218
|
+
sys.exit(1)
|
|
219
|
+
|
|
220
|
+
content = _read_text(src)
|
|
221
|
+
pw = _resolve_password(args)
|
|
222
|
+
|
|
223
|
+
if args.pow != 3:
|
|
224
|
+
ui.info("Note: --pow flag is ignored during verify (auto-detected from file)", silent=args.silent)
|
|
225
|
+
|
|
226
|
+
with ui.Spinner("Verifying HMAC…", silent=args.silent):
|
|
227
|
+
ok = core.verify_hmac(content, pw)
|
|
228
|
+
|
|
229
|
+
if ok:
|
|
230
|
+
ui.ok("OK — HMAC valid", silent=args.silent)
|
|
231
|
+
print("OK")
|
|
232
|
+
sys.exit(0)
|
|
233
|
+
else:
|
|
234
|
+
ui.error("TAMPERED — HMAC mismatch")
|
|
235
|
+
print("TAMPERED")
|
|
236
|
+
sys.exit(1)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def cmd_info(args: argparse.Namespace) -> None:
|
|
240
|
+
src = args.info
|
|
241
|
+
if not os.path.isfile(src):
|
|
242
|
+
ui.error(f"File not found: {src}")
|
|
243
|
+
sys.exit(1)
|
|
244
|
+
|
|
245
|
+
content = _read_text(src)
|
|
246
|
+
try:
|
|
247
|
+
hdr = core.parse_header(content)
|
|
248
|
+
except ValueError as exc:
|
|
249
|
+
ui.error(str(exc))
|
|
250
|
+
sys.exit(1)
|
|
251
|
+
|
|
252
|
+
file_size = os.path.getsize(src)
|
|
253
|
+
sys.stderr.write(
|
|
254
|
+
f" Version: {ui.bold(hdr['version'])}\n"
|
|
255
|
+
f" Pow: {hdr['strength']}\n"
|
|
256
|
+
f" IV: {hdr['iv'][:32]}{'…' if len(hdr['iv']) > 32 else ''}\n"
|
|
257
|
+
f" HMAC: {hdr['hmac'][:32]}…\n"
|
|
258
|
+
f" Blocks: {hdr['block_count']}\n"
|
|
259
|
+
f" File size: {_human_size(file_size)}\n"
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def cmd_bench(args: argparse.Namespace) -> None:
|
|
264
|
+
pw = b"benchmark-password-1234"
|
|
265
|
+
salt = os.urandom(32)
|
|
266
|
+
|
|
267
|
+
sys.stderr.write(ui.bold("\n KDF Benchmark (scrypt, pow=3)\n"))
|
|
268
|
+
t0 = time.perf_counter()
|
|
269
|
+
core.derive_key_v3(pw, salt, 3)
|
|
270
|
+
kdf_time = time.perf_counter() - t0
|
|
271
|
+
sys.stderr.write(f" Time: {kdf_time:.2f}s\n")
|
|
272
|
+
|
|
273
|
+
# Pre-derive keys at strength=1 for encrypt speed tests
|
|
274
|
+
n1, n2, n3, sk, hk, pepper = core.derive_key_v3(pw, salt, 1)
|
|
275
|
+
|
|
276
|
+
sizes = [256, 1024, 4096, 16384, 65536]
|
|
277
|
+
sys.stderr.write(ui.bold("\n Encrypt Speed\n"))
|
|
278
|
+
sys.stderr.write(f" {'Size':>6s} {'Time':>8s} {'Speed':>10s}\n")
|
|
279
|
+
sys.stderr.write(f" {'─' * 6} {'─' * 8} {'─' * 10}\n")
|
|
280
|
+
|
|
281
|
+
for sz in sizes:
|
|
282
|
+
data = os.urandom(sz)
|
|
283
|
+
raw_iv = os.urandom(32)
|
|
284
|
+
t0 = time.perf_counter()
|
|
285
|
+
core.encrypt_raw(data, n1, n2, n3, sk, hk, pepper, raw_iv)
|
|
286
|
+
elapsed = time.perf_counter() - t0
|
|
287
|
+
label = f"{sz}B" if sz < 1024 else f"{sz // 1024}KB"
|
|
288
|
+
speed = sz / elapsed if elapsed > 0 else float("inf")
|
|
289
|
+
sys.stderr.write(f" {label:>6s} {elapsed:>7.3f}s {speed:>8.0f} B/s\n")
|
|
290
|
+
|
|
291
|
+
sys.stderr.write("\n")
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def cmd_test(args: argparse.Namespace) -> None:
|
|
295
|
+
passed: int = 0
|
|
296
|
+
failed: int = 0
|
|
297
|
+
|
|
298
|
+
sys.stderr.write(ui.bold("\n NCR Self-Tests\n\n"))
|
|
299
|
+
for name, fn in core.SELF_TESTS:
|
|
300
|
+
try:
|
|
301
|
+
fn()
|
|
302
|
+
sys.stderr.write(f" {ui.green('PASS')} {name}\n")
|
|
303
|
+
passed = passed + 1
|
|
304
|
+
except Exception as exc:
|
|
305
|
+
sys.stderr.write(f" {ui.red('FAIL')} {name}: {exc}\n")
|
|
306
|
+
failed = failed + 1
|
|
307
|
+
|
|
308
|
+
sys.stderr.write(f"\n {passed} passed, {failed} failed\n\n")
|
|
309
|
+
sys.exit(1 if failed else 0)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def cmd_version() -> None:
|
|
313
|
+
print(f"ncr {__version__}")
|
|
314
|
+
|
|
315
|
+
# ── Argument parser ─────────────────────────────────────────────────
|
|
316
|
+
|
|
317
|
+
def _build_parser() -> argparse.ArgumentParser:
|
|
318
|
+
p = argparse.ArgumentParser(
|
|
319
|
+
prog="ncr",
|
|
320
|
+
description="NCR3 encryption tool — encrypt, decrypt, and verify files.",
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
# Commands (mutually exclusive at the top level)
|
|
324
|
+
cmd = p.add_mutually_exclusive_group()
|
|
325
|
+
cmd.add_argument("--keygen", metavar="KEYFILE", help="Generate a new key file")
|
|
326
|
+
cmd.add_argument("--lock", metavar="FILE", help="Encrypt a file")
|
|
327
|
+
cmd.add_argument("--unlock", metavar="FILE", help="Decrypt a file")
|
|
328
|
+
cmd.add_argument("--verify", metavar="FILE", help="Verify HMAC without decrypting")
|
|
329
|
+
cmd.add_argument("--info", metavar="FILE", help="Show file info (no password needed)")
|
|
330
|
+
cmd.add_argument("--bench", action="store_true", help="Run benchmarks")
|
|
331
|
+
cmd.add_argument("--test", action="store_true", help="Run internal self-tests")
|
|
332
|
+
cmd.add_argument("--version", action="store_true", help="Print version")
|
|
333
|
+
|
|
334
|
+
# Shared options
|
|
335
|
+
p.add_argument("--key", "-k", metavar="KEYFILE", help="Key file for lock/unlock/verify")
|
|
336
|
+
p.add_argument("--out", "-o", metavar="PATH", help="Output path override")
|
|
337
|
+
p.add_argument("--inplace", "-i", action="store_true", help="Overwrite original file")
|
|
338
|
+
p.add_argument("--silent", "-s", action="store_true", help="Suppress non-error output")
|
|
339
|
+
p.add_argument("--force", "-f", action="store_true", help="Overwrite without confirmation")
|
|
340
|
+
p.add_argument("--pow", type=int, choices=range(1, 6), default=3,
|
|
341
|
+
metavar="1-5", help="KDF strength (pow) level (1=fast, 3=default, 5=strong). Ignored during unlock.")
|
|
342
|
+
|
|
343
|
+
return p
|
|
344
|
+
|
|
345
|
+
# ── Main ────────────────────────────────────────────────────────────
|
|
346
|
+
|
|
347
|
+
def main() -> None:
|
|
348
|
+
parser = _build_parser()
|
|
349
|
+
args = parser.parse_args()
|
|
350
|
+
|
|
351
|
+
try:
|
|
352
|
+
if args.keygen:
|
|
353
|
+
cmd_keygen(args)
|
|
354
|
+
elif args.lock:
|
|
355
|
+
cmd_lock(args)
|
|
356
|
+
elif args.unlock:
|
|
357
|
+
cmd_unlock(args)
|
|
358
|
+
elif args.verify:
|
|
359
|
+
cmd_verify(args)
|
|
360
|
+
elif args.info:
|
|
361
|
+
cmd_info(args)
|
|
362
|
+
elif args.bench:
|
|
363
|
+
cmd_bench(args)
|
|
364
|
+
elif args.test:
|
|
365
|
+
cmd_test(args)
|
|
366
|
+
elif args.version:
|
|
367
|
+
cmd_version()
|
|
368
|
+
else:
|
|
369
|
+
parser.print_help(sys.stderr)
|
|
370
|
+
sys.exit(2)
|
|
371
|
+
except KeyboardInterrupt:
|
|
372
|
+
sys.exit(130)
|
|
373
|
+
except SystemExit:
|
|
374
|
+
raise
|
|
375
|
+
except Exception as exc:
|
|
376
|
+
ui.error(str(exc))
|
|
377
|
+
sys.exit(1)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
if __name__ == "__main__":
|
|
381
|
+
main()
|