transcrypto 1.6.0__py3-none-any.whl → 1.8.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.
- transcrypto/__init__.py +7 -0
- transcrypto/aes.py +150 -44
- transcrypto/base.py +384 -520
- transcrypto/cli/__init__.py +3 -0
- transcrypto/cli/aeshash.py +368 -0
- transcrypto/cli/bidsecret.py +334 -0
- transcrypto/cli/clibase.py +303 -0
- transcrypto/cli/intmath.py +427 -0
- transcrypto/cli/publicalgos.py +877 -0
- transcrypto/constants.py +20070 -1906
- transcrypto/dsa.py +132 -99
- transcrypto/elgamal.py +116 -84
- transcrypto/modmath.py +88 -78
- transcrypto/profiler.py +228 -175
- transcrypto/rsa.py +126 -90
- transcrypto/sss.py +122 -70
- transcrypto/transcrypto.py +419 -1423
- {transcrypto-1.6.0.dist-info → transcrypto-1.8.0.dist-info}/METADATA +88 -66
- transcrypto-1.8.0.dist-info/RECORD +23 -0
- {transcrypto-1.6.0.dist-info → transcrypto-1.8.0.dist-info}/WHEEL +1 -2
- transcrypto-1.8.0.dist-info/entry_points.txt +4 -0
- transcrypto/safetrans.py +0 -1228
- transcrypto-1.6.0.dist-info/RECORD +0 -18
- transcrypto-1.6.0.dist-info/top_level.txt +0 -1
- {transcrypto-1.6.0.dist-info → transcrypto-1.8.0.dist-info}/licenses/LICENSE +0 -0
transcrypto/transcrypto.py
CHANGED
|
@@ -1,1465 +1,461 @@
|
|
|
1
|
-
|
|
2
|
-
#
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
1
|
+
# SPDX-FileCopyrightText: Copyright 2026 Daniel Balparda <balparda@github.com>
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
"""Balparda's TransCrypto command line interface (CLI).
|
|
4
|
+
|
|
5
|
+
See <transcrypto.md> for documentation on how to use. Quick examples:
|
|
6
|
+
|
|
7
|
+
--- Randomness ---
|
|
8
|
+
poetry run transcrypto random bits 16
|
|
9
|
+
poetry run transcrypto random int 1000 2000
|
|
10
|
+
poetry run transcrypto random bytes 32
|
|
11
|
+
poetry run transcrypto random prime 64
|
|
12
|
+
|
|
13
|
+
--- Primes ---
|
|
14
|
+
poetry run transcrypto isprime 428568761
|
|
15
|
+
poetry run transcrypto primegen 100 -c 3
|
|
16
|
+
poetry run transcrypto mersenne -k 2 -C 17
|
|
17
|
+
|
|
18
|
+
--- Integer / Modular Math ---
|
|
19
|
+
poetry run transcrypto gcd 462 1071
|
|
20
|
+
poetry run transcrypto xgcd 127 13
|
|
21
|
+
poetry run transcrypto mod inv 17 97
|
|
22
|
+
poetry run transcrypto mod div 6 127 13
|
|
23
|
+
poetry run transcrypto mod exp 438 234 127
|
|
24
|
+
poetry run transcrypto mod poly 12 17 10 20 30
|
|
25
|
+
poetry run transcrypto mod lagrange 5 13 2:4 6:3 7:1
|
|
26
|
+
poetry run transcrypto mod crt 6 7 127 13
|
|
27
|
+
|
|
28
|
+
--- Hashing ---
|
|
29
|
+
poetry run transcrypto hash sha256 xyz
|
|
30
|
+
poetry run transcrypto --input-format b64 hash sha512 -- eHl6
|
|
31
|
+
poetry run transcrypto hash file /etc/passwd --digest sha512
|
|
32
|
+
|
|
33
|
+
--- AES ---
|
|
34
|
+
poetry run transcrypto --output-format b64 aes key "correct horse battery staple"
|
|
35
|
+
poetry run transcrypto -i b64 -o b64 aes encrypt -k "<b64key>" -- "secret"
|
|
36
|
+
poetry run transcrypto -i b64 -o b64 aes decrypt -k "<b64key>" -- "<ciphertext>"
|
|
37
|
+
poetry run transcrypto aes ecb encrypt -k "<b64key>" "<128bithexblock>"
|
|
38
|
+
poetry run transcrypto aes ecb decrypt -k "<b64key>" "<128bithexblock>"
|
|
39
|
+
|
|
40
|
+
--- RSA ---
|
|
41
|
+
poetry run transcrypto -p rsa-key rsa new --bits 2048
|
|
42
|
+
poetry run transcrypto -p rsa-key.pub rsa rawencrypt <plaintext>
|
|
43
|
+
poetry run transcrypto -p rsa-key.priv rsa rawdecrypt <ciphertext>
|
|
44
|
+
poetry run transcrypto -p rsa-key.priv rsa rawsign <message>
|
|
45
|
+
poetry run transcrypto -p rsa-key.pub rsa rawverify <message> <signature>
|
|
46
|
+
poetry run transcrypto -i bin -o b64 -p rsa-key.pub rsa encrypt -a <aad> <plaintext>
|
|
47
|
+
poetry run transcrypto -i b64 -o bin -p rsa-key.priv rsa decrypt -a <aad> -- <ciphertext>
|
|
48
|
+
poetry run transcrypto -i bin -o b64 -p rsa-key.priv rsa sign <message>
|
|
49
|
+
poetry run transcrypto -i b64 -p rsa-key.pub rsa verify -- <message> <signature>
|
|
50
|
+
|
|
51
|
+
--- ElGamal ---
|
|
52
|
+
poetry run transcrypto -p eg-key elgamal shared --bits 2048
|
|
53
|
+
poetry run transcrypto -p eg-key elgamal new
|
|
54
|
+
poetry run transcrypto -p eg-key.pub elgamal rawencrypt <plaintext>
|
|
55
|
+
poetry run transcrypto -p eg-key.priv elgamal rawdecrypt <c1:c2>
|
|
56
|
+
poetry run transcrypto -p eg-key.priv elgamal rawsign <message>
|
|
57
|
+
poetry run transcrypto -p eg-key.pub elgamal rawverify <message> <s1:s2>
|
|
58
|
+
poetry run transcrypto -i bin -o b64 -p eg-key.pub elgamal encrypt <plaintext>
|
|
59
|
+
poetry run transcrypto -i b64 -o bin -p eg-key.priv elgamal decrypt -- <ciphertext>
|
|
60
|
+
poetry run transcrypto -i bin -o b64 -p eg-key.priv elgamal sign <message>
|
|
61
|
+
poetry run transcrypto -i b64 -p eg-key.pub elgamal verify -- <message> <signature>
|
|
62
|
+
|
|
63
|
+
--- DSA ---
|
|
64
|
+
poetry run transcrypto -p dsa-key dsa shared --p-bits 2048 --q-bits 256
|
|
65
|
+
poetry run transcrypto -p dsa-key dsa new
|
|
66
|
+
poetry run transcrypto -p dsa-key.priv dsa rawsign <message>
|
|
67
|
+
poetry run transcrypto -p dsa-key.pub dsa rawverify <message> <s1:s2>
|
|
68
|
+
poetry run transcrypto -i bin -o b64 -p dsa-key.priv dsa sign <message>
|
|
69
|
+
poetry run transcrypto -i b64 -p dsa-key.pub dsa verify -- <message> <signature>
|
|
70
|
+
|
|
71
|
+
--- Public Bid ---
|
|
72
|
+
poetry run transcrypto -i bin bid new "tomorrow it will rain"
|
|
73
|
+
poetry run transcrypto -o bin bid verify
|
|
74
|
+
|
|
75
|
+
--- Shamir Secret Sharing (SSS) ---
|
|
76
|
+
poetry run transcrypto -p sss-key sss new 3 --bits 1024
|
|
77
|
+
poetry run transcrypto -p sss-key sss rawshares <secret> <n>
|
|
78
|
+
poetry run transcrypto -p sss-key sss rawrecover
|
|
79
|
+
poetry run transcrypto -p sss-key sss rawverify <secret>
|
|
80
|
+
poetry run transcrypto -i bin -p sss-key sss shares <secret> <n>
|
|
81
|
+
poetry run transcrypto -o bin -p sss-key sss recover
|
|
82
|
+
|
|
83
|
+
--- Markdown ---
|
|
84
|
+
poetry run transcrypto markdown > transcrypto.md
|
|
85
|
+
|
|
86
|
+
Test this CLI with:
|
|
87
|
+
|
|
88
|
+
poetry run pytest -vvv tests/transcrypto_test.py
|
|
22
89
|
"""
|
|
23
90
|
|
|
24
91
|
from __future__ import annotations
|
|
25
92
|
|
|
26
|
-
import
|
|
93
|
+
import dataclasses
|
|
27
94
|
import enum
|
|
28
|
-
import glob
|
|
29
95
|
import logging
|
|
30
|
-
|
|
31
|
-
import sys
|
|
32
|
-
from typing import Any, Iterable
|
|
96
|
+
import pathlib
|
|
33
97
|
|
|
34
|
-
|
|
98
|
+
import click
|
|
99
|
+
import typer
|
|
35
100
|
|
|
36
|
-
from . import
|
|
101
|
+
from transcrypto.cli import clibase
|
|
37
102
|
|
|
38
|
-
|
|
39
|
-
__version__
|
|
40
|
-
|
|
103
|
+
from . import (
|
|
104
|
+
__version__,
|
|
105
|
+
aes,
|
|
106
|
+
base,
|
|
107
|
+
)
|
|
41
108
|
|
|
42
109
|
|
|
43
|
-
|
|
110
|
+
class IOFormat(enum.Enum):
|
|
111
|
+
"""Input/output data format for CLI commands."""
|
|
44
112
|
|
|
113
|
+
hex = 'hex'
|
|
114
|
+
b64 = 'b64'
|
|
115
|
+
bin = 'bin'
|
|
45
116
|
|
|
46
|
-
def _ParseInt(s: str, /) -> int:
|
|
47
|
-
"""Parse int, try to determine if binary, octal, decimal, or hexadecimal."""
|
|
48
|
-
s = s.strip().lower().replace('_', '')
|
|
49
|
-
base_guess = 10
|
|
50
|
-
if s.startswith('0x'):
|
|
51
|
-
base_guess = 16
|
|
52
|
-
elif s.startswith('0b'):
|
|
53
|
-
base_guess = 2
|
|
54
|
-
elif s.startswith('0o'):
|
|
55
|
-
base_guess = 8
|
|
56
|
-
return int(s, base_guess)
|
|
57
117
|
|
|
118
|
+
@dataclasses.dataclass(kw_only=True, slots=True, frozen=True)
|
|
119
|
+
class TransConfig(clibase.CLIConfig):
|
|
120
|
+
"""CLI global context, storing the configuration."""
|
|
58
121
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
122
|
+
input_format: IOFormat
|
|
123
|
+
output_format: IOFormat
|
|
124
|
+
key_path: pathlib.Path | None
|
|
125
|
+
protect: str | None
|
|
62
126
|
|
|
63
127
|
|
|
64
|
-
|
|
65
|
-
"""
|
|
66
|
-
RAW = 0
|
|
67
|
-
HEXADECIMAL = 1
|
|
68
|
-
BASE64 = 2
|
|
128
|
+
def RequireKeyPath(config: TransConfig, command: str, /) -> str:
|
|
129
|
+
"""Ensure key path is provided and valid.
|
|
69
130
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
if sum((is_hex, is_base64, is_bin)) > 1:
|
|
74
|
-
raise base.InputError('Only one of --hex, --b64, --bin can be set, if any.')
|
|
75
|
-
if is_bin:
|
|
76
|
-
return _StrBytesType.RAW
|
|
77
|
-
if is_base64:
|
|
78
|
-
return _StrBytesType.BASE64
|
|
79
|
-
return _StrBytesType.HEXADECIMAL # default
|
|
131
|
+
Args:
|
|
132
|
+
config (TransConfig): context
|
|
133
|
+
command (str): command name
|
|
80
134
|
|
|
135
|
+
Raises:
|
|
136
|
+
base.InputError: input error
|
|
81
137
|
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
138
|
+
Returns:
|
|
139
|
+
str: key path
|
|
140
|
+
|
|
141
|
+
"""
|
|
142
|
+
if config.key_path is None:
|
|
143
|
+
raise base.InputError(f'you must provide -p/--key-path option for {command!r}')
|
|
144
|
+
if config.key_path.exists() and config.key_path.is_dir():
|
|
145
|
+
raise base.InputError(f'-p/--key-path must not be a directory: {str(config.key_path)!r}')
|
|
146
|
+
return str(config.key_path)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def ParseInt(s: str, /, *, min_value: int | None = None) -> int:
|
|
150
|
+
"""Parse int, try to determine if binary, octal, decimal, or hexadecimal.
|
|
151
|
+
|
|
152
|
+
Args:
|
|
153
|
+
s (str): putative int
|
|
154
|
+
min_value (int | None, optional): minimum allowed value. Defaults to None.
|
|
155
|
+
|
|
156
|
+
Returns:
|
|
157
|
+
int: parsed int
|
|
158
|
+
|
|
159
|
+
Raises:
|
|
160
|
+
base.InputError: input (conversion) error
|
|
161
|
+
|
|
162
|
+
"""
|
|
163
|
+
raw: str = s.strip()
|
|
164
|
+
if not raw:
|
|
165
|
+
raise base.InputError(f'invalid int: {s!r}')
|
|
166
|
+
try:
|
|
167
|
+
clean: str = raw.lower().replace('_', '')
|
|
168
|
+
value: int
|
|
169
|
+
if clean.startswith('0x'):
|
|
170
|
+
value = int(clean, 16)
|
|
171
|
+
elif clean.startswith('0b'):
|
|
172
|
+
value = int(clean, 2)
|
|
173
|
+
elif clean.startswith('0o'):
|
|
174
|
+
value = int(clean, 8)
|
|
175
|
+
else:
|
|
176
|
+
value = int(clean, 10)
|
|
177
|
+
if min_value is not None and value < min_value:
|
|
178
|
+
raise base.InputError(f'int must be ≥ {min_value}, got {value}')
|
|
179
|
+
return value
|
|
180
|
+
except ValueError as err:
|
|
181
|
+
raise base.InputError(f'invalid int: {s!r}') from err
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def ParseIntPairCLI(s: str, /) -> tuple[int, int]:
|
|
185
|
+
"""Parse a CLI int pair of the form `a:b`.
|
|
186
|
+
|
|
187
|
+
Args:
|
|
188
|
+
s (str): string to parse
|
|
189
|
+
|
|
190
|
+
Raises:
|
|
191
|
+
base.InputError: if the input string is not a valid int pair
|
|
192
|
+
|
|
193
|
+
Returns:
|
|
194
|
+
tuple[int, int]: parsed int pair
|
|
195
|
+
|
|
196
|
+
"""
|
|
197
|
+
parts: list[str] = s.split(':')
|
|
198
|
+
if len(parts) != 2: # noqa: PLR2004
|
|
199
|
+
raise base.InputError(f'invalid int(s): {s!r} (expected a:b)')
|
|
200
|
+
return (ParseInt(parts[0]), ParseInt(parts[1]))
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def BytesFromText(text: str, fmt: IOFormat, /) -> bytes:
|
|
204
|
+
"""Parse bytes according to `fmt` (IOFormat.hex|b64|bin).
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
text (str): text
|
|
208
|
+
fmt (IOFormat): input format
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
bytes: parsed bytes
|
|
212
|
+
|
|
213
|
+
"""
|
|
214
|
+
match fmt:
|
|
215
|
+
case IOFormat.bin:
|
|
86
216
|
return text.encode('utf-8')
|
|
87
|
-
case
|
|
217
|
+
case IOFormat.hex:
|
|
88
218
|
return base.HexToBytes(text)
|
|
89
|
-
case
|
|
219
|
+
case IOFormat.b64:
|
|
90
220
|
return base.EncodedToBytes(text)
|
|
91
221
|
|
|
92
222
|
|
|
93
|
-
def
|
|
94
|
-
"""
|
|
95
|
-
|
|
96
|
-
|
|
223
|
+
def BytesToText(b: bytes, fmt: IOFormat, /) -> str:
|
|
224
|
+
"""Format bytes according to `fmt` (IOFormat.hex|b64|bin).
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
b (bytes): blob
|
|
228
|
+
fmt (IOFormat): output format
|
|
229
|
+
|
|
230
|
+
Returns:
|
|
231
|
+
str: formatted string
|
|
232
|
+
|
|
233
|
+
"""
|
|
234
|
+
match fmt:
|
|
235
|
+
case IOFormat.bin:
|
|
97
236
|
return b.decode('utf-8', errors='replace')
|
|
98
|
-
case
|
|
237
|
+
case IOFormat.hex:
|
|
99
238
|
return base.BytesToHex(b)
|
|
100
|
-
case
|
|
239
|
+
case IOFormat.b64:
|
|
101
240
|
return base.BytesToEncoded(b)
|
|
102
241
|
|
|
103
242
|
|
|
104
|
-
def
|
|
105
|
-
"""
|
|
106
|
-
return aes.AESKey.FromStaticPassword(password) if password else None
|
|
243
|
+
def SaveObj(obj: base.CryptoKey, path: str, password: str | None, /) -> None:
|
|
244
|
+
"""Save object.
|
|
107
245
|
|
|
246
|
+
Args:
|
|
247
|
+
obj (base.CryptoKey): object
|
|
248
|
+
path (str): path
|
|
249
|
+
password (str | None): password
|
|
108
250
|
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
key: aes.AESKey | None = _MaybePasswordKey(password)
|
|
251
|
+
"""
|
|
252
|
+
key: aes.AESKey | None = aes.AESKey.FromStaticPassword(password) if password else None
|
|
112
253
|
blob: bytes = base.Serialize(obj, file_path=path, key=key)
|
|
113
254
|
logging.info('saved object: %s (%s)', path, base.HumanizedBytes(len(blob)))
|
|
114
255
|
|
|
115
256
|
|
|
116
|
-
def
|
|
117
|
-
"""Load object.
|
|
118
|
-
|
|
119
|
-
|
|
257
|
+
def LoadObj[T](path: str, password: str | None, expect: type[T], /) -> T:
|
|
258
|
+
"""Load object.
|
|
259
|
+
|
|
260
|
+
Args:
|
|
261
|
+
path (str): path
|
|
262
|
+
password (str | None): password
|
|
263
|
+
expect (type[T]): type to expect
|
|
264
|
+
|
|
265
|
+
Raises:
|
|
266
|
+
base.InputError: input error
|
|
267
|
+
|
|
268
|
+
Returns:
|
|
269
|
+
T: loaded object
|
|
270
|
+
|
|
271
|
+
"""
|
|
272
|
+
key: aes.AESKey | None = aes.AESKey.FromStaticPassword(password) if password else None
|
|
273
|
+
obj: T = base.DeSerialize(file_path=path, key=key)
|
|
120
274
|
if not isinstance(obj, expect):
|
|
121
275
|
raise base.InputError(
|
|
122
|
-
|
|
276
|
+
f'Object loaded from {path} is of invalid type {type(obj)}, expected {expect}'
|
|
277
|
+
)
|
|
123
278
|
return obj
|
|
124
279
|
|
|
125
280
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
#
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
281
|
+
# ============================= "TRANSCRYPTO"/ROOT COMMAND =========================================
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
# CLI app setup, this is an important object and can be imported elsewhere and called
|
|
285
|
+
app = typer.Typer(
|
|
286
|
+
add_completion=True,
|
|
287
|
+
no_args_is_help=True,
|
|
288
|
+
help=( # keep in sync with Main().help
|
|
289
|
+
'transcrypto: CLI for number theory, hash, AES, RSA, El-Gamal, DSA, bidding, SSS, and more.'
|
|
290
|
+
),
|
|
291
|
+
epilog=(
|
|
292
|
+
'Example:\n\n\n\n'
|
|
293
|
+
'# --- Randomness ---\n\n'
|
|
294
|
+
'poetry run transcrypto random bits 16\n\n'
|
|
295
|
+
'poetry run transcrypto random int 1000 2000\n\n'
|
|
296
|
+
'poetry run transcrypto random bytes 32\n\n'
|
|
297
|
+
'poetry run transcrypto random prime 64\n\n\n\n'
|
|
298
|
+
'# --- Primes ---\n\n'
|
|
299
|
+
'poetry run transcrypto isprime 428568761\n\n'
|
|
300
|
+
'poetry run transcrypto primegen 100 -c 3\n\n'
|
|
301
|
+
'poetry run transcrypto mersenne -k 2 -C 17\n\n\n\n'
|
|
302
|
+
'# --- Integer / Modular Math ---\n\n'
|
|
303
|
+
'poetry run transcrypto gcd 462 1071\n\n'
|
|
304
|
+
'poetry run transcrypto xgcd 127 13\n\n'
|
|
305
|
+
'poetry run transcrypto mod inv 17 97\n\n'
|
|
306
|
+
'poetry run transcrypto mod div 6 127 13\n\n'
|
|
307
|
+
'poetry run transcrypto mod exp 438 234 127\n\n'
|
|
308
|
+
'poetry run transcrypto mod poly 12 17 10 20 30\n\n'
|
|
309
|
+
'poetry run transcrypto mod lagrange 5 13 2:4 6:3 7:1\n\n'
|
|
310
|
+
'poetry run transcrypto mod crt 6 7 127 13\n\n\n\n'
|
|
311
|
+
'# --- Hashing ---\n\n'
|
|
312
|
+
'poetry run transcrypto hash sha256 xyz\n\n'
|
|
313
|
+
'poetry run transcrypto --input-format b64 hash sha512 -- eHl6\n\n'
|
|
314
|
+
'poetry run transcrypto hash file /etc/passwd --digest sha512\n\n\n\n'
|
|
315
|
+
'# --- AES ---\n\n'
|
|
316
|
+
'poetry run transcrypto --output-format b64 aes key "correct horse battery staple"\n\n'
|
|
317
|
+
'poetry run transcrypto -i b64 -o b64 aes encrypt -k "<b64key>" -- "secret"\n\n'
|
|
318
|
+
'poetry run transcrypto -i b64 -o b64 aes decrypt -k "<b64key>" -- "<ciphertext>"\n\n'
|
|
319
|
+
'poetry run transcrypto aes ecb encrypt -k "<b64key>" "<128bithexblock>"\n\n'
|
|
320
|
+
'poetry run transcrypto aes ecb decrypt -k "<b64key>" "<128bithexblock>"\n\n\n\n'
|
|
321
|
+
'# --- RSA ---\n\n'
|
|
322
|
+
'poetry run transcrypto -p rsa-key rsa new --bits 2048\n\n'
|
|
323
|
+
'poetry run transcrypto -p rsa-key.pub rsa rawencrypt <plaintext>\n\n'
|
|
324
|
+
'poetry run transcrypto -p rsa-key.priv rsa rawdecrypt <ciphertext>\n\n'
|
|
325
|
+
'poetry run transcrypto -p rsa-key.priv rsa rawsign <message>\n\n'
|
|
326
|
+
'poetry run transcrypto -p rsa-key.pub rsa rawverify <message> <signature>\n\n'
|
|
327
|
+
'poetry run transcrypto -i bin -o b64 -p rsa-key.pub rsa encrypt -a <aad> <plaintext>\n\n'
|
|
328
|
+
'poetry run transcrypto -i b64 -o bin -p rsa-key.priv rsa decrypt -a <aad> -- <ciphertext>\n\n'
|
|
329
|
+
'poetry run transcrypto -i bin -o b64 -p rsa-key.priv rsa sign <message>\n\n'
|
|
330
|
+
'poetry run transcrypto -i b64 -p rsa-key.pub rsa verify -- <message> <signature>\n\n\n\n'
|
|
331
|
+
'# --- ElGamal ---\n\n'
|
|
332
|
+
'poetry run transcrypto -p eg-key elgamal shared --bits 2048\n\n'
|
|
333
|
+
'poetry run transcrypto -p eg-key elgamal new\n\n'
|
|
334
|
+
'poetry run transcrypto -p eg-key.pub elgamal rawencrypt <plaintext>\n\n'
|
|
335
|
+
'poetry run transcrypto -p eg-key.priv elgamal rawdecrypt <c1:c2>\n\n'
|
|
336
|
+
'poetry run transcrypto -p eg-key.priv elgamal rawsign <message>\n\n'
|
|
337
|
+
'poetry run transcrypto -p eg-key.pub elgamal rawverify <message> <s1:s2>\n\n'
|
|
338
|
+
'poetry run transcrypto -i bin -o b64 -p eg-key.pub elgamal encrypt <plaintext>\n\n'
|
|
339
|
+
'poetry run transcrypto -i b64 -o bin -p eg-key.priv elgamal decrypt -- <ciphertext>\n\n'
|
|
340
|
+
'poetry run transcrypto -i bin -o b64 -p eg-key.priv elgamal sign <message>\n\n'
|
|
341
|
+
'poetry run transcrypto -i b64 -p eg-key.pub elgamal verify -- <message> <signature>\n\n\n\n'
|
|
342
|
+
'# --- DSA ---\n\n'
|
|
343
|
+
'poetry run transcrypto -p dsa-key dsa shared --p-bits 2048 --q-bits 256\n\n'
|
|
344
|
+
'poetry run transcrypto -p dsa-key dsa new\n\n'
|
|
345
|
+
'poetry run transcrypto -p dsa-key.priv dsa rawsign <message>\n\n'
|
|
346
|
+
'poetry run transcrypto -p dsa-key.pub dsa rawverify <message> <s1:s2>\n\n'
|
|
347
|
+
'poetry run transcrypto -i bin -o b64 -p dsa-key.priv dsa sign <message>\n\n'
|
|
348
|
+
'poetry run transcrypto -i b64 -p dsa-key.pub dsa verify -- <message> <signature>\n\n\n\n'
|
|
349
|
+
'# --- Public Bid ---\n\n'
|
|
350
|
+
'poetry run transcrypto -i bin bid new "tomorrow it will rain"\n\n'
|
|
351
|
+
'poetry run transcrypto -o bin bid verify\n\n\n\n'
|
|
352
|
+
'# --- Shamir Secret Sharing (SSS) ---\n\n'
|
|
353
|
+
'poetry run transcrypto -p sss-key sss new 3 --bits 1024\n\n'
|
|
354
|
+
'poetry run transcrypto -p sss-key sss rawshares <secret> <n>\n\n'
|
|
355
|
+
'poetry run transcrypto -p sss-key sss rawrecover\n\n'
|
|
356
|
+
'poetry run transcrypto -p sss-key sss rawverify <secret>\n\n'
|
|
357
|
+
'poetry run transcrypto -i bin -p sss-key sss shares <secret> <n>\n\n'
|
|
358
|
+
'poetry run transcrypto -o bin -p sss-key sss recover\n\n\n\n'
|
|
359
|
+
'# --- Markdown ---\n\n'
|
|
360
|
+
'poetry run transcrypto markdown > transcrypto.md\n\n'
|
|
361
|
+
),
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def Run() -> None:
|
|
366
|
+
"""Run the CLI."""
|
|
367
|
+
app()
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
@app.callback(
|
|
371
|
+
invoke_without_command=True, # have only one; this is the "constructor"
|
|
372
|
+
help='transcrypto: CLI for number theory, hash, AES, RSA, El-Gamal, DSA, bidding, SSS, and more.',
|
|
373
|
+
) # keep message in sync with app.help
|
|
374
|
+
@clibase.CLIErrorGuard
|
|
375
|
+
def Main( # documentation is help/epilog/args # noqa: D103
|
|
376
|
+
*,
|
|
377
|
+
ctx: click.Context, # global context
|
|
378
|
+
version: bool = typer.Option(False, '--version', help='Show version and exit.'),
|
|
379
|
+
verbose: int = typer.Option(
|
|
380
|
+
0,
|
|
381
|
+
'-v',
|
|
382
|
+
'--verbose',
|
|
383
|
+
count=True,
|
|
384
|
+
help='Verbosity (nothing=ERROR, -v=WARNING, -vv=INFO, -vvv=DEBUG).',
|
|
385
|
+
min=0,
|
|
386
|
+
max=3,
|
|
387
|
+
),
|
|
388
|
+
color: bool | None = typer.Option(
|
|
389
|
+
None,
|
|
390
|
+
'--color/--no-color',
|
|
391
|
+
help=(
|
|
392
|
+
'Force enable/disable colored output (respects NO_COLOR env var if not provided). '
|
|
393
|
+
'Defaults to having colors.' # state default because None default means docs don't show it
|
|
394
|
+
),
|
|
395
|
+
),
|
|
396
|
+
input_format: IOFormat = typer.Option( # noqa: B008
|
|
397
|
+
IOFormat.hex,
|
|
398
|
+
'-i',
|
|
399
|
+
'--input-format',
|
|
400
|
+
help=(
|
|
401
|
+
'How to format inputs: "hex" (default hexadecimal), "b64" (base64), or "bin" (binary); '
|
|
402
|
+
'sometimes base64 will start with "-" and that can conflict with other flags, so use " -- " '
|
|
403
|
+
'before positional arguments if needed.'
|
|
404
|
+
),
|
|
405
|
+
),
|
|
406
|
+
output_format: IOFormat = typer.Option( # noqa: B008
|
|
407
|
+
IOFormat.hex,
|
|
408
|
+
'-o',
|
|
409
|
+
'--output-format',
|
|
410
|
+
help='How to format outputs: "hex" (default hexadecimal), "b64" (base64), or "bin" (binary).',
|
|
411
|
+
),
|
|
226
412
|
# key loading/saving from/to file, with optional password; will only work with some commands
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
epilog='isprime 2305843009213693951\nTrue $$ isprime 2305843009213693953\nFalse')
|
|
277
|
-
p_isprime.add_argument(
|
|
278
|
-
'n', type=str, help='Integer to test, ≥ 1')
|
|
279
|
-
|
|
280
|
-
# Primes generator
|
|
281
|
-
p_pg: argparse.ArgumentParser = sub.add_parser(
|
|
282
|
-
'primegen',
|
|
283
|
-
help='Generate (stream) primes ≥ `start` (prints a limited `count` by default).',
|
|
284
|
-
epilog='primegen 100 -c 3\n101\n103\n107')
|
|
285
|
-
p_pg.add_argument('start', type=str, help='Starting integer (inclusive)')
|
|
286
|
-
p_pg.add_argument(
|
|
287
|
-
'-c', '--count', type=int, default=10, help='How many to print (0 = unlimited)')
|
|
288
|
-
|
|
289
|
-
# Mersenne primes generator
|
|
290
|
-
p_mersenne: argparse.ArgumentParser = sub.add_parser(
|
|
291
|
-
'mersenne',
|
|
292
|
-
help=('Generate (stream) Mersenne prime exponents `k`, also outputting `2^k-1` '
|
|
293
|
-
'(the Mersenne prime, `M`) and `M×2^(k-1)` (the associated perfect number), '
|
|
294
|
-
'starting at `min-k` and stopping once `k` > `cutoff-k`.'),
|
|
295
|
-
epilog=('mersenne -k 0 -C 15\nk=2 M=3 perfect=6\nk=3 M=7 perfect=28\n'
|
|
296
|
-
'k=5 M=31 perfect=496\nk=7 M=127 perfect=8128\n'
|
|
297
|
-
'k=13 M=8191 perfect=33550336\nk=17 M=131071 perfect=8589869056'))
|
|
298
|
-
p_mersenne.add_argument(
|
|
299
|
-
'-k', '--min-k', type=int, default=1, help='Starting exponent `k`, ≥ 1')
|
|
300
|
-
p_mersenne.add_argument(
|
|
301
|
-
'-C', '--cutoff-k', type=int, default=10000, help='Stop once `k` > `cutoff-k`')
|
|
302
|
-
|
|
303
|
-
# ========================= integer / modular math ===============================================
|
|
304
|
-
|
|
305
|
-
# GCD
|
|
306
|
-
p_gcd: argparse.ArgumentParser = sub.add_parser(
|
|
307
|
-
'gcd',
|
|
308
|
-
help='Greatest Common Divisor (GCD) of integers `a` and `b`.',
|
|
309
|
-
epilog='gcd 462 1071\n21 $$ gcd 0 5\n5 $$ gcd 127 13\n1')
|
|
310
|
-
p_gcd.add_argument('a', type=str, help='Integer, ≥ 0')
|
|
311
|
-
p_gcd.add_argument('b', type=str, help='Integer, ≥ 0 (can\'t be both zero)')
|
|
312
|
-
|
|
313
|
-
# Extended GCD
|
|
314
|
-
p_xgcd: argparse.ArgumentParser = sub.add_parser(
|
|
315
|
-
'xgcd',
|
|
316
|
-
help=('Extended Greatest Common Divisor (x-GCD) of integers `a` and `b`, '
|
|
317
|
-
'will return `(g, x, y)` where `a×x+b×y==g`.'),
|
|
318
|
-
epilog='xgcd 462 1071\n(21, 7, -3) $$ xgcd 0 5\n(5, 0, 1) $$ xgcd 127 13\n(1, 4, -39)')
|
|
319
|
-
p_xgcd.add_argument('a', type=str, help='Integer, ≥ 0')
|
|
320
|
-
p_xgcd.add_argument('b', type=str, help='Integer, ≥ 0 (can\'t be both zero)')
|
|
321
|
-
|
|
322
|
-
# Modular math group
|
|
323
|
-
p_mod: argparse.ArgumentParser = sub.add_parser('mod', help='Modular arithmetic helpers.')
|
|
324
|
-
mod_sub = p_mod.add_subparsers(dest='mod_command')
|
|
325
|
-
|
|
326
|
-
# Modular inverse
|
|
327
|
-
p_mi: argparse.ArgumentParser = mod_sub.add_parser(
|
|
328
|
-
'inv',
|
|
329
|
-
help=('Modular inverse: find integer 0≤`i`<`m` such that `a×i ≡ 1 (mod m)`. '
|
|
330
|
-
'Will only work if `gcd(a,m)==1`, else will fail with a message.'),
|
|
331
|
-
epilog=('mod inv 127 13\n4 $$ mod inv 17 3120\n2753 $$ '
|
|
332
|
-
'mod inv 462 1071\n<<INVALID>> no modular inverse exists (ModularDivideError)'))
|
|
333
|
-
p_mi.add_argument('a', type=str, help='Integer to invert')
|
|
334
|
-
p_mi.add_argument('m', type=str, help='Modulus `m`, ≥ 2')
|
|
335
|
-
|
|
336
|
-
# Modular division
|
|
337
|
-
p_md: argparse.ArgumentParser = mod_sub.add_parser(
|
|
338
|
-
'div',
|
|
339
|
-
help=('Modular division: find integer 0≤`z`<`m` such that `z×y ≡ x (mod m)`. '
|
|
340
|
-
'Will only work if `gcd(y,m)==1` and `y!=0`, else will fail with a message.'),
|
|
341
|
-
epilog=('mod div 6 127 13\n11 $$ '
|
|
342
|
-
'mod div 6 0 13\n<<INVALID>> no modular inverse exists (ModularDivideError)'))
|
|
343
|
-
p_md.add_argument('x', type=str, help='Integer')
|
|
344
|
-
p_md.add_argument('y', type=str, help='Integer, cannot be zero')
|
|
345
|
-
p_md.add_argument('m', type=str, help='Modulus `m`, ≥ 2')
|
|
346
|
-
|
|
347
|
-
# Modular exponentiation
|
|
348
|
-
p_me: argparse.ArgumentParser = mod_sub.add_parser(
|
|
349
|
-
'exp',
|
|
350
|
-
help='Modular exponentiation: `a^e mod m`. Efficient, can handle huge values.',
|
|
351
|
-
epilog='mod exp 438 234 127\n32 $$ mod exp 438 234 89854\n60622')
|
|
352
|
-
p_me.add_argument('a', type=str, help='Integer')
|
|
353
|
-
p_me.add_argument('e', type=str, help='Integer, ≥ 0')
|
|
354
|
-
p_me.add_argument('m', type=str, help='Modulus `m`, ≥ 2')
|
|
355
|
-
|
|
356
|
-
# Polynomial evaluation mod m
|
|
357
|
-
p_mp: argparse.ArgumentParser = mod_sub.add_parser(
|
|
358
|
-
'poly',
|
|
359
|
-
help=('Efficiently evaluate polynomial with `coeff` coefficients at point `x` modulo `m` '
|
|
360
|
-
'(`c₀+c₁×x+c₂×x²+…+cₙ×xⁿ mod m`).'),
|
|
361
|
-
epilog=('mod poly 12 17 10 20 30\n14 # (10+20×12+30×12² ≡ 14 (mod 17)) $$ '
|
|
362
|
-
'mod poly 10 97 3 0 0 1 1\n42 # (3+1×10³+1×10⁴ ≡ 42 (mod 97))'))
|
|
363
|
-
p_mp.add_argument('x', type=str, help='Evaluation point `x`')
|
|
364
|
-
p_mp.add_argument('m', type=str, help='Modulus `m`, ≥ 2')
|
|
365
|
-
p_mp.add_argument(
|
|
366
|
-
'coeff', nargs='+', help='Coefficients (constant-term first: `c₀+c₁×x+c₂×x²+…+cₙ×xⁿ`)')
|
|
367
|
-
|
|
368
|
-
# Lagrange interpolation mod m
|
|
369
|
-
p_ml: argparse.ArgumentParser = mod_sub.add_parser(
|
|
370
|
-
'lagrange',
|
|
371
|
-
help=('Lagrange interpolation over modulus `m`: find the `f(x)` solution for the '
|
|
372
|
-
'given `x` and `zₙ:f(zₙ)` points `pt`. The modulus `m` must be a prime.'),
|
|
373
|
-
epilog=('mod lagrange 5 13 2:4 6:3 7:1\n3 # passes through (2,4), (6,3), (7,1) $$ '
|
|
374
|
-
'mod lagrange 11 97 1:1 2:4 3:9 4:16 5:25\n24 '
|
|
375
|
-
'# passes through (1,1), (2,4), (3,9), (4,16), (5,25)'))
|
|
376
|
-
p_ml.add_argument('x', type=str, help='Evaluation point `x`')
|
|
377
|
-
p_ml.add_argument('m', type=str, help='Modulus `m`, ≥ 2')
|
|
378
|
-
p_ml.add_argument(
|
|
379
|
-
'pt', nargs='+', help='Points `zₙ:f(zₙ)` as `key:value` pairs (e.g., `2:4 5:3 7:1`)')
|
|
380
|
-
|
|
381
|
-
# Chinese Remainder Theorem for 2 equations
|
|
382
|
-
p_crt: argparse.ArgumentParser = mod_sub.add_parser(
|
|
383
|
-
'crt',
|
|
384
|
-
help=('Solves Chinese Remainder Theorem (CRT) Pair: finds the unique integer 0≤`x`<`(m1×m2)` '
|
|
385
|
-
'satisfying both `x ≡ a1 (mod m1)` and `x ≡ a2 (mod m2)`, if `gcd(m1,m2)==1`.'),
|
|
386
|
-
epilog=('mod crt 6 7 127 13\n62 $$ mod crt 12 56 17 19\n796 $$ '
|
|
387
|
-
'mod crt 6 7 462 1071\n<<INVALID>> moduli m1/m2 not co-prime (ModularDivideError)'))
|
|
388
|
-
p_crt.add_argument('a1', type=str, help='Integer residue for first congruence')
|
|
389
|
-
p_crt.add_argument('m1', type=str, help='Modulus `m1`, ≥ 2 and `gcd(m1,m2)==1`')
|
|
390
|
-
p_crt.add_argument('a2', type=str, help='Integer residue for second congruence')
|
|
391
|
-
p_crt.add_argument('m2', type=str, help='Modulus `m2`, ≥ 2 and `gcd(m1,m2)==1`')
|
|
392
|
-
|
|
393
|
-
# ========================= hashing ==============================================================
|
|
394
|
-
|
|
395
|
-
# Hashing group
|
|
396
|
-
p_hash: argparse.ArgumentParser = sub.add_parser(
|
|
397
|
-
'hash', help='Cryptographic Hashing (SHA-256 / SHA-512 / file).')
|
|
398
|
-
hash_sub = p_hash.add_subparsers(dest='hash_command')
|
|
399
|
-
|
|
400
|
-
# SHA-256
|
|
401
|
-
p_h256: argparse.ArgumentParser = hash_sub.add_parser(
|
|
402
|
-
'sha256',
|
|
403
|
-
help='SHA-256 of input `data`.',
|
|
404
|
-
epilog=('--bin hash sha256 xyz\n'
|
|
405
|
-
'3608bca1e44ea6c4d268eb6db02260269892c0b42b86bbf1e77a6fa16c3c9282 $$'
|
|
406
|
-
'--b64 hash sha256 -- eHl6 # "xyz" in base-64\n'
|
|
407
|
-
'3608bca1e44ea6c4d268eb6db02260269892c0b42b86bbf1e77a6fa16c3c9282'))
|
|
408
|
-
p_h256.add_argument('data', type=str, help='Input data (raw text; or use --hex/--b64/--bin)')
|
|
409
|
-
|
|
410
|
-
# SHA-512
|
|
411
|
-
p_h512 = hash_sub.add_parser(
|
|
412
|
-
'sha512',
|
|
413
|
-
help='SHA-512 of input `data`.',
|
|
414
|
-
epilog=('--bin hash sha512 xyz\n'
|
|
415
|
-
'4a3ed8147e37876adc8f76328e5abcc1b470e6acfc18efea0135f983604953a5'
|
|
416
|
-
'8e183c1a6086e91ba3e821d926f5fdeb37761c7ca0328a963f5e92870675b728 $$'
|
|
417
|
-
'--b64 hash sha512 -- eHl6 # "xyz" in base-64\n'
|
|
418
|
-
'4a3ed8147e37876adc8f76328e5abcc1b470e6acfc18efea0135f983604953a5'
|
|
419
|
-
'8e183c1a6086e91ba3e821d926f5fdeb37761c7ca0328a963f5e92870675b728'))
|
|
420
|
-
p_h512.add_argument('data', type=str, help='Input data (raw text; or use --hex/--b64/--bin)')
|
|
421
|
-
|
|
422
|
-
# Hash file contents (streamed)
|
|
423
|
-
p_hf: argparse.ArgumentParser = hash_sub.add_parser(
|
|
424
|
-
'file',
|
|
425
|
-
help='SHA-256/512 hash of file contents, defaulting to SHA-256.',
|
|
426
|
-
epilog=('hash file /etc/passwd --digest sha512\n'
|
|
427
|
-
'8966f5953e79f55dfe34d3dc5b160ac4a4a3f9cbd1c36695a54e28d77c7874df'
|
|
428
|
-
'f8595502f8a420608911b87d336d9e83c890f0e7ec11a76cb10b03e757f78aea'))
|
|
429
|
-
p_hf.add_argument('path', type=str, help='Path to existing file')
|
|
430
|
-
p_hf.add_argument('--digest', choices=['sha256', 'sha512'], default='sha256',
|
|
431
|
-
help='Digest type, SHA-256 ("sha256") or SHA-512 ("sha512")')
|
|
432
|
-
|
|
433
|
-
# ========================= AES (GCM + ECB helper) ===============================================
|
|
434
|
-
|
|
435
|
-
# AES group
|
|
436
|
-
p_aes: argparse.ArgumentParser = sub.add_parser(
|
|
437
|
-
'aes',
|
|
438
|
-
help=('AES-256 operations (GCM/ECB) and key derivation. '
|
|
439
|
-
'No measures are taken here to prevent timing attacks.'))
|
|
440
|
-
aes_sub = p_aes.add_subparsers(dest='aes_command')
|
|
441
|
-
|
|
442
|
-
# Derive key from password
|
|
443
|
-
p_aes_key_pass: argparse.ArgumentParser = aes_sub.add_parser(
|
|
444
|
-
'key',
|
|
445
|
-
help=('Derive key from a password (PBKDF2-HMAC-SHA256) with custom expensive '
|
|
446
|
-
'salt and iterations. Very good/safe for simple password-to-key but not for '
|
|
447
|
-
'passwords databases (because of constant salt).'),
|
|
448
|
-
epilog=('--out-b64 aes key "correct horse battery staple"\n'
|
|
449
|
-
'DbWJ_ZrknLEEIoq_NpoCQwHYfjskGokpueN2O_eY0es= $$ ' # cspell:disable-line
|
|
450
|
-
'-p keyfile.out --protect hunter aes key "correct horse battery staple"\n'
|
|
451
|
-
'AES key saved to \'keyfile.out\''))
|
|
452
|
-
p_aes_key_pass.add_argument(
|
|
453
|
-
'password', type=str, help='Password (leading/trailing spaces ignored)')
|
|
454
|
-
|
|
455
|
-
# AES-256-GCM encrypt
|
|
456
|
-
p_aes_enc: argparse.ArgumentParser = aes_sub.add_parser(
|
|
457
|
-
'encrypt',
|
|
458
|
-
help=('AES-256-GCM: safely encrypt `plaintext` with `-k`/`--key` or with '
|
|
459
|
-
'`-p`/`--key-path` keyfile. All inputs are raw, or you '
|
|
460
|
-
'can use `--bin`/`--hex`/`--b64` flags. Attention: if you provide `-a`/`--aad` '
|
|
461
|
-
'(associated data, AAD), you will need to provide the same AAD when decrypting '
|
|
462
|
-
'and it is NOT included in the `ciphertext`/CT returned by this method!'),
|
|
463
|
-
epilog=('--b64 --out-b64 aes encrypt -k DbWJ_ZrknLEEIoq_NpoCQwHYfjskGokpueN2O_eY0es= -- ' # cspell:disable-line
|
|
464
|
-
'AAAAAAB4eXo=\nF2_ZLrUw5Y8oDnbTP5t5xCUWX8WtVILLD0teyUi_37_4KHeV-YowVA== $$ ' # cspell:disable-line
|
|
465
|
-
'--b64 --out-b64 aes encrypt -k DbWJ_ZrknLEEIoq_NpoCQwHYfjskGokpueN2O_eY0es= -a eHl6 ' # cspell:disable-line
|
|
466
|
-
'-- AAAAAAB4eXo=\nxOlAHPUPpeyZHId-f3VQ_QKKMxjIW0_FBo9WOfIBrzjn0VkVV6xTRA==')) # cspell:disable-line
|
|
467
|
-
p_aes_enc.add_argument('plaintext', type=str, help='Input data to encrypt (PT)')
|
|
468
|
-
p_aes_enc.add_argument(
|
|
469
|
-
'-k', '--key', type=str, default='', help='Key if `-p`/`--key-path` wasn\'t used (32 bytes)')
|
|
470
|
-
p_aes_enc.add_argument(
|
|
471
|
-
'-a', '--aad', type=str, default='',
|
|
472
|
-
help='Associated data (optional; has to be separately sent to receiver/stored)')
|
|
473
|
-
|
|
474
|
-
# AES-256-GCM decrypt
|
|
475
|
-
p_aes_dec: argparse.ArgumentParser = aes_sub.add_parser(
|
|
476
|
-
'decrypt',
|
|
477
|
-
help=('AES-256-GCM: safely decrypt `ciphertext` with `-k`/`--key` or with '
|
|
478
|
-
'`-p`/`--key-path` keyfile. All inputs are raw, or you '
|
|
479
|
-
'can use `--bin`/`--hex`/`--b64` flags. Attention: if you provided `-a`/`--aad` '
|
|
480
|
-
'(associated data, AAD) during encryption, you will need to provide the same AAD now!'),
|
|
481
|
-
epilog=('--b64 --out-b64 aes decrypt -k DbWJ_ZrknLEEIoq_NpoCQwHYfjskGokpueN2O_eY0es= -- ' # cspell:disable-line
|
|
482
|
-
'F2_ZLrUw5Y8oDnbTP5t5xCUWX8WtVILLD0teyUi_37_4KHeV-YowVA==\nAAAAAAB4eXo= $$ ' # cspell:disable-line
|
|
483
|
-
'--b64 --out-b64 aes decrypt -k DbWJ_ZrknLEEIoq_NpoCQwHYfjskGokpueN2O_eY0es= ' # cspell:disable-line
|
|
484
|
-
'-a eHl6 -- xOlAHPUPpeyZHId-f3VQ_QKKMxjIW0_FBo9WOfIBrzjn0VkVV6xTRA==\nAAAAAAB4eXo=')) # cspell:disable-line
|
|
485
|
-
p_aes_dec.add_argument('ciphertext', type=str, help='Input data to decrypt (CT)')
|
|
486
|
-
p_aes_dec.add_argument(
|
|
487
|
-
'-k', '--key', type=str, default='', help='Key if `-p`/`--key-path` wasn\'t used (32 bytes)')
|
|
488
|
-
p_aes_dec.add_argument(
|
|
489
|
-
'-a', '--aad', type=str, default='',
|
|
490
|
-
help='Associated data (optional; has to be exactly the same as used during encryption)')
|
|
491
|
-
|
|
492
|
-
# AES-ECB
|
|
493
|
-
p_aes_ecb: argparse.ArgumentParser = aes_sub.add_parser(
|
|
494
|
-
'ecb',
|
|
495
|
-
help=('AES-256-ECB: encrypt/decrypt 128 bit (16 bytes) hexadecimal blocks. UNSAFE, except '
|
|
496
|
-
'for specifically encrypting hash blocks which are very much expected to look random. '
|
|
497
|
-
'ECB mode will have the same output for the same input (no IV/nonce is used).'))
|
|
498
|
-
p_aes_ecb.add_argument(
|
|
499
|
-
'-k', '--key', type=str, default='',
|
|
500
|
-
help=('Key if `-p`/`--key-path` wasn\'t used (32 bytes; raw, or you '
|
|
501
|
-
'can use `--bin`/`--hex`/`--b64` flags)'))
|
|
502
|
-
aes_ecb_sub = p_aes_ecb.add_subparsers(dest='aes_ecb_command')
|
|
503
|
-
|
|
504
|
-
# AES-ECB encrypt 16-byte hex block
|
|
505
|
-
p_aes_ecb_e: argparse.ArgumentParser = aes_ecb_sub.add_parser(
|
|
506
|
-
'encrypt',
|
|
507
|
-
help=('AES-256-ECB: encrypt 16-bytes hex `plaintext` with `-k`/`--key` or with '
|
|
508
|
-
'`-p`/`--key-path` keyfile. UNSAFE, except for specifically encrypting hash blocks.'),
|
|
509
|
-
epilog=('--b64 aes ecb -k DbWJ_ZrknLEEIoq_NpoCQwHYfjskGokpueN2O_eY0es= encrypt ' # cspell:disable-line
|
|
510
|
-
'00112233445566778899aabbccddeeff\n54ec742ca3da7b752e527b74e3a798d7'))
|
|
511
|
-
p_aes_ecb_e.add_argument('plaintext', type=str, help='Plaintext block as 32 hex chars (16-bytes)')
|
|
512
|
-
|
|
513
|
-
# AES-ECB decrypt 16-byte hex block
|
|
514
|
-
p_aes_scb_d: argparse.ArgumentParser = aes_ecb_sub.add_parser(
|
|
515
|
-
'decrypt',
|
|
516
|
-
help=('AES-256-ECB: decrypt 16-bytes hex `ciphertext` with `-k`/`--key` or with '
|
|
517
|
-
'`-p`/`--key-path` keyfile. UNSAFE, except for specifically encrypting hash blocks.'),
|
|
518
|
-
epilog=('--b64 aes ecb -k DbWJ_ZrknLEEIoq_NpoCQwHYfjskGokpueN2O_eY0es= decrypt ' # cspell:disable-line
|
|
519
|
-
'54ec742ca3da7b752e527b74e3a798d7\n00112233445566778899aabbccddeeff')) # cspell:disable-line
|
|
520
|
-
p_aes_scb_d.add_argument(
|
|
521
|
-
'ciphertext', type=str, help='Ciphertext block as 32 hex chars (16-bytes)')
|
|
522
|
-
|
|
523
|
-
# ========================= RSA ==================================================================
|
|
524
|
-
|
|
525
|
-
# RSA group
|
|
526
|
-
p_rsa: argparse.ArgumentParser = sub.add_parser(
|
|
527
|
-
'rsa',
|
|
528
|
-
help=('RSA (Rivest-Shamir-Adleman) asymmetric cryptography. '
|
|
529
|
-
'No measures are taken here to prevent timing attacks. '
|
|
530
|
-
'All methods require file key(s) as `-p`/`--key-path` (see provided examples).'))
|
|
531
|
-
rsa_sub = p_rsa.add_subparsers(dest='rsa_command')
|
|
532
|
-
|
|
533
|
-
# Generate new RSA private key
|
|
534
|
-
p_rsa_new: argparse.ArgumentParser = rsa_sub.add_parser(
|
|
535
|
-
'new',
|
|
536
|
-
help=('Generate RSA private/public key pair with `bits` modulus size '
|
|
537
|
-
'(prime sizes will be `bits`/2). '
|
|
538
|
-
'Requires `-p`/`--key-path` to set the basename for output files.'),
|
|
539
|
-
epilog=('-p rsa-key rsa new --bits 64 # NEVER use such a small key: example only!\n'
|
|
540
|
-
'RSA private/public keys saved to \'rsa-key.priv/.pub\''))
|
|
541
|
-
p_rsa_new.add_argument(
|
|
542
|
-
'--bits', type=int, default=3332, help='Modulus size in bits; the default is a safe size')
|
|
543
|
-
|
|
544
|
-
# Encrypt with public key
|
|
545
|
-
p_rsa_enc_raw: argparse.ArgumentParser = rsa_sub.add_parser(
|
|
546
|
-
'rawencrypt',
|
|
547
|
-
help=('Raw encrypt *integer* `message` with public key '
|
|
548
|
-
'(BEWARE: no OAEP/PSS padding or validation).'),
|
|
549
|
-
epilog='-p rsa-key.pub rsa rawencrypt 999\n6354905961171348600')
|
|
550
|
-
p_rsa_enc_raw.add_argument(
|
|
551
|
-
'message', type=str, help='Integer message to encrypt, 1≤`message`<*modulus*')
|
|
552
|
-
p_rsa_enc_safe: argparse.ArgumentParser = rsa_sub.add_parser(
|
|
553
|
-
'encrypt',
|
|
554
|
-
help='Encrypt `message` with public key.',
|
|
555
|
-
epilog=('--bin --out-b64 -p rsa-key.pub rsa encrypt "abcde" -a "xyz"\n'
|
|
556
|
-
'AO6knI6xwq6TGR…Qy22jiFhXi1eQ=='))
|
|
557
|
-
p_rsa_enc_safe.add_argument('plaintext', type=str, help='Message to encrypt')
|
|
558
|
-
p_rsa_enc_safe.add_argument(
|
|
559
|
-
'-a', '--aad', type=str, default='',
|
|
560
|
-
help='Associated data (optional; has to be separately sent to receiver/stored)')
|
|
561
|
-
|
|
562
|
-
# Decrypt ciphertext with private key
|
|
563
|
-
p_rsa_dec_raw: argparse.ArgumentParser = rsa_sub.add_parser(
|
|
564
|
-
'rawdecrypt',
|
|
565
|
-
help=('Raw decrypt *integer* `ciphertext` with private key '
|
|
566
|
-
'(BEWARE: no OAEP/PSS padding or validation).'),
|
|
567
|
-
epilog='-p rsa-key.priv rsa rawdecrypt 6354905961171348600\n999')
|
|
568
|
-
p_rsa_dec_raw.add_argument(
|
|
569
|
-
'ciphertext', type=str, help='Integer ciphertext to decrypt, 1≤`ciphertext`<*modulus*')
|
|
570
|
-
p_rsa_dec_safe: argparse.ArgumentParser = rsa_sub.add_parser(
|
|
571
|
-
'decrypt',
|
|
572
|
-
help='Decrypt `ciphertext` with private key.',
|
|
573
|
-
epilog=('--b64 --out-bin -p rsa-key.priv rsa decrypt -a eHl6 -- '
|
|
574
|
-
'AO6knI6xwq6TGR…Qy22jiFhXi1eQ==\nabcde'))
|
|
575
|
-
p_rsa_dec_safe.add_argument('ciphertext', type=str, help='Ciphertext to decrypt')
|
|
576
|
-
p_rsa_dec_safe.add_argument(
|
|
577
|
-
'-a', '--aad', type=str, default='',
|
|
578
|
-
help='Associated data (optional; has to be exactly the same as used during encryption)')
|
|
579
|
-
|
|
580
|
-
# Sign message with private key
|
|
581
|
-
p_rsa_sig_raw: argparse.ArgumentParser = rsa_sub.add_parser(
|
|
582
|
-
'rawsign',
|
|
583
|
-
help=('Raw sign *integer* `message` with private key '
|
|
584
|
-
'(BEWARE: no OAEP/PSS padding or validation).'),
|
|
585
|
-
epilog='-p rsa-key.priv rsa rawsign 999\n7632909108672871784')
|
|
586
|
-
p_rsa_sig_raw.add_argument(
|
|
587
|
-
'message', type=str, help='Integer message to sign, 1≤`message`<*modulus*')
|
|
588
|
-
p_rsa_sig_safe: argparse.ArgumentParser = rsa_sub.add_parser(
|
|
589
|
-
'sign',
|
|
590
|
-
help='Sign `message` with private key.',
|
|
591
|
-
epilog='--bin --out-b64 -p rsa-key.priv rsa sign "xyz"\n91TS7gC6LORiL…6RD23Aejsfxlw==') # cspell:disable-line
|
|
592
|
-
p_rsa_sig_safe.add_argument('message', type=str, help='Message to sign')
|
|
593
|
-
p_rsa_sig_safe.add_argument(
|
|
594
|
-
'-a', '--aad', type=str, default='',
|
|
595
|
-
help='Associated data (optional; has to be separately sent to receiver/stored)')
|
|
596
|
-
|
|
597
|
-
# Verify signature with public key
|
|
598
|
-
p_rsa_ver_raw: argparse.ArgumentParser = rsa_sub.add_parser(
|
|
599
|
-
'rawverify',
|
|
600
|
-
help=('Raw verify *integer* `signature` for *integer* `message` with public key '
|
|
601
|
-
'(BEWARE: no OAEP/PSS padding or validation).'),
|
|
602
|
-
epilog=('-p rsa-key.pub rsa rawverify 999 7632909108672871784\nRSA signature: OK $$ '
|
|
603
|
-
'-p rsa-key.pub rsa rawverify 999 7632909108672871785\nRSA signature: INVALID'))
|
|
604
|
-
p_rsa_ver_raw.add_argument(
|
|
605
|
-
'message', type=str, help='Integer message that was signed earlier, 1≤`message`<*modulus*')
|
|
606
|
-
p_rsa_ver_raw.add_argument(
|
|
607
|
-
'signature', type=str,
|
|
608
|
-
help='Integer putative signature for `message`, 1≤`signature`<*modulus*')
|
|
609
|
-
p_rsa_ver_safe: argparse.ArgumentParser = rsa_sub.add_parser(
|
|
610
|
-
'verify',
|
|
611
|
-
help='Verify `signature` for `message` with public key.',
|
|
612
|
-
epilog=('--b64 -p rsa-key.pub rsa verify -- eHl6 '
|
|
613
|
-
'91TS7gC6LORiL…6RD23Aejsfxlw==\nRSA signature: OK $$ ' # cspell:disable-line
|
|
614
|
-
'--b64 -p rsa-key.pub rsa verify -- eLl6 '
|
|
615
|
-
'91TS7gC6LORiL…6RD23Aejsfxlw==\nRSA signature: INVALID')) # cspell:disable-line
|
|
616
|
-
p_rsa_ver_safe.add_argument('message', type=str, help='Message that was signed earlier')
|
|
617
|
-
p_rsa_ver_safe.add_argument('signature', type=str, help='Putative signature for `message`')
|
|
618
|
-
p_rsa_ver_safe.add_argument(
|
|
619
|
-
'-a', '--aad', type=str, default='',
|
|
620
|
-
help='Associated data (optional; has to be exactly the same as used during signing)')
|
|
621
|
-
|
|
622
|
-
# ========================= ElGamal ==============================================================
|
|
623
|
-
|
|
624
|
-
# ElGamal group
|
|
625
|
-
p_eg: argparse.ArgumentParser = sub.add_parser(
|
|
626
|
-
'elgamal',
|
|
627
|
-
help=('El-Gamal asymmetric cryptography. '
|
|
628
|
-
'No measures are taken here to prevent timing attacks. '
|
|
629
|
-
'All methods require file key(s) as `-p`/`--key-path` (see provided examples).'))
|
|
630
|
-
eg_sub = p_eg.add_subparsers(dest='eg_command')
|
|
631
|
-
|
|
632
|
-
# Generate shared (p,g) params
|
|
633
|
-
p_eg_shared: argparse.ArgumentParser = eg_sub.add_parser(
|
|
634
|
-
'shared',
|
|
635
|
-
help=('Generate a shared El-Gamal key with `bits` prime modulus size, which is the '
|
|
636
|
-
'first step in key generation. '
|
|
637
|
-
'The shared key can safely be used by any number of users to generate their '
|
|
638
|
-
'private/public key pairs (with the `new` command). The shared keys are "public". '
|
|
639
|
-
'Requires `-p`/`--key-path` to set the basename for output files.'),
|
|
640
|
-
epilog=('-p eg-key elgamal shared --bits 64 # NEVER use such a small key: example only!\n'
|
|
641
|
-
'El-Gamal shared key saved to \'eg-key.shared\''))
|
|
642
|
-
p_eg_shared.add_argument(
|
|
643
|
-
'--bits', type=int, default=3332,
|
|
644
|
-
help='Prime modulus (`p`) size in bits; the default is a safe size')
|
|
645
|
-
|
|
646
|
-
# Generate individual private key from shared (p,g)
|
|
647
|
-
eg_sub.add_parser(
|
|
648
|
-
'new',
|
|
649
|
-
help='Generate an individual El-Gamal private/public key pair from a shared key.',
|
|
650
|
-
epilog='-p eg-key elgamal new\nEl-Gamal private/public keys saved to \'eg-key.priv/.pub\'')
|
|
651
|
-
|
|
652
|
-
# Encrypt with public key
|
|
653
|
-
p_eg_enc_raw: argparse.ArgumentParser = eg_sub.add_parser(
|
|
654
|
-
'rawencrypt',
|
|
655
|
-
help=('Raw encrypt *integer* `message` with public key '
|
|
656
|
-
'(BEWARE: no ECIES-style KEM/DEM padding or validation).'),
|
|
657
|
-
epilog='-p eg-key.pub elgamal rawencrypt 999\n2948854810728206041:15945988196340032688')
|
|
658
|
-
p_eg_enc_raw.add_argument(
|
|
659
|
-
'message', type=str, help='Integer message to encrypt, 1≤`message`<*modulus*')
|
|
660
|
-
p_eg_enc_safe: argparse.ArgumentParser = eg_sub.add_parser(
|
|
661
|
-
'encrypt',
|
|
662
|
-
help='Encrypt `message` with public key.',
|
|
663
|
-
epilog=('--bin --out-b64 -p eg-key.pub elgamal encrypt "abcde" -a "xyz"\n'
|
|
664
|
-
'CdFvoQ_IIPFPZLua…kqjhcUTspISxURg==')) # cspell:disable-line
|
|
665
|
-
p_eg_enc_safe.add_argument('plaintext', type=str, help='Message to encrypt')
|
|
666
|
-
p_eg_enc_safe.add_argument(
|
|
667
|
-
'-a', '--aad', type=str, default='',
|
|
668
|
-
help='Associated data (optional; has to be separately sent to receiver/stored)')
|
|
669
|
-
|
|
670
|
-
# Decrypt El-Gamal ciphertext tuple (c1,c2)
|
|
671
|
-
p_eg_dec_raw: argparse.ArgumentParser = eg_sub.add_parser(
|
|
672
|
-
'rawdecrypt',
|
|
673
|
-
help=('Raw decrypt *integer* `ciphertext` with private key '
|
|
674
|
-
'(BEWARE: no ECIES-style KEM/DEM padding or validation).'),
|
|
675
|
-
epilog='-p eg-key.priv elgamal rawdecrypt 2948854810728206041:15945988196340032688\n999')
|
|
676
|
-
p_eg_dec_raw.add_argument(
|
|
677
|
-
'ciphertext', type=str,
|
|
678
|
-
help=('Integer ciphertext to decrypt; expects `c1:c2` format with 2 integers, '
|
|
679
|
-
' 2≤`c1`,`c2`<*modulus*'))
|
|
680
|
-
p_eg_dec_safe: argparse.ArgumentParser = eg_sub.add_parser(
|
|
681
|
-
'decrypt',
|
|
682
|
-
help='Decrypt `ciphertext` with private key.',
|
|
683
|
-
epilog=('--b64 --out-bin -p eg-key.priv elgamal decrypt -a eHl6 -- '
|
|
684
|
-
'CdFvoQ_IIPFPZLua…kqjhcUTspISxURg==\nabcde')) # cspell:disable-line
|
|
685
|
-
p_eg_dec_safe.add_argument('ciphertext', type=str, help='Ciphertext to decrypt')
|
|
686
|
-
p_eg_dec_safe.add_argument(
|
|
687
|
-
'-a', '--aad', type=str, default='',
|
|
688
|
-
help='Associated data (optional; has to be exactly the same as used during encryption)')
|
|
689
|
-
|
|
690
|
-
# Sign message with private key
|
|
691
|
-
p_eg_sig_raw: argparse.ArgumentParser = eg_sub.add_parser(
|
|
692
|
-
'rawsign',
|
|
693
|
-
help=('Raw sign *integer* message with private key '
|
|
694
|
-
'(BEWARE: no ECIES-style KEM/DEM padding or validation). '
|
|
695
|
-
'Output will 2 *integers* in a `s1:s2` format.'),
|
|
696
|
-
epilog='-p eg-key.priv elgamal rawsign 999\n4674885853217269088:14532144906178302633')
|
|
697
|
-
p_eg_sig_raw.add_argument(
|
|
698
|
-
'message', type=str, help='Integer message to sign, 1≤`message`<*modulus*')
|
|
699
|
-
p_eg_sig_safe: argparse.ArgumentParser = eg_sub.add_parser(
|
|
700
|
-
'sign',
|
|
701
|
-
help='Sign message with private key.',
|
|
702
|
-
epilog='--bin --out-b64 -p eg-key.priv elgamal sign "xyz"\nXl4hlYK8SHVGw…0fCKJE1XVzA==') # cspell:disable-line
|
|
703
|
-
p_eg_sig_safe.add_argument('message', type=str, help='Message to sign')
|
|
704
|
-
p_eg_sig_safe.add_argument(
|
|
705
|
-
'-a', '--aad', type=str, default='',
|
|
706
|
-
help='Associated data (optional; has to be separately sent to receiver/stored)')
|
|
707
|
-
|
|
708
|
-
# Verify El-Gamal signature (s1,s2)
|
|
709
|
-
p_eg_ver_raw: argparse.ArgumentParser = eg_sub.add_parser(
|
|
710
|
-
'rawverify',
|
|
711
|
-
help=('Raw verify *integer* `signature` for *integer* `message` with public key '
|
|
712
|
-
'(BEWARE: no ECIES-style KEM/DEM padding or validation).'),
|
|
713
|
-
epilog=('-p eg-key.pub elgamal rawverify 999 4674885853217269088:14532144906178302633\n'
|
|
714
|
-
'El-Gamal signature: OK $$ '
|
|
715
|
-
'-p eg-key.pub elgamal rawverify 999 4674885853217269088:14532144906178302632\n'
|
|
716
|
-
'El-Gamal signature: INVALID'))
|
|
717
|
-
p_eg_ver_raw.add_argument(
|
|
718
|
-
'message', type=str, help='Integer message that was signed earlier, 1≤`message`<*modulus*')
|
|
719
|
-
p_eg_ver_raw.add_argument(
|
|
720
|
-
'signature', type=str,
|
|
721
|
-
help=('Integer putative signature for `message`; expects `s1:s2` format with 2 integers, '
|
|
722
|
-
' 2≤`s1`,`s2`<*modulus*'))
|
|
723
|
-
p_eg_ver_safe: argparse.ArgumentParser = eg_sub.add_parser(
|
|
724
|
-
'verify',
|
|
725
|
-
help='Verify `signature` for `message` with public key.',
|
|
726
|
-
epilog=('--b64 -p eg-key.pub elgamal verify -- eHl6 Xl4hlYK8SHVGw…0fCKJE1XVzA==\n' # cspell:disable-line
|
|
727
|
-
'El-Gamal signature: OK $$ '
|
|
728
|
-
'--b64 -p eg-key.pub elgamal verify -- eLl6 Xl4hlYK8SHVGw…0fCKJE1XVzA==\n' # cspell:disable-line
|
|
729
|
-
'El-Gamal signature: INVALID'))
|
|
730
|
-
p_eg_ver_safe.add_argument('message', type=str, help='Message that was signed earlier')
|
|
731
|
-
p_eg_ver_safe.add_argument('signature', type=str, help='Putative signature for `message`')
|
|
732
|
-
p_eg_ver_safe.add_argument(
|
|
733
|
-
'-a', '--aad', type=str, default='',
|
|
734
|
-
help='Associated data (optional; has to be exactly the same as used during signing)')
|
|
735
|
-
|
|
736
|
-
# ========================= DSA ==================================================================
|
|
737
|
-
|
|
738
|
-
# DSA group
|
|
739
|
-
p_dsa: argparse.ArgumentParser = sub.add_parser(
|
|
740
|
-
'dsa',
|
|
741
|
-
help=('DSA (Digital Signature Algorithm) asymmetric signing/verifying. '
|
|
742
|
-
'No measures are taken here to prevent timing attacks. '
|
|
743
|
-
'All methods require file key(s) as `-p`/`--key-path` (see provided examples).'))
|
|
744
|
-
dsa_sub = p_dsa.add_subparsers(dest='dsa_command')
|
|
745
|
-
|
|
746
|
-
# Generate shared (p,q,g) params
|
|
747
|
-
p_dsa_shared: argparse.ArgumentParser = dsa_sub.add_parser(
|
|
748
|
-
'shared',
|
|
749
|
-
help=('Generate a shared DSA key with `p-bits`/`q-bits` prime modulus sizes, which is '
|
|
750
|
-
'the first step in key generation. `q-bits` should be larger than the secrets that '
|
|
751
|
-
'will be protected and `p-bits` should be much larger than `q-bits` (e.g. 4096/544). '
|
|
752
|
-
'The shared key can safely be used by any number of users to generate their '
|
|
753
|
-
'private/public key pairs (with the `new` command). The shared keys are "public". '
|
|
754
|
-
'Requires `-p`/`--key-path` to set the basename for output files.'),
|
|
755
|
-
epilog=('-p dsa-key dsa shared --p-bits 128 --q-bits 32 '
|
|
756
|
-
'# NEVER use such a small key: example only!\n'
|
|
757
|
-
'DSA shared key saved to \'dsa-key.shared\''))
|
|
758
|
-
p_dsa_shared.add_argument(
|
|
759
|
-
'--p-bits', type=int, default=4096,
|
|
760
|
-
help='Prime modulus (`p`) size in bits; the default is a safe size')
|
|
761
|
-
p_dsa_shared.add_argument(
|
|
762
|
-
'--q-bits', type=int, default=544,
|
|
763
|
-
help=('Prime modulus (`q`) size in bits; the default is a safe size ***IFF*** you '
|
|
764
|
-
'are protecting symmetric keys or regular hashes'))
|
|
765
|
-
|
|
766
|
-
# Generate individual private key from shared (p,q,g)
|
|
767
|
-
dsa_sub.add_parser(
|
|
768
|
-
'new',
|
|
769
|
-
help='Generate an individual DSA private/public key pair from a shared key.',
|
|
770
|
-
epilog='-p dsa-key dsa new\nDSA private/public keys saved to \'dsa-key.priv/.pub\'')
|
|
771
|
-
|
|
772
|
-
# Sign message with private key
|
|
773
|
-
p_dsa_sign_raw: argparse.ArgumentParser = dsa_sub.add_parser(
|
|
774
|
-
'rawsign',
|
|
775
|
-
help=('Raw sign *integer* message with private key '
|
|
776
|
-
'(BEWARE: no ECDSA/EdDSA padding or validation). '
|
|
777
|
-
'Output will 2 *integers* in a `s1:s2` format.'),
|
|
778
|
-
epilog='-p dsa-key.priv dsa rawsign 999\n2395961484:3435572290')
|
|
779
|
-
p_dsa_sign_raw.add_argument('message', type=str, help='Integer message to sign, 1≤`message`<`q`')
|
|
780
|
-
p_dsa_sign_safe: argparse.ArgumentParser = dsa_sub.add_parser(
|
|
781
|
-
'sign',
|
|
782
|
-
help='Sign message with private key.',
|
|
783
|
-
epilog='--bin --out-b64 -p dsa-key.priv dsa sign "xyz"\nyq8InJVpViXh9…BD4par2XuA=')
|
|
784
|
-
p_dsa_sign_safe.add_argument('message', type=str, help='Message to sign')
|
|
785
|
-
p_dsa_sign_safe.add_argument(
|
|
786
|
-
'-a', '--aad', type=str, default='',
|
|
787
|
-
help='Associated data (optional; has to be separately sent to receiver/stored)')
|
|
788
|
-
|
|
789
|
-
# Verify DSA signature (s1,s2)
|
|
790
|
-
p_dsa_verify_raw: argparse.ArgumentParser = dsa_sub.add_parser(
|
|
791
|
-
'rawverify',
|
|
792
|
-
help=('Raw verify *integer* `signature` for *integer* `message` with public key '
|
|
793
|
-
'(BEWARE: no ECDSA/EdDSA padding or validation).'),
|
|
794
|
-
epilog=('-p dsa-key.pub dsa rawverify 999 2395961484:3435572290\nDSA signature: OK $$ '
|
|
795
|
-
'-p dsa-key.pub dsa rawverify 999 2395961484:3435572291\nDSA signature: INVALID'))
|
|
796
|
-
p_dsa_verify_raw.add_argument(
|
|
797
|
-
'message', type=str, help='Integer message that was signed earlier, 1≤`message`<`q`')
|
|
798
|
-
p_dsa_verify_raw.add_argument(
|
|
799
|
-
'signature', type=str,
|
|
800
|
-
help=('Integer putative signature for `message`; expects `s1:s2` format with 2 integers, '
|
|
801
|
-
' 2≤`s1`,`s2`<`q`'))
|
|
802
|
-
p_dsa_verify_safe: argparse.ArgumentParser = dsa_sub.add_parser(
|
|
803
|
-
'verify',
|
|
804
|
-
help='Verify `signature` for `message` with public key.',
|
|
805
|
-
epilog=('--b64 -p dsa-key.pub dsa verify -- eHl6 yq8InJVpViXh9…BD4par2XuA=\n'
|
|
806
|
-
'DSA signature: OK $$ '
|
|
807
|
-
'--b64 -p dsa-key.pub dsa verify -- eLl6 yq8InJVpViXh9…BD4par2XuA=\n'
|
|
808
|
-
'DSA signature: INVALID'))
|
|
809
|
-
p_dsa_verify_safe.add_argument('message', type=str, help='Message that was signed earlier')
|
|
810
|
-
p_dsa_verify_safe.add_argument('signature', type=str, help='Putative signature for `message`')
|
|
811
|
-
p_dsa_verify_safe.add_argument(
|
|
812
|
-
'-a', '--aad', type=str, default='',
|
|
813
|
-
help='Associated data (optional; has to be exactly the same as used during signing)')
|
|
814
|
-
|
|
815
|
-
# ========================= Public Bid ===========================================================
|
|
816
|
-
|
|
817
|
-
# bidding group
|
|
818
|
-
p_bid: argparse.ArgumentParser = sub.add_parser(
|
|
819
|
-
'bid',
|
|
820
|
-
help=('Bidding on a `secret` so that you can cryptographically convince a neutral '
|
|
821
|
-
'party that the `secret` that was committed to previously was not changed. '
|
|
822
|
-
'All methods require file key(s) as `-p`/`--key-path` (see provided examples).'))
|
|
823
|
-
bid_sub = p_bid.add_subparsers(dest='bid_command')
|
|
824
|
-
|
|
825
|
-
# Generate a new bid
|
|
826
|
-
p_bid_new: argparse.ArgumentParser = bid_sub.add_parser(
|
|
827
|
-
'new',
|
|
828
|
-
help=('Generate the bid files for `secret`. '
|
|
829
|
-
'Requires `-p`/`--key-path` to set the basename for output files.'),
|
|
830
|
-
epilog=('--bin -p my-bid bid new "tomorrow it will rain"\n'
|
|
831
|
-
'Bid private/public commitments saved to \'my-bid.priv/.pub\''))
|
|
832
|
-
p_bid_new.add_argument('secret', type=str, help='Input data to bid to, the protected "secret"')
|
|
833
|
-
|
|
834
|
-
# verify bid
|
|
835
|
-
bid_sub.add_parser(
|
|
836
|
-
'verify',
|
|
837
|
-
help=('Verify the bid files for correctness and reveal the `secret`. '
|
|
838
|
-
'Requires `-p`/`--key-path` to set the basename for output files.'),
|
|
839
|
-
epilog=('--out-bin -p my-bid bid verify\n'
|
|
840
|
-
'Bid commitment: OK\nBid secret:\ntomorrow it will rain'))
|
|
841
|
-
|
|
842
|
-
# ========================= Shamir Secret Sharing ================================================
|
|
843
|
-
|
|
844
|
-
# SSS group
|
|
845
|
-
p_sss: argparse.ArgumentParser = sub.add_parser(
|
|
846
|
-
'sss',
|
|
847
|
-
help=('SSS (Shamir Shared Secret) secret sharing crypto scheme. '
|
|
848
|
-
'No measures are taken here to prevent timing attacks. '
|
|
849
|
-
'All methods require file key(s) as `-p`/`--key-path` (see provided examples).'))
|
|
850
|
-
sss_sub = p_sss.add_subparsers(dest='sss_command')
|
|
851
|
-
|
|
852
|
-
# Generate new SSS params (t, prime, coefficients)
|
|
853
|
-
p_sss_new: argparse.ArgumentParser = sss_sub.add_parser(
|
|
854
|
-
'new',
|
|
855
|
-
help=('Generate the private keys with `bits` prime modulus size and so that at least a '
|
|
856
|
-
'`minimum` number of shares are needed to recover the secret. '
|
|
857
|
-
'This key will be used to generate the shares later (with the `shares` command). '
|
|
858
|
-
'Requires `-p`/`--key-path` to set the basename for output files.'),
|
|
859
|
-
epilog=('-p sss-key sss new 3 --bits 64 # NEVER use such a small key: example only!\n'
|
|
860
|
-
'SSS private/public keys saved to \'sss-key.priv/.pub\''))
|
|
861
|
-
p_sss_new.add_argument(
|
|
862
|
-
'minimum', type=int, help='Minimum number of shares required to recover secret, ≥ 2')
|
|
863
|
-
p_sss_new.add_argument(
|
|
864
|
-
'--bits', type=int, default=1024,
|
|
865
|
-
help=('Prime modulus (`p`) size in bits; the default is a safe size ***IFF*** you '
|
|
866
|
-
'are protecting symmetric keys; the number of bits should be comfortably larger '
|
|
867
|
-
'than the size of the secret you want to protect with this scheme'))
|
|
868
|
-
|
|
869
|
-
# Issue N shares for a secret
|
|
870
|
-
p_sss_shares_raw: argparse.ArgumentParser = sss_sub.add_parser(
|
|
871
|
-
'rawshares',
|
|
872
|
-
help=('Raw shares: Issue `count` private shares for an *integer* `secret` '
|
|
873
|
-
'(BEWARE: no modern message wrapping, padding or validation).'),
|
|
874
|
-
epilog=('-p sss-key sss rawshares 999 5\n'
|
|
875
|
-
'SSS 5 individual (private) shares saved to \'sss-key.share.1…5\'\n'
|
|
876
|
-
'$ rm sss-key.share.2 sss-key.share.4 '
|
|
877
|
-
'# this is to simulate only having shares 1,3,5'))
|
|
878
|
-
p_sss_shares_raw.add_argument(
|
|
879
|
-
'secret', type=str, help='Integer secret to be protected, 1≤`secret`<*modulus*')
|
|
880
|
-
p_sss_shares_raw.add_argument(
|
|
881
|
-
'count', type=int,
|
|
882
|
-
help=('How many shares to produce; must be ≥ `minimum` used in `new` command or else the '
|
|
883
|
-
'`secret` would become unrecoverable'))
|
|
884
|
-
p_sss_shares_safe: argparse.ArgumentParser = sss_sub.add_parser(
|
|
885
|
-
'shares',
|
|
886
|
-
help='Shares: Issue `count` private shares for a `secret`.',
|
|
887
|
-
epilog=('--bin -p sss-key sss shares "abcde" 5\n'
|
|
888
|
-
'SSS 5 individual (private) shares saved to \'sss-key.share.1…5\'\n'
|
|
889
|
-
'$ rm sss-key.share.2 sss-key.share.4 '
|
|
890
|
-
'# this is to simulate only having shares 1,3,5'))
|
|
891
|
-
p_sss_shares_safe.add_argument('secret', type=str, help='Secret to be protected')
|
|
892
|
-
p_sss_shares_safe.add_argument(
|
|
893
|
-
'count', type=int,
|
|
894
|
-
help=('How many shares to produce; must be ≥ `minimum` used in `new` command or else the '
|
|
895
|
-
'`secret` would become unrecoverable'))
|
|
896
|
-
|
|
897
|
-
# Recover secret from shares
|
|
898
|
-
sss_sub.add_parser(
|
|
899
|
-
'rawrecover',
|
|
900
|
-
help=('Raw recover *integer* secret from shares; will use any available shares '
|
|
901
|
-
'that were found (BEWARE: no modern message wrapping, padding or validation).'),
|
|
902
|
-
epilog=('-p sss-key sss rawrecover\n'
|
|
903
|
-
'Loaded SSS share: \'sss-key.share.3\'\n'
|
|
904
|
-
'Loaded SSS share: \'sss-key.share.5\'\n'
|
|
905
|
-
'Loaded SSS share: \'sss-key.share.1\' '
|
|
906
|
-
'# using only 3 shares: number 2/4 are missing\n'
|
|
907
|
-
'Secret:\n999'))
|
|
908
|
-
sss_sub.add_parser(
|
|
909
|
-
'recover',
|
|
910
|
-
help='Recover secret from shares; will use any available shares that were found.',
|
|
911
|
-
epilog=('--out-bin -p sss-key sss recover\n'
|
|
912
|
-
'Loaded SSS share: \'sss-key.share.3\'\n'
|
|
913
|
-
'Loaded SSS share: \'sss-key.share.5\'\n'
|
|
914
|
-
'Loaded SSS share: \'sss-key.share.1\' '
|
|
915
|
-
'# using only 3 shares: number 2/4 are missing\n'
|
|
916
|
-
'Secret:\nabcde'))
|
|
917
|
-
|
|
918
|
-
# Verify a share against a secret
|
|
919
|
-
p_sss_verify_raw: argparse.ArgumentParser = sss_sub.add_parser(
|
|
920
|
-
'rawverify',
|
|
921
|
-
help=('Raw verify shares against a secret (private params; '
|
|
922
|
-
'BEWARE: no modern message wrapping, padding or validation).'),
|
|
923
|
-
epilog=('-p sss-key sss rawverify 999\n'
|
|
924
|
-
'SSS share \'sss-key.share.3\' verification: OK\n'
|
|
925
|
-
'SSS share \'sss-key.share.5\' verification: OK\n'
|
|
926
|
-
'SSS share \'sss-key.share.1\' verification: OK $$ '
|
|
927
|
-
'-p sss-key sss rawverify 998\n'
|
|
928
|
-
'SSS share \'sss-key.share.3\' verification: INVALID\n'
|
|
929
|
-
'SSS share \'sss-key.share.5\' verification: INVALID\n'
|
|
930
|
-
'SSS share \'sss-key.share.1\' verification: INVALID'))
|
|
931
|
-
p_sss_verify_raw.add_argument(
|
|
932
|
-
'secret', type=str, help='Integer secret used to generate the shares')
|
|
933
|
-
|
|
934
|
-
# ========================= Markdown Generation ==================================================
|
|
935
|
-
|
|
936
|
-
# Documentation generation
|
|
937
|
-
doc: argparse.ArgumentParser = sub.add_parser(
|
|
938
|
-
'doc', help='Documentation utilities. (Not for regular use: these are developer utils.)')
|
|
939
|
-
doc_sub = doc.add_subparsers(dest='doc_command')
|
|
940
|
-
doc_sub.add_parser(
|
|
941
|
-
'md',
|
|
942
|
-
help='Emit Markdown docs for the CLI (see README.md section "Creating a New Version").',
|
|
943
|
-
epilog='doc md > transcrypto.md\n<<saves file>>')
|
|
944
|
-
|
|
945
|
-
return parser
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
def AESCommand(
|
|
949
|
-
args: argparse.Namespace, in_format: _StrBytesType, out_format: _StrBytesType,
|
|
950
|
-
console: rich_console.Console, /) -> None:
|
|
951
|
-
"""Execute `aes` command."""
|
|
952
|
-
pt: bytes
|
|
953
|
-
ct: bytes
|
|
954
|
-
aad: bytes | None = None
|
|
955
|
-
aes_key: aes.AESKey = _NULL_AES_KEY
|
|
956
|
-
aes_cmd: str = args.aes_command.lower().strip() if args.aes_command else ''
|
|
957
|
-
if aes_cmd in ('encrypt', 'decrypt', 'ecb'):
|
|
958
|
-
if args.key:
|
|
959
|
-
aes_key = aes.AESKey(key256=_BytesFromText(args.key, in_format))
|
|
960
|
-
elif args.key_path:
|
|
961
|
-
aes_key = _LoadObj(args.key_path, args.protect or None, aes.AESKey)
|
|
962
|
-
else:
|
|
963
|
-
raise base.InputError('provide -k/--key or -p/--key-path')
|
|
964
|
-
if aes_cmd != 'ecb':
|
|
965
|
-
aad = _BytesFromText(args.aad, in_format) if args.aad else None
|
|
966
|
-
match aes_cmd:
|
|
967
|
-
case 'key':
|
|
968
|
-
aes_key = aes.AESKey.FromStaticPassword(args.password)
|
|
969
|
-
if args.key_path:
|
|
970
|
-
_SaveObj(aes_key, args.key_path, args.protect or None)
|
|
971
|
-
console.print(f'AES key saved to {args.key_path!r}')
|
|
972
|
-
else:
|
|
973
|
-
console.print(_BytesToText(aes_key.key256, out_format))
|
|
974
|
-
case 'encrypt':
|
|
975
|
-
pt = _BytesFromText(args.plaintext, in_format)
|
|
976
|
-
ct = aes_key.Encrypt(pt, associated_data=aad)
|
|
977
|
-
console.print(_BytesToText(ct, out_format))
|
|
978
|
-
case 'decrypt':
|
|
979
|
-
ct = _BytesFromText(args.ciphertext, in_format)
|
|
980
|
-
pt = aes_key.Decrypt(ct, associated_data=aad)
|
|
981
|
-
console.print(_BytesToText(pt, out_format))
|
|
982
|
-
case 'ecb':
|
|
983
|
-
ecb_cmd: str = args.aes_ecb_command.lower().strip() if args.aes_ecb_command else ''
|
|
984
|
-
match ecb_cmd:
|
|
985
|
-
case 'encrypt':
|
|
986
|
-
ecb: aes.AESKey.ECBEncoderClass = aes_key.ECBEncoder()
|
|
987
|
-
console.print(ecb.EncryptHex(args.plaintext))
|
|
988
|
-
case 'decrypt':
|
|
989
|
-
ecb = aes_key.ECBEncoder()
|
|
990
|
-
console.print(ecb.DecryptHex(args.ciphertext))
|
|
991
|
-
case _:
|
|
992
|
-
raise NotImplementedError()
|
|
993
|
-
case _:
|
|
994
|
-
raise NotImplementedError()
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
def RSACommand(
|
|
998
|
-
args: argparse.Namespace, in_format: _StrBytesType, out_format: _StrBytesType,
|
|
999
|
-
console: rich_console.Console, /) -> None:
|
|
1000
|
-
"""Execute `rsa` command."""
|
|
1001
|
-
c: int
|
|
1002
|
-
m: int
|
|
1003
|
-
pt: bytes
|
|
1004
|
-
ct: bytes
|
|
1005
|
-
aad: bytes | None = None
|
|
1006
|
-
rsa_priv: rsa.RSAPrivateKey
|
|
1007
|
-
rsa_pub: rsa.RSAPublicKey
|
|
1008
|
-
rsa_cmd: str = args.rsa_command.lower().strip() if args.rsa_command else ''
|
|
1009
|
-
if rsa_cmd in ('encrypt', 'verify', 'decrypt', 'sign'):
|
|
1010
|
-
aad = _BytesFromText(args.aad, in_format) if args.aad else None
|
|
1011
|
-
match rsa_cmd:
|
|
1012
|
-
case 'new':
|
|
1013
|
-
rsa_priv = rsa.RSAPrivateKey.New(args.bits)
|
|
1014
|
-
rsa_pub = rsa.RSAPublicKey.Copy(rsa_priv)
|
|
1015
|
-
_SaveObj(rsa_priv, args.key_path + '.priv', args.protect or None)
|
|
1016
|
-
_SaveObj(rsa_pub, args.key_path + '.pub', args.protect or None)
|
|
1017
|
-
console.print(f'RSA private/public keys saved to {args.key_path + ".priv/.pub"!r}')
|
|
1018
|
-
case 'rawencrypt':
|
|
1019
|
-
rsa_pub = rsa.RSAPublicKey.Copy(
|
|
1020
|
-
_LoadObj(args.key_path, args.protect or None, rsa.RSAPublicKey))
|
|
1021
|
-
m = _ParseInt(args.message)
|
|
1022
|
-
console.print(rsa_pub.RawEncrypt(m))
|
|
1023
|
-
case 'rawdecrypt':
|
|
1024
|
-
rsa_priv = _LoadObj(args.key_path, args.protect or None, rsa.RSAPrivateKey)
|
|
1025
|
-
c = _ParseInt(args.ciphertext)
|
|
1026
|
-
console.print(rsa_priv.RawDecrypt(c))
|
|
1027
|
-
case 'rawsign':
|
|
1028
|
-
rsa_priv = _LoadObj(args.key_path, args.protect or None, rsa.RSAPrivateKey)
|
|
1029
|
-
m = _ParseInt(args.message)
|
|
1030
|
-
console.print(rsa_priv.RawSign(m))
|
|
1031
|
-
case 'rawverify':
|
|
1032
|
-
rsa_pub = rsa.RSAPublicKey.Copy(
|
|
1033
|
-
_LoadObj(args.key_path, args.protect or None, rsa.RSAPublicKey))
|
|
1034
|
-
m = _ParseInt(args.message)
|
|
1035
|
-
sig: int = _ParseInt(args.signature)
|
|
1036
|
-
console.print('RSA signature: ' + ('OK' if rsa_pub.RawVerify(m, sig) else 'INVALID'))
|
|
1037
|
-
case 'encrypt':
|
|
1038
|
-
rsa_pub = _LoadObj(args.key_path, args.protect or None, rsa.RSAPublicKey)
|
|
1039
|
-
pt = _BytesFromText(args.plaintext, in_format)
|
|
1040
|
-
ct = rsa_pub.Encrypt(pt, associated_data=aad)
|
|
1041
|
-
console.print(_BytesToText(ct, out_format))
|
|
1042
|
-
case 'decrypt':
|
|
1043
|
-
rsa_priv = _LoadObj(args.key_path, args.protect or None, rsa.RSAPrivateKey)
|
|
1044
|
-
ct = _BytesFromText(args.ciphertext, in_format)
|
|
1045
|
-
pt = rsa_priv.Decrypt(ct, associated_data=aad)
|
|
1046
|
-
console.print(_BytesToText(pt, out_format))
|
|
1047
|
-
case 'sign':
|
|
1048
|
-
rsa_priv = _LoadObj(args.key_path, args.protect or None, rsa.RSAPrivateKey)
|
|
1049
|
-
pt = _BytesFromText(args.message, in_format)
|
|
1050
|
-
ct = rsa_priv.Sign(pt, associated_data=aad)
|
|
1051
|
-
console.print(_BytesToText(ct, out_format))
|
|
1052
|
-
case 'verify':
|
|
1053
|
-
rsa_pub = _LoadObj(args.key_path, args.protect or None, rsa.RSAPublicKey)
|
|
1054
|
-
pt = _BytesFromText(args.message, in_format)
|
|
1055
|
-
ct = _BytesFromText(args.signature, in_format)
|
|
1056
|
-
console.print(
|
|
1057
|
-
'RSA signature: ' + ('OK' if rsa_pub.Verify(pt, ct, associated_data=aad) else 'INVALID'))
|
|
1058
|
-
case _:
|
|
1059
|
-
raise NotImplementedError()
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
def ElGamalCommand( # pylint: disable=too-many-statements
|
|
1063
|
-
args: argparse.Namespace, in_format: _StrBytesType, out_format: _StrBytesType,
|
|
1064
|
-
console: rich_console.Console, /) -> None:
|
|
1065
|
-
"""Execute `elgamal` command."""
|
|
1066
|
-
c1: str
|
|
1067
|
-
c2: str
|
|
1068
|
-
m: int
|
|
1069
|
-
ss: tuple[int, int]
|
|
1070
|
-
pt: bytes
|
|
1071
|
-
ct: bytes
|
|
1072
|
-
aad: bytes | None = None
|
|
1073
|
-
eg_priv: elgamal.ElGamalPrivateKey
|
|
1074
|
-
eg_pub: elgamal.ElGamalPublicKey
|
|
1075
|
-
eg_cmd: str = args.eg_command.lower().strip() if args.eg_command else ''
|
|
1076
|
-
if eg_cmd in ('encrypt', 'verify', 'decrypt', 'sign'):
|
|
1077
|
-
aad = _BytesFromText(args.aad, in_format) if args.aad else None
|
|
1078
|
-
match eg_cmd:
|
|
1079
|
-
case 'shared':
|
|
1080
|
-
shared_eg: elgamal.ElGamalSharedPublicKey = elgamal.ElGamalSharedPublicKey.NewShared(
|
|
1081
|
-
args.bits)
|
|
1082
|
-
_SaveObj(shared_eg, args.key_path + '.shared', args.protect or None)
|
|
1083
|
-
console.print(f'El-Gamal shared key saved to {args.key_path + ".shared"!r}')
|
|
1084
|
-
case 'new':
|
|
1085
|
-
eg_priv = elgamal.ElGamalPrivateKey.New(
|
|
1086
|
-
_LoadObj(args.key_path + '.shared', args.protect or None, elgamal.ElGamalSharedPublicKey))
|
|
1087
|
-
eg_pub = elgamal.ElGamalPublicKey.Copy(eg_priv)
|
|
1088
|
-
_SaveObj(eg_priv, args.key_path + '.priv', args.protect or None)
|
|
1089
|
-
_SaveObj(eg_pub, args.key_path + '.pub', args.protect or None)
|
|
1090
|
-
console.print(f'El-Gamal private/public keys saved to {args.key_path + ".priv/.pub"!r}')
|
|
1091
|
-
case 'rawencrypt':
|
|
1092
|
-
eg_pub = elgamal.ElGamalPublicKey.Copy(
|
|
1093
|
-
_LoadObj(args.key_path, args.protect or None, elgamal.ElGamalPublicKey))
|
|
1094
|
-
m = _ParseInt(args.message)
|
|
1095
|
-
ss = eg_pub.RawEncrypt(m)
|
|
1096
|
-
console.print(f'{ss[0]}:{ss[1]}')
|
|
1097
|
-
case 'rawdecrypt':
|
|
1098
|
-
eg_priv = _LoadObj(args.key_path, args.protect or None, elgamal.ElGamalPrivateKey)
|
|
1099
|
-
c1, c2 = args.ciphertext.split(':')
|
|
1100
|
-
ss = (_ParseInt(c1), _ParseInt(c2))
|
|
1101
|
-
console.print(eg_priv.RawDecrypt(ss))
|
|
1102
|
-
case 'rawsign':
|
|
1103
|
-
eg_priv = _LoadObj(args.key_path, args.protect or None, elgamal.ElGamalPrivateKey)
|
|
1104
|
-
m = _ParseInt(args.message)
|
|
1105
|
-
ss = eg_priv.RawSign(m)
|
|
1106
|
-
console.print(f'{ss[0]}:{ss[1]}')
|
|
1107
|
-
case 'rawverify':
|
|
1108
|
-
eg_pub = elgamal.ElGamalPublicKey.Copy(
|
|
1109
|
-
_LoadObj(args.key_path, args.protect or None, elgamal.ElGamalPublicKey))
|
|
1110
|
-
m = _ParseInt(args.message)
|
|
1111
|
-
c1, c2 = args.signature.split(':')
|
|
1112
|
-
ss = (_ParseInt(c1), _ParseInt(c2))
|
|
1113
|
-
console.print('El-Gamal signature: ' + ('OK' if eg_pub.RawVerify(m, ss) else 'INVALID'))
|
|
1114
|
-
case 'encrypt':
|
|
1115
|
-
eg_pub = _LoadObj(args.key_path, args.protect or None, elgamal.ElGamalPublicKey)
|
|
1116
|
-
pt = _BytesFromText(args.plaintext, in_format)
|
|
1117
|
-
ct = eg_pub.Encrypt(pt, associated_data=aad)
|
|
1118
|
-
console.print(_BytesToText(ct, out_format))
|
|
1119
|
-
case 'decrypt':
|
|
1120
|
-
eg_priv = _LoadObj(args.key_path, args.protect or None, elgamal.ElGamalPrivateKey)
|
|
1121
|
-
ct = _BytesFromText(args.ciphertext, in_format)
|
|
1122
|
-
pt = eg_priv.Decrypt(ct, associated_data=aad)
|
|
1123
|
-
console.print(_BytesToText(pt, out_format))
|
|
1124
|
-
case 'sign':
|
|
1125
|
-
eg_priv = _LoadObj(args.key_path, args.protect or None, elgamal.ElGamalPrivateKey)
|
|
1126
|
-
pt = _BytesFromText(args.message, in_format)
|
|
1127
|
-
ct = eg_priv.Sign(pt, associated_data=aad)
|
|
1128
|
-
console.print(_BytesToText(ct, out_format))
|
|
1129
|
-
case 'verify':
|
|
1130
|
-
eg_pub = _LoadObj(args.key_path, args.protect or None, elgamal.ElGamalPublicKey)
|
|
1131
|
-
pt = _BytesFromText(args.message, in_format)
|
|
1132
|
-
ct = _BytesFromText(args.signature, in_format)
|
|
1133
|
-
console.print(
|
|
1134
|
-
'El-Gamal signature: ' + ('OK' if eg_pub.Verify(pt, ct, associated_data=aad)
|
|
1135
|
-
else 'INVALID'))
|
|
1136
|
-
case _:
|
|
1137
|
-
raise NotImplementedError()
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
def DSACommand(
|
|
1141
|
-
args: argparse.Namespace, in_format: _StrBytesType, out_format: _StrBytesType,
|
|
1142
|
-
console: rich_console.Console, /) -> None:
|
|
1143
|
-
"""Execute `dsa` command."""
|
|
1144
|
-
c1: str
|
|
1145
|
-
c2: str
|
|
1146
|
-
m: int
|
|
1147
|
-
ss: tuple[int, int]
|
|
1148
|
-
pt: bytes
|
|
1149
|
-
ct: bytes
|
|
1150
|
-
aad: bytes | None = None
|
|
1151
|
-
dsa_priv: dsa.DSAPrivateKey
|
|
1152
|
-
dsa_pub: dsa.DSAPublicKey
|
|
1153
|
-
dsa_cmd: str = args.dsa_command.lower().strip() if args.dsa_command else ''
|
|
1154
|
-
if dsa_cmd in ('verify', 'sign'):
|
|
1155
|
-
aad = _BytesFromText(args.aad, in_format) if args.aad else None
|
|
1156
|
-
match dsa_cmd:
|
|
1157
|
-
case 'shared':
|
|
1158
|
-
dsa_shared: dsa.DSASharedPublicKey = dsa.DSASharedPublicKey.NewShared(
|
|
1159
|
-
args.p_bits, args.q_bits)
|
|
1160
|
-
_SaveObj(dsa_shared, args.key_path + '.shared', args.protect or None)
|
|
1161
|
-
console.print(f'DSA shared key saved to {args.key_path + ".shared"!r}')
|
|
1162
|
-
case 'new':
|
|
1163
|
-
dsa_priv = dsa.DSAPrivateKey.New(
|
|
1164
|
-
_LoadObj(args.key_path + '.shared', args.protect or None, dsa.DSASharedPublicKey))
|
|
1165
|
-
dsa_pub = dsa.DSAPublicKey.Copy(dsa_priv)
|
|
1166
|
-
_SaveObj(dsa_priv, args.key_path + '.priv', args.protect or None)
|
|
1167
|
-
_SaveObj(dsa_pub, args.key_path + '.pub', args.protect or None)
|
|
1168
|
-
console.print(f'DSA private/public keys saved to {args.key_path + ".priv/.pub"!r}')
|
|
1169
|
-
case 'rawsign':
|
|
1170
|
-
dsa_priv = _LoadObj(args.key_path, args.protect or None, dsa.DSAPrivateKey)
|
|
1171
|
-
m = _ParseInt(args.message) % dsa_priv.prime_seed
|
|
1172
|
-
ss = dsa_priv.RawSign(m)
|
|
1173
|
-
console.print(f'{ss[0]}:{ss[1]}')
|
|
1174
|
-
case 'rawverify':
|
|
1175
|
-
dsa_pub = dsa.DSAPublicKey.Copy(
|
|
1176
|
-
_LoadObj(args.key_path, args.protect or None, dsa.DSAPublicKey))
|
|
1177
|
-
m = _ParseInt(args.message) % dsa_pub.prime_seed
|
|
1178
|
-
c1, c2 = args.signature.split(':')
|
|
1179
|
-
ss = (_ParseInt(c1), _ParseInt(c2))
|
|
1180
|
-
console.print('DSA signature: ' + ('OK' if dsa_pub.RawVerify(m, ss) else 'INVALID'))
|
|
1181
|
-
case 'sign':
|
|
1182
|
-
dsa_priv = _LoadObj(args.key_path, args.protect or None, dsa.DSAPrivateKey)
|
|
1183
|
-
pt = _BytesFromText(args.message, in_format)
|
|
1184
|
-
ct = dsa_priv.Sign(pt, associated_data=aad)
|
|
1185
|
-
console.print(_BytesToText(ct, out_format))
|
|
1186
|
-
case 'verify':
|
|
1187
|
-
dsa_pub = _LoadObj(args.key_path, args.protect or None, dsa.DSAPublicKey)
|
|
1188
|
-
pt = _BytesFromText(args.message, in_format)
|
|
1189
|
-
ct = _BytesFromText(args.signature, in_format)
|
|
1190
|
-
console.print(
|
|
1191
|
-
'DSA signature: ' + ('OK' if dsa_pub.Verify(pt, ct, associated_data=aad) else 'INVALID'))
|
|
1192
|
-
case _:
|
|
1193
|
-
raise NotImplementedError()
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
def BidCommand(
|
|
1197
|
-
args: argparse.Namespace, in_format: _StrBytesType, out_format: _StrBytesType,
|
|
1198
|
-
console: rich_console.Console, /) -> None:
|
|
1199
|
-
"""Execute `bid` command."""
|
|
1200
|
-
bid_cmd: str = args.bid_command.lower().strip() if args.bid_command else ''
|
|
1201
|
-
match bid_cmd:
|
|
1202
|
-
case 'new':
|
|
1203
|
-
secret: bytes = _BytesFromText(args.secret, in_format)
|
|
1204
|
-
bid_priv: base.PrivateBid512 = base.PrivateBid512.New(secret)
|
|
1205
|
-
bid_pub: base.PublicBid512 = base.PublicBid512.Copy(bid_priv)
|
|
1206
|
-
_SaveObj(bid_priv, args.key_path + '.priv', args.protect or None)
|
|
1207
|
-
_SaveObj(bid_pub, args.key_path + '.pub', args.protect or None)
|
|
1208
|
-
console.print(f'Bid private/public commitments saved to {args.key_path + ".priv/.pub"!r}')
|
|
1209
|
-
case 'verify':
|
|
1210
|
-
bid_priv = _LoadObj(args.key_path + '.priv', args.protect or None, base.PrivateBid512)
|
|
1211
|
-
bid_pub = _LoadObj(args.key_path + '.pub', args.protect or None, base.PublicBid512)
|
|
1212
|
-
bid_pub_expect: base.PublicBid512 = base.PublicBid512.Copy(bid_priv)
|
|
1213
|
-
console.print('Bid commitment: ' + (
|
|
1214
|
-
'OK' if (bid_pub.VerifyBid(bid_priv.private_key, bid_priv.secret_bid) and
|
|
1215
|
-
bid_pub == bid_pub_expect) else 'INVALID'))
|
|
1216
|
-
console.print('Bid secret:')
|
|
1217
|
-
console.print(_BytesToText(bid_priv.secret_bid, out_format))
|
|
1218
|
-
case _:
|
|
1219
|
-
raise NotImplementedError()
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
def SSSCommand(
|
|
1223
|
-
args: argparse.Namespace, in_format: _StrBytesType, out_format: _StrBytesType,
|
|
1224
|
-
console: rich_console.Console, /) -> None:
|
|
1225
|
-
"""Execute `sss` command."""
|
|
1226
|
-
pt: bytes
|
|
1227
|
-
sss_share: sss.ShamirSharePrivate
|
|
1228
|
-
subset: list[sss.ShamirSharePrivate]
|
|
1229
|
-
data_share: sss.ShamirShareData | None
|
|
1230
|
-
sss_cmd: str = args.sss_command.lower().strip() if args.sss_command else ''
|
|
1231
|
-
match sss_cmd:
|
|
1232
|
-
case 'new':
|
|
1233
|
-
sss_priv: sss.ShamirSharedSecretPrivate = sss.ShamirSharedSecretPrivate.New(
|
|
1234
|
-
args.minimum, args.bits)
|
|
1235
|
-
sss_pub: sss.ShamirSharedSecretPublic = sss.ShamirSharedSecretPublic.Copy(sss_priv)
|
|
1236
|
-
_SaveObj(sss_priv, args.key_path + '.priv', args.protect or None)
|
|
1237
|
-
_SaveObj(sss_pub, args.key_path + '.pub', args.protect or None)
|
|
1238
|
-
console.print(f'SSS private/public keys saved to {args.key_path + ".priv/.pub"!r}')
|
|
1239
|
-
case 'rawshares':
|
|
1240
|
-
sss_priv = _LoadObj(
|
|
1241
|
-
args.key_path + '.priv', args.protect or None, sss.ShamirSharedSecretPrivate)
|
|
1242
|
-
secret: int = _ParseInt(args.secret)
|
|
1243
|
-
for i, sss_share in enumerate(sss_priv.RawShares(secret, max_shares=args.count)):
|
|
1244
|
-
_SaveObj(sss_share, f'{args.key_path}.share.{i + 1}', args.protect or None)
|
|
1245
|
-
console.print(
|
|
1246
|
-
f'SSS {args.count} individual (private) shares saved to '
|
|
1247
|
-
f'{args.key_path + ".share.1…" + str(args.count)!r}')
|
|
1248
|
-
case 'rawrecover':
|
|
1249
|
-
sss_pub = _LoadObj(args.key_path + '.pub', args.protect or None, sss.ShamirSharedSecretPublic)
|
|
1250
|
-
subset = []
|
|
1251
|
-
for fname in glob.glob(args.key_path + '.share.*'):
|
|
1252
|
-
sss_share = _LoadObj(fname, args.protect or None, sss.ShamirSharePrivate)
|
|
1253
|
-
subset.append(sss_share)
|
|
1254
|
-
console.print(f'Loaded SSS share: {fname!r}')
|
|
1255
|
-
console.print('Secret:')
|
|
1256
|
-
console.print(sss_pub.RawRecoverSecret(subset))
|
|
1257
|
-
case 'rawverify':
|
|
1258
|
-
sss_priv = _LoadObj(
|
|
1259
|
-
args.key_path + '.priv', args.protect or None, sss.ShamirSharedSecretPrivate)
|
|
1260
|
-
secret = _ParseInt(args.secret)
|
|
1261
|
-
for fname in glob.glob(args.key_path + '.share.*'):
|
|
1262
|
-
sss_share = _LoadObj(fname, args.protect or None, sss.ShamirSharePrivate)
|
|
1263
|
-
console.print(
|
|
1264
|
-
f'SSS share {fname!r} verification: '
|
|
1265
|
-
f'{"OK" if sss_priv.RawVerifyShare(secret, sss_share) else "INVALID"}')
|
|
1266
|
-
case 'shares':
|
|
1267
|
-
sss_priv = _LoadObj(
|
|
1268
|
-
args.key_path + '.priv', args.protect or None, sss.ShamirSharedSecretPrivate)
|
|
1269
|
-
pt = _BytesFromText(args.secret, in_format)
|
|
1270
|
-
for i, data_share in enumerate(sss_priv.MakeDataShares(pt, args.count)):
|
|
1271
|
-
_SaveObj(data_share, f'{args.key_path}.share.{i + 1}', args.protect or None)
|
|
1272
|
-
console.print(
|
|
1273
|
-
f'SSS {args.count} individual (private) shares saved to '
|
|
1274
|
-
f'{args.key_path + ".share.1…" + str(args.count)!r}')
|
|
1275
|
-
case 'recover':
|
|
1276
|
-
sss_pub = _LoadObj(args.key_path + '.pub', args.protect or None, sss.ShamirSharedSecretPublic)
|
|
1277
|
-
subset, data_share = [], None
|
|
1278
|
-
for fname in glob.glob(args.key_path + '.share.*'):
|
|
1279
|
-
sss_share = _LoadObj(fname, args.protect or None, sss.ShamirSharePrivate)
|
|
1280
|
-
subset.append(sss_share)
|
|
1281
|
-
if isinstance(sss_share, sss.ShamirShareData):
|
|
1282
|
-
data_share = sss_share
|
|
1283
|
-
console.print(f'Loaded SSS share: {fname!r}')
|
|
1284
|
-
if data_share is None:
|
|
1285
|
-
raise base.InputError('no data share found among the available shares')
|
|
1286
|
-
pt = data_share.RecoverData(subset)
|
|
1287
|
-
console.print('Secret:')
|
|
1288
|
-
console.print(_BytesToText(pt, out_format))
|
|
1289
|
-
case _:
|
|
1290
|
-
raise NotImplementedError()
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
def main(argv: list[str] | None = None, /) -> int: # pylint: disable=invalid-name,too-many-locals,too-many-branches,too-many-statements
|
|
1294
|
-
"""Main entry point."""
|
|
1295
|
-
# build the parser and parse args
|
|
1296
|
-
parser: argparse.ArgumentParser = _BuildParser()
|
|
1297
|
-
args: argparse.Namespace = parser.parse_args(argv)
|
|
1298
|
-
# take care of global options
|
|
1299
|
-
console: rich_console.Console = base.InitLogging(args.verbose, soft_wrap=True)
|
|
1300
|
-
in_format: _StrBytesType = _StrBytesType.FromFlags(args.hex, args.b64, args.bin)
|
|
1301
|
-
out_format: _StrBytesType = _StrBytesType.FromFlags(args.out_hex, args.out_b64, args.out_bin)
|
|
1302
|
-
|
|
1303
|
-
a: int
|
|
1304
|
-
b: int
|
|
1305
|
-
e: int
|
|
1306
|
-
i: int
|
|
1307
|
-
m: int
|
|
1308
|
-
n: int
|
|
1309
|
-
x: int
|
|
1310
|
-
y: int
|
|
1311
|
-
bt: bytes
|
|
1312
|
-
|
|
1313
|
-
try:
|
|
1314
|
-
# get the command, do basic checks and switch
|
|
1315
|
-
command: str = args.command.lower().strip() if args.command else ''
|
|
1316
|
-
if command in ('rsa', 'elgamal', 'dsa', 'bid', 'sss') and not args.key_path:
|
|
1317
|
-
raise base.InputError(f'you must provide -p/--key-path option for {command!r}')
|
|
1318
|
-
match command:
|
|
1319
|
-
# -------- primes ----------
|
|
1320
|
-
case 'isprime':
|
|
1321
|
-
n = _ParseInt(args.n)
|
|
1322
|
-
console.print(modmath.IsPrime(n))
|
|
1323
|
-
case 'primegen':
|
|
1324
|
-
start: int = _ParseInt(args.start)
|
|
1325
|
-
count: int = args.count
|
|
1326
|
-
i = 0
|
|
1327
|
-
for p in modmath.PrimeGenerator(start):
|
|
1328
|
-
console.print(p)
|
|
1329
|
-
i += 1
|
|
1330
|
-
if count and i >= count:
|
|
1331
|
-
break
|
|
1332
|
-
case 'mersenne':
|
|
1333
|
-
for k, m_p, perfect in modmath.MersennePrimesGenerator(args.min_k):
|
|
1334
|
-
console.print(f'k={k} M={m_p} perfect={perfect}')
|
|
1335
|
-
if k > args.cutoff_k:
|
|
1336
|
-
break
|
|
1337
|
-
|
|
1338
|
-
# -------- integer / modular ----------
|
|
1339
|
-
case 'gcd':
|
|
1340
|
-
a, b = _ParseInt(args.a), _ParseInt(args.b)
|
|
1341
|
-
console.print(base.GCD(a, b))
|
|
1342
|
-
case 'xgcd':
|
|
1343
|
-
a, b = _ParseInt(args.a), _ParseInt(args.b)
|
|
1344
|
-
console.print(base.ExtendedGCD(a, b))
|
|
1345
|
-
case 'mod':
|
|
1346
|
-
mod_command: str = args.mod_command.lower().strip() if args.mod_command else ''
|
|
1347
|
-
match mod_command:
|
|
1348
|
-
case 'inv':
|
|
1349
|
-
a, m = _ParseInt(args.a), _ParseInt(args.m)
|
|
1350
|
-
try:
|
|
1351
|
-
console.print(modmath.ModInv(a, m))
|
|
1352
|
-
except modmath.ModularDivideError:
|
|
1353
|
-
console.print('<<INVALID>> no modular inverse exists (ModularDivideError)')
|
|
1354
|
-
case 'div':
|
|
1355
|
-
x, y, m = _ParseInt(args.x), _ParseInt(args.y), _ParseInt(args.m)
|
|
1356
|
-
try:
|
|
1357
|
-
console.print(modmath.ModDiv(x, y, m))
|
|
1358
|
-
except modmath.ModularDivideError:
|
|
1359
|
-
console.print('<<INVALID>> no modular inverse exists (ModularDivideError)')
|
|
1360
|
-
case 'exp':
|
|
1361
|
-
a, e, m = _ParseInt(args.a), _ParseInt(args.e), _ParseInt(args.m)
|
|
1362
|
-
console.print(modmath.ModExp(a, e, m))
|
|
1363
|
-
case 'poly':
|
|
1364
|
-
x, m = _ParseInt(args.x), _ParseInt(args.m)
|
|
1365
|
-
coeffs: list[int] = _ParseIntList(args.coeff)
|
|
1366
|
-
console.print(modmath.ModPolynomial(x, coeffs, m))
|
|
1367
|
-
case 'lagrange':
|
|
1368
|
-
x, m = _ParseInt(args.x), _ParseInt(args.m)
|
|
1369
|
-
pts: dict[int, int] = {}
|
|
1370
|
-
k_s: str
|
|
1371
|
-
v_s: str
|
|
1372
|
-
for kv in args.pt:
|
|
1373
|
-
k_s, v_s = kv.split(':', 1)
|
|
1374
|
-
pts[_ParseInt(k_s)] = _ParseInt(v_s)
|
|
1375
|
-
console.print(modmath.ModLagrangeInterpolate(x, pts, m))
|
|
1376
|
-
case 'crt':
|
|
1377
|
-
crt_tuple: tuple[int, int, int, int] = (
|
|
1378
|
-
_ParseInt(args.a1), _ParseInt(args.m1), _ParseInt(args.a2), _ParseInt(args.m2))
|
|
1379
|
-
try:
|
|
1380
|
-
console.print(modmath.CRTPair(*crt_tuple))
|
|
1381
|
-
except modmath.ModularDivideError:
|
|
1382
|
-
console.print('<<INVALID>> moduli m1/m2 not co-prime (ModularDivideError)')
|
|
1383
|
-
case _:
|
|
1384
|
-
raise NotImplementedError()
|
|
1385
|
-
|
|
1386
|
-
# -------- randomness / hashing ----------
|
|
1387
|
-
case 'random':
|
|
1388
|
-
rand_cmd: str = args.rand_command.lower().strip() if args.rand_command else ''
|
|
1389
|
-
match rand_cmd:
|
|
1390
|
-
case 'bits':
|
|
1391
|
-
console.print(base.RandBits(args.bits))
|
|
1392
|
-
case 'int':
|
|
1393
|
-
console.print(base.RandInt(_ParseInt(args.min), _ParseInt(args.max)))
|
|
1394
|
-
case 'bytes':
|
|
1395
|
-
console.print(base.BytesToHex(base.RandBytes(args.n)))
|
|
1396
|
-
case 'prime':
|
|
1397
|
-
console.print(modmath.NBitRandomPrimes(args.bits).pop())
|
|
1398
|
-
case _:
|
|
1399
|
-
raise NotImplementedError()
|
|
1400
|
-
case 'hash':
|
|
1401
|
-
hash_cmd: str = args.hash_command.lower().strip() if args.hash_command else ''
|
|
1402
|
-
match hash_cmd:
|
|
1403
|
-
case 'sha256':
|
|
1404
|
-
bt = _BytesFromText(args.data, in_format)
|
|
1405
|
-
digest: bytes = base.Hash256(bt)
|
|
1406
|
-
console.print(_BytesToText(digest, out_format))
|
|
1407
|
-
case 'sha512':
|
|
1408
|
-
bt = _BytesFromText(args.data, in_format)
|
|
1409
|
-
digest = base.Hash512(bt)
|
|
1410
|
-
console.print(_BytesToText(digest, out_format))
|
|
1411
|
-
case 'file':
|
|
1412
|
-
digest = base.FileHash(args.path, digest=args.digest)
|
|
1413
|
-
console.print(_BytesToText(digest, out_format))
|
|
1414
|
-
case _:
|
|
1415
|
-
raise NotImplementedError()
|
|
1416
|
-
|
|
1417
|
-
# -------- AES / RSA / El-Gamal / DSA / SSS ----------
|
|
1418
|
-
case 'aes':
|
|
1419
|
-
AESCommand(args, in_format, out_format, console)
|
|
1420
|
-
|
|
1421
|
-
case 'rsa':
|
|
1422
|
-
RSACommand(args, in_format, out_format, console)
|
|
1423
|
-
|
|
1424
|
-
case 'elgamal':
|
|
1425
|
-
ElGamalCommand(args, in_format, out_format, console)
|
|
1426
|
-
|
|
1427
|
-
case 'dsa':
|
|
1428
|
-
DSACommand(args, in_format, out_format, console)
|
|
1429
|
-
|
|
1430
|
-
case 'bid':
|
|
1431
|
-
BidCommand(args, in_format, out_format, console)
|
|
1432
|
-
|
|
1433
|
-
case 'sss':
|
|
1434
|
-
SSSCommand(args, in_format, out_format, console)
|
|
1435
|
-
|
|
1436
|
-
# -------- Documentation ----------
|
|
1437
|
-
case 'doc':
|
|
1438
|
-
doc_command: str = (
|
|
1439
|
-
args.doc_command.lower().strip() if getattr(args, 'doc_command', '') else '')
|
|
1440
|
-
match doc_command:
|
|
1441
|
-
case 'md':
|
|
1442
|
-
console.print(base.GenerateCLIMarkdown(
|
|
1443
|
-
'transcrypto', _BuildParser(), description=(
|
|
1444
|
-
'`transcrypto` is a command-line utility that provides access to all core '
|
|
1445
|
-
'functionality described in this documentation. It serves as a convenient '
|
|
1446
|
-
'wrapper over the Python APIs, enabling **cryptographic operations**, '
|
|
1447
|
-
'**number theory functions**, **secure randomness generation**, **hashing**, '
|
|
1448
|
-
'**AES**, **RSA**, **El-Gamal**, **DSA**, **bidding**, **SSS**, '
|
|
1449
|
-
'and other utilities without writing code.')))
|
|
1450
|
-
case _:
|
|
1451
|
-
raise NotImplementedError()
|
|
1452
|
-
|
|
1453
|
-
case _:
|
|
1454
|
-
parser.print_help()
|
|
1455
|
-
|
|
1456
|
-
except NotImplementedError as err:
|
|
1457
|
-
console.print(f'Invalid command: {err}')
|
|
1458
|
-
except (base.Error, ValueError) as err:
|
|
1459
|
-
console.print(str(err))
|
|
1460
|
-
|
|
1461
|
-
return 0
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
if __name__ == '__main__':
|
|
1465
|
-
sys.exit(main())
|
|
413
|
+
key_path: pathlib.Path | None = typer.Option( # noqa: B008
|
|
414
|
+
None,
|
|
415
|
+
'-p',
|
|
416
|
+
'--key-path',
|
|
417
|
+
resolve_path=True,
|
|
418
|
+
help='File path to serialized key object, if key is needed for operation',
|
|
419
|
+
),
|
|
420
|
+
protect: str | None = typer.Option(
|
|
421
|
+
None,
|
|
422
|
+
'-x',
|
|
423
|
+
'--protect',
|
|
424
|
+
help='Password to encrypt/decrypt key file if using the `-p`/`--key-path` option',
|
|
425
|
+
),
|
|
426
|
+
) -> None:
|
|
427
|
+
if version:
|
|
428
|
+
typer.echo(__version__)
|
|
429
|
+
raise typer.Exit(0)
|
|
430
|
+
console, verbose, color = clibase.InitLogging(
|
|
431
|
+
verbose,
|
|
432
|
+
color=color,
|
|
433
|
+
include_process=False,
|
|
434
|
+
)
|
|
435
|
+
# create context with the arguments we received.
|
|
436
|
+
ctx.obj = TransConfig(
|
|
437
|
+
console=console,
|
|
438
|
+
verbose=verbose,
|
|
439
|
+
color=color,
|
|
440
|
+
input_format=input_format,
|
|
441
|
+
output_format=output_format,
|
|
442
|
+
key_path=key_path,
|
|
443
|
+
protect=protect,
|
|
444
|
+
)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
@app.command(
|
|
448
|
+
'markdown',
|
|
449
|
+
help='Emit Markdown docs for the CLI (see README.md section "Creating a New Version").',
|
|
450
|
+
epilog=(
|
|
451
|
+
'Example:\n\n\n\n$ poetry run transcrypto markdown > transcrypto.md\n\n<<saves CLI doc>>'
|
|
452
|
+
),
|
|
453
|
+
)
|
|
454
|
+
@clibase.CLIErrorGuard
|
|
455
|
+
def Markdown(*, ctx: typer.Context) -> None: # documentation is help/epilog/args # noqa: D103
|
|
456
|
+
config: TransConfig = ctx.obj
|
|
457
|
+
config.console.print(clibase.GenerateTyperHelpMarkdown(app, prog_name='transcrypto'))
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
# Import CLI modules to register their commands with the app
|
|
461
|
+
from transcrypto.cli import aeshash, bidsecret, intmath, publicalgos # pyright: ignore[reportUnusedImport] # noqa: I001, E402, F401
|